You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2016/08/17 23:10:50 UTC
[01/24] incubator-geode git commit: GEODE-1782: include start
timestamp in stat resource equals
Repository: incubator-geode
Updated Branches:
refs/heads/feature/GEODE-1781-02 [created] 81c1c982e
GEODE-1782: include start timestamp in stat resource equals
* stat resources with different time stamps should not be equal
* StatArchiveWithConsecutiveResourceInstGenerator generates gfs with
multiple stat resources of same name but different times
* StatArchiveWithConsecutiveResourceInstIntegrationTest confirms
existence of bug GEODE-1782: StatArchiveReader ignores later stats
resource with same name as closed stats resource
* ResourceInstTest verifies the underlying issue and fix in
StatArchiveReader.ResourceInst.equals and the fix
Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/7dc1ce68
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/7dc1ce68
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/7dc1ce68
Branch: refs/heads/feature/GEODE-1781-02
Commit: 7dc1ce68a483f993adeb613893073d8a7c88a9b7
Parents: 1150701
Author: Kirk Lund <kl...@apache.org>
Authored: Mon Aug 15 18:35:45 2016 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Wed Aug 17 15:44:51 2016 -0700
----------------------------------------------------------------------
.../internal/statistics/StatArchiveReader.java | 3 +
.../internal/statistics/ResourceInstTest.java | 84 +++++++
...iveWithConsecutiveResourceInstGenerator.java | 223 +++++++++++++++++++
...ithConsecutiveResourceInstGeneratorTest.java | 55 +++++
...hConsecutiveResourceInstIntegrationTest.java | 108 +++++++++
.../gemfire/internal/statistics/StatUtils.java | 102 +++++++++
...thConsecutiveResourceInstIntegrationTest.gfs | Bin 0 -> 1924 bytes
7 files changed, 575 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7dc1ce68/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java
index 12637bc..e597b83 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java
@@ -2672,6 +2672,9 @@ public class StatArchiveReader implements StatArchiveFormat {
return false;
} else if (!type.equals(other.type))
return false;
+ if (this.firstTSidx != other.firstTSidx) {
+ return false;
+ }
return true;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7dc1ce68/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ResourceInstTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ResourceInstTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ResourceInstTest.java
new file mode 100644
index 0000000..9b697bd
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ResourceInstTest.java
@@ -0,0 +1,84 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.assertj.core.api.Assertions.*;
+import static org.mockito.MockitoAnnotations.*;
+
+import java.lang.reflect.Field;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.mockito.Mock;
+
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.ResourceInst;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.ResourceType;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatArchiveFile;
+import com.gemstone.gemfire.test.junit.categories.UnitTest;
+
+/**
+ * Unit tests for {@link ResourceInst}.
+ *
+ * <p>Confirms ResourceInst equals change to fix GEODE-1782.
+ *
+ * <p>GEODE-1782: StatArchiveReader ignores later stats resource with same name as closed stats resource
+ *
+ * @since Geode 1.0
+ */
+@Category(UnitTest.class)
+public class ResourceInstTest {
+
+ @Mock
+ private StatArchiveFile archive1;
+ @Mock
+ private StatArchiveFile archive2;
+ @Mock
+ private ResourceType resourceType;
+
+ @Before
+ public void setUp() throws Exception {
+ initMocks(this);
+ }
+
+ @Test
+ public void sameFirstTSidxEquals() throws Exception {
+ ResourceInst resourceInst1 = new ResourceInst(this.archive1, 0, "name", 0, this.resourceType, false);
+ setFirstTSidx(resourceInst1, 1);
+ ResourceInst resourceInst2 = new ResourceInst(this.archive1, 0, "name", 0, this.resourceType, false);
+ setFirstTSidx(resourceInst2, 1);
+
+ assertThat(resourceInst1).isEqualTo(resourceInst2);
+ }
+
+ @Test
+ public void differentFirstTSidxIsNotEqual() throws Exception {
+ ResourceInst resourceInst1 = new ResourceInst(this.archive1, 0, "name", 0, this.resourceType, false);
+ setFirstTSidx(resourceInst1, 1);
+ ResourceInst resourceInst2 = new ResourceInst(this.archive1, 0, "name", 0, this.resourceType, false);
+ setFirstTSidx(resourceInst2, 2);
+
+ assertThat(resourceInst1).isNotEqualTo(resourceInst2);
+ }
+
+ private void setFirstTSidx(ResourceInst resourceInst, int value) throws IllegalAccessException, NoSuchFieldException {
+ Field field = ResourceInst.class.getDeclaredField("firstTSidx");
+ field.setAccessible(true);
+ field.setInt(resourceInst, value);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7dc1ce68/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstGenerator.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstGenerator.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstGenerator.java
new file mode 100644
index 0000000..972e6702
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstGenerator.java
@@ -0,0 +1,223 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.gemstone.gemfire.internal.statistics.StatArchiveFormat.NANOS_PER_MILLI;
+import static com.gemstone.gemfire.internal.statistics.StatUtils.*;
+import static com.gemstone.gemfire.internal.statistics.TestStatArchiveWriter.*;
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.ResourceInst;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatValue;
+
+/**
+ * Generates the stat archive file that is committed under src/test/resources
+ * for {@link StatArchiveWithConsecutiveResourceInstIntegrationTest} to load.
+ *
+ * <p>The generated gfs file is used to confirm GEODE-1782 and its fix.
+ *
+ * @since Geode 1.0
+ */
+public class StatArchiveWithConsecutiveResourceInstGenerator {
+
+ private static final Logger logger = LogManager.getLogger();
+
+ protected static final String STATS_TYPE_NAME = "TestStats";
+ protected static final String STATS_SPEC_STRING = ":" + STATS_TYPE_NAME;
+
+ protected static final String TEST_NAME = StatArchiveWithConsecutiveResourceInstIntegrationTest.class.getSimpleName();
+ protected static final String ARCHIVE_FILE_NAME = TEST_NAME + ".gfs";
+
+ private File dir;
+ private Map<String,String> statisticTypes;
+ private Map<String,Map<String,Number>> allStatistics;
+ protected String archiveFileName;
+
+ private TestStatisticsManager manager;
+ private TestStatisticsSampler sampler;
+ private SampleCollector sampleCollector;
+ private StatArchiveWriter writer;
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUpGenerator() throws Exception {
+ this.statisticTypes = new HashMap<>();
+ this.allStatistics = new HashMap<>();
+ this.dir = this.temporaryFolder.getRoot();
+ this.archiveFileName = new File(this.dir.getAbsolutePath(), ARCHIVE_FILE_NAME).getAbsolutePath();
+
+ this.manager = new TestStatisticsManager(1, getUniqueName(), WRITER_INITIAL_DATE_MILLIS);
+ StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS - 2000)
+ .setSystemDirectoryPath(TEST_NAME)
+ .setProductDescription(TEST_NAME)
+ .build();
+ this.writer = new TestStatArchiveWriter(archiveDescriptor);
+ this.sampler = new TestStatisticsSampler(manager);
+ this.sampleCollector = new SampleCollector(sampler);
+ this.sampleCollector.addSampleHandler(this.writer);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ StatisticsTypeFactoryImpl.clear();
+ }
+
+ @Test
+ public void generateStatArchiveFile() throws Exception {
+
+ long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + NANOS_PER_MILLI*1000;
+
+ // 1) create statistics
+
+ StatisticsType type = createStatisticsType(STATS_TYPE_NAME, "description of " + STATS_TYPE_NAME);
+ Statistics statistics1 = createStatistics(type, STATS_TYPE_NAME + "1", 1);
+
+ // 2) sample changing stat
+
+ for (int i = 0; i < 100; i++) {
+ incInt(statistics1, "stat", 1);
+ this.sampleCollector.sample(sampleTimeNanos += (1000 * NANOS_PER_MILLI));
+ }
+
+ // 3) close statistics
+
+ statistics1.close();
+
+ // 4) recreate statistics
+
+ Statistics statistics2 = createStatistics(type, STATS_TYPE_NAME + "1", 1);
+
+ // 5) sample changing stat again
+
+ for (int i = 0; i < 100; i++) {
+ incInt(statistics2, "stat", 1);
+ this.sampleCollector.sample(sampleTimeNanos += (1000 * NANOS_PER_MILLI));
+ }
+
+ // close the writer
+
+ this.writer.close();
+
+ // validate that stat archive file exists
+
+ File actual = new File(this.archiveFileName);
+ assertTrue(actual.exists());
+
+ // validate content of stat archive file using StatArchiveReader
+
+ StatArchiveReader reader = new StatArchiveReader(new File[]{actual}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ for (final Iterator iter = reader.getResourceInstList().iterator(); iter.hasNext();) {
+ StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
+ String resourceName = ri.getName();
+ assertNotNull(resourceName);
+
+ String expectedStatsType = this.statisticTypes.get(resourceName);
+ assertNotNull(expectedStatsType);
+ assertEquals(expectedStatsType, ri.getType().getName());
+
+ Map<String,Number> expectedStatValues = this.allStatistics.get(resourceName);
+ assertNotNull(expectedStatValues);
+
+ StatValue[] statValues = ri.getStatValues();
+ for (int i = 0; i < statValues.length; i++) {
+ final String statName = ri.getType().getStats()[i].getName();
+ assertNotNull(statName);
+ assertNotNull(expectedStatValues.get(statName));
+
+ assertEquals(statName, statValues[i].getDescriptor().getName());
+
+ statValues[i].setFilter(StatValue.FILTER_NONE);
+ double[] rawSnapshots = statValues[i].getRawSnapshots();
+ assertEquals("Value " + i + " for " + statName + " is wrong: " + expectedStatValues,
+ expectedStatValues.get(statName).doubleValue(),
+ statValues[i].getSnapshotsMostRecent(), 0.01);
+ }
+ }
+
+ validateArchiveFile();
+ }
+
+ protected void validateArchiveFile() throws IOException {
+ final File archiveFile = new File(this.archiveFileName);
+ assertTrue(archiveFile.exists());
+
+ logger.info("ArchiveFile: {}", archiveFile.getAbsolutePath());
+ logger.info("ArchiveFile length: {}", archiveFile.length());
+
+ for (ResourceInst resourceInst: findResourceInsts(archiveFile, STATS_SPEC_STRING)) {
+ logger.info("ResourceInst: {}", resourceInst);
+ }
+ }
+
+ private String getUniqueName() {
+ return StatArchiveWithConsecutiveResourceInstGenerator.class + "_" + this.testName.getMethodName();
+ }
+
+ private StatisticsType createStatisticsType(final String name, final String description) {
+ StatisticDescriptor[] descriptors = new StatisticDescriptor[] {
+ manager.createIntCounter("stat", "description of stat", "units"),
+ };
+ return manager.createType(name, description, descriptors);
+ }
+
+ private Statistics createStatistics(final StatisticsType type, final String textId, final long numericId) {
+ return manager.createAtomicStatistics(type, textId, 1);
+ }
+
+ private void incInt(Statistics statistics, String stat, int value) {
+ assertFalse(statistics.isClosed());
+ Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
+ if (statValues == null) {
+ statValues = new HashMap<>();
+ this.allStatistics.put(statistics.getTextId(), statValues);
+ }
+ statistics.incInt(stat, value);
+ statValues.put(stat, statistics.getInt(stat));
+ if (this.statisticTypes.get(statistics.getTextId()) == null) {
+ this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7dc1ce68/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstGeneratorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstGeneratorTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstGeneratorTest.java
new file mode 100644
index 0000000..1e4554e
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstGeneratorTest.java
@@ -0,0 +1,55 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.gemstone.gemfire.internal.statistics.StatUtils.*;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+
+import org.apache.commons.io.FileUtils;
+import org.junit.Before;
+import org.junit.experimental.categories.Category;
+
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+
+/**
+ * Compares the output results of {@link StatArchiveWithConsecutiveResourceInstGenerator} against the saved stat
+ * archive file in src/test/resources that is used by {@link StatArchiveWithConsecutiveResourceInstIntegrationTest}.
+ *
+ * @since Geode 1.0
+ */
+@Category(IntegrationTest.class)
+public class StatArchiveWithConsecutiveResourceInstGeneratorTest extends StatArchiveWithConsecutiveResourceInstGenerator {
+
+ private File expectedStatArchiveFile;
+
+ @Before
+ public void setUpGeneratorTest() throws Exception {
+ URL url = getClass().getResource(ARCHIVE_FILE_NAME);
+ File testFolder = this.temporaryFolder.newFolder(getClass().getSimpleName());
+ this.expectedStatArchiveFile = new File(testFolder, ARCHIVE_FILE_NAME);
+ FileUtils.copyURLToFile(url, this.expectedStatArchiveFile);
+ }
+
+ @Override
+ protected void validateArchiveFile() throws IOException {
+ compareStatArchiveFiles(this.expectedStatArchiveFile, new File(this.archiveFileName));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7dc1ce68/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstIntegrationTest.java
new file mode 100644
index 0000000..e272fec
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstIntegrationTest.java
@@ -0,0 +1,108 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.gemstone.gemfire.internal.statistics.StatArchiveWithConsecutiveResourceInstGenerator.*;
+import static org.assertj.core.api.Assertions.*;
+
+import java.io.File;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.internal.SystemAdmin.StatSpec;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.ResourceInst;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatValue;
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+
+/**
+ * Confirms existence of GEODE-1782 and its fix.
+ *
+ * <p>GEODE-1782: StatArchiveReader ignores later stats resource with same name as closed stats resource
+ *
+ * @since Geode 1.0
+ */
+@Category(IntegrationTest.class)
+public class StatArchiveWithConsecutiveResourceInstIntegrationTest {
+
+ private static final Logger logger = LogManager.getLogger();
+
+ private File archiveFile;
+ private StatSpec statSpec;
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUp() throws Exception {
+ URL url = getClass().getResource(ARCHIVE_FILE_NAME);
+ this.archiveFile = this.temporaryFolder.newFile(ARCHIVE_FILE_NAME);
+ FileUtils.copyURLToFile(url, archiveFile);
+
+ this.statSpec = new StatSpec(STATS_SPEC_STRING);
+
+ // precondition
+ assertThat(this.archiveFile).exists();
+ }
+
+ @Test
+ public void readingFourActiveCacheClientUpdaterStatsWithReaderMatchSpec() throws Exception {
+ StatArchiveReader reader = new StatArchiveReader(new File[] {this.archiveFile}, new StatSpec[] {this.statSpec }, true);
+
+ Set<ResourceInst> resourceInstList = new HashSet<>();
+ for (StatValue statValue: reader.matchSpec(this.statSpec)) {
+ for (int i = 0; i < statValue.getResources().length; i++) {
+ resourceInstList.add(statValue.getResources()[i]);
+ }
+ }
+
+ assertThat(resourceInstList.size()).isEqualTo(2);
+ }
+
+ @Test
+ public void readingFourActiveCacheClientUpdaterStatsWithReader() throws Exception {
+ StatArchiveReader reader = new StatArchiveReader(new File[] {this.archiveFile}, new StatSpec[]{this.statSpec }, true);
+
+ Set<ResourceInst> resourceInstList = new HashSet<>();
+ for (Iterator<ResourceInst> it = reader.getResourceInstList().iterator(); it.hasNext();) {
+ resourceInstList.add(it.next());
+ }
+
+ assertThat(resourceInstList.size()).isEqualTo(2);
+ }
+
+ private void printResourceInsts(Set<ResourceInst> resourceInstList) {
+ for (ResourceInst resourceInst : resourceInstList) {
+ logger.info(this.testName.getMethodName() + ":ResourceInst: {}", resourceInst);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7dc1ce68/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatUtils.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatUtils.java
new file mode 100644
index 0000000..1ffbd6f
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatUtils.java
@@ -0,0 +1,102 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.assertj.core.api.Assertions.*;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.apache.commons.lang.StringUtils;
+
+import com.gemstone.gemfire.internal.SystemAdmin.StatSpec;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.ResourceInst;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatValue;
+
+/**
+ * @since Geode 1.0
+ */
+public class StatUtils {
+
+ /**
+ * final File expectedStatArchiveFile = new File(TestUtil.getResourcePath(getClass(), "StatArchiveWriterReaderJUnitTest_" + this.testName.getMethodName() + "_expected.gfs"));
+ */
+ public static void compareStatArchiveFiles(final File expectedStatArchiveFile, final File actualStatArchiveFile) throws IOException {
+ assertThat(expectedStatArchiveFile).exists();
+ assertThat(actualStatArchiveFile.length()).isEqualTo(expectedStatArchiveFile.length());
+
+ assertThat(readBytes(actualStatArchiveFile)).isEqualTo(readBytes(expectedStatArchiveFile));
+ }
+
+ public static Set<ResourceInst> findResourceInsts(final File archiveFile, final String specString) throws IOException {
+ Set<ResourceInst> resourceInsts = new HashSet<>();
+
+ if (StringUtils.isNotEmpty(specString)) {
+ addResourceInstsToSet(archiveFile, specString, resourceInsts);
+ } else {
+ addResourceInstsToSet(archiveFile, resourceInsts);
+ }
+
+ return resourceInsts;
+ }
+
+ private static void addResourceInstsToSet(final File archiveFile, final Set<ResourceInst> resourceInsts) throws IOException {
+ StatArchiveReader reader = new StatArchiveReader(new File[] {archiveFile}, new StatSpec[]{}, true);
+
+ for (Iterator<ResourceInst> it = reader.getResourceInstList().iterator(); it.hasNext();) {
+ resourceInsts.add(it.next());
+ }
+ }
+
+ private static void addResourceInstsToSet(final File archiveFile, final String specString, final Set<ResourceInst> resourceInsts) throws IOException {
+ StatSpec statSpec = new StatSpec(specString);
+
+ StatArchiveReader reader = new StatArchiveReader(new File[] { archiveFile }, new StatSpec[] { statSpec }, true);
+ StatValue[] statValues = reader.matchSpec(statSpec);
+
+ for (StatValue statValue : statValues) {
+ for (ResourceInst resourceInst : statValue.getResources()) {
+ resourceInsts.add(resourceInst);
+ }
+ }
+ }
+
+ private static byte[] readBytes(File file) throws IOException {
+ int byteCount = (int)file.length();
+
+ byte[] input = new byte[byteCount];
+
+ URL url = file.toURL();
+ assertThat(url).isNotNull();
+
+ InputStream is = url.openStream();
+ assertThat(is).isNotNull();
+
+ BufferedInputStream bis = new BufferedInputStream(is);
+ int bytesRead = bis.read(input);
+ bis.close();
+
+ assertThat(bytesRead).isEqualTo(byteCount);
+ return input;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/7dc1ce68/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstIntegrationTest.gfs
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstIntegrationTest.gfs b/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstIntegrationTest.gfs
new file mode 100644
index 0000000..943f6d9
Binary files /dev/null and b/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWithConsecutiveResourceInstIntegrationTest.gfs differ
[03/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsDistributedTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsDistributedTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsDistributedTest.java
new file mode 100755
index 0000000..21a8ee0
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsDistributedTest.java
@@ -0,0 +1,851 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.jayway.awaitility.Awaitility.*;
+import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
+import static com.gemstone.gemfire.test.dunit.Assert.*;
+import static com.gemstone.gemfire.test.dunit.Host.*;
+import static com.gemstone.gemfire.test.dunit.Invoke.*;
+import static java.util.concurrent.TimeUnit.*;
+
+import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.atomic.AtomicReferenceArray;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsFactory;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.StatisticsTypeFactory;
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.CacheListener;
+import com.gemstone.gemfire.cache.EntryEvent;
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.RegionEvent;
+import com.gemstone.gemfire.cache.RegionFactory;
+import com.gemstone.gemfire.cache.Scope;
+import com.gemstone.gemfire.cache.util.CacheListenerAdapter;
+import com.gemstone.gemfire.cache.util.RegionMembershipListenerAdapter;
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
+import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
+import com.gemstone.gemfire.internal.NanoTimer;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.ResourceInst;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatSpec;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatValue;
+import com.gemstone.gemfire.test.dunit.AsyncInvocation;
+import com.gemstone.gemfire.test.dunit.VM;
+import com.gemstone.gemfire.test.dunit.cache.internal.JUnit4CacheTestCase;
+import com.gemstone.gemfire.test.junit.categories.DistributedTest;
+import com.gemstone.gemfire.test.junit.rules.serializable.SerializableTemporaryFolder;
+
+/**
+ * Distributed tests for {@link Statistics}.
+ *
+ * <p>VM0 performs puts and VM1 receives updates. Both use custom statistics for start/end with increment to add up puts
+ * and updates. Then validation tests values in stat resource instances and uses StatArchiveReader. Both are tested
+ * against static counters in both VMs.
+ *
+ * <p>This test mimics hydratest/locators/cacheDS.conf in an attempt to reproduce bug #45478. So far this test passes
+ * consistently.
+ *
+ * @since GemFire 7.0
+ */
+@Category(DistributedTest.class)
+@SuppressWarnings({ "rawtypes", "serial", "unused" })
+public class StatisticsDistributedTest extends JUnit4CacheTestCase {
+
+ private static final int MAX_PUTS = 1000;
+ private static final int NUM_KEYS = 100;
+ private static final int NUM_PUB_THREADS = 2;
+ private static final int NUM_PUBS = 2;
+ private static final boolean RANDOMIZE_PUTS = true;
+
+ private static AtomicInteger updateEvents = new AtomicInteger();
+ private static AtomicInteger puts = new AtomicInteger();
+ private static AtomicReference<PubSubStats> subStatsRef = new AtomicReference<>();
+ private static AtomicReferenceArray<PubSubStats> pubStatsRef = new AtomicReferenceArray<>(NUM_PUB_THREADS);
+ private static AtomicReference<RegionMembershipListener> rmlRef = new AtomicReference<>();
+
+ private File directory;
+
+ @Rule
+ public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
+
+ @Override
+ public final void postSetUp() throws Exception {
+ this.directory = this.temporaryFolder.getRoot();
+ }
+
+ @Override
+ public final void preTearDownCacheTestCase() throws Exception {
+ invokeInEveryVM(() -> cleanup());
+ disconnectAllFromDS(); // because this test enabled stat sampling!
+ }
+
+ @Test
+ public void testPubAndSubCustomStats() throws Exception {
+ String regionName = "region_" + getName();
+ VM[] pubs = new VM[NUM_PUBS];
+ for (int pubVM = 0; pubVM < NUM_PUBS; pubVM++) {
+ pubs[pubVM] = getHost(0).getVM(pubVM);
+ }
+ VM sub = getHost(0).getVM(NUM_PUBS);
+
+ String subArchive = this.directory.getAbsolutePath() + File.separator + getName() + "_sub" + ".gfs";
+ String[] pubArchives = new String[NUM_PUBS];
+ for (int pubVM = 0; pubVM < NUM_PUBS; pubVM++) {
+ pubArchives[pubVM] = this.directory.getAbsolutePath() + File.separator + getName() + "_pub-" + pubVM + ".gfs";
+ }
+
+ for (int i = 0; i < NUM_PUBS; i++) {
+ final int pubVM = i;
+ pubs[pubVM].invoke("pub-connect-and-create-data-" + pubVM, () -> {
+ Properties props = new Properties();
+ props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
+ props.setProperty(STATISTIC_SAMPLE_RATE, "1000");
+ props.setProperty(STATISTIC_ARCHIVE_FILE, pubArchives[pubVM]);
+
+ InternalDistributedSystem system = getSystem(props);
+
+ // assert that sampler is working as expected
+ GemFireStatSampler sampler = system.getStatSampler();
+ assertTrue(sampler.isSamplingEnabled());
+ assertTrue(sampler.isAlive());
+ assertEquals(new File(pubArchives[pubVM]), sampler.getArchiveFileName());
+
+ await("awaiting SampleCollector to exist").atMost(30, SECONDS).until(() -> sampler.getSampleCollector() != null);
+
+ SampleCollector sampleCollector = sampler.getSampleCollector();
+ assertNotNull(sampleCollector);
+
+ StatArchiveHandler archiveHandler = sampleCollector.getStatArchiveHandler();
+ assertNotNull(archiveHandler);
+ assertTrue(archiveHandler.isArchiving());
+
+ // create cache and region
+ Cache cache = getCache();
+ RegionFactory<String, Number> factory = cache.createRegionFactory();
+ factory.setScope(Scope.DISTRIBUTED_ACK);
+
+ RegionMembershipListener rml = new RegionMembershipListener();
+ rmlRef.set(rml);
+ factory.addCacheListener(rml);
+ Region<String, Number> region = factory.create(regionName);
+
+ // create the keys
+ if (region.getAttributes().getScope() == Scope.DISTRIBUTED_ACK) {
+ for (int key = 0; key < NUM_KEYS; key++) {
+ region.create("KEY-"+key, null);
+ }
+ }
+ });
+ }
+
+ DistributedMember subMember = sub.invoke("sub-connect-and-create-keys", () -> {
+ Properties props = new Properties();
+ props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
+ props.setProperty(STATISTIC_SAMPLE_RATE, "1000");
+ props.setProperty(STATISTIC_ARCHIVE_FILE, subArchive);
+
+ InternalDistributedSystem system = getSystem(props);
+
+ PubSubStats statistics = new PubSubStats(system, "sub-1", 1);
+ subStatsRef.set(statistics);
+
+ // assert that sampler is working as expected
+ GemFireStatSampler sampler = system.getStatSampler();
+ assertTrue(sampler.isSamplingEnabled());
+ assertTrue(sampler.isAlive());
+ assertEquals(new File(subArchive), sampler.getArchiveFileName());
+
+ await("awaiting SampleCollector to exist").atMost(30, SECONDS).until(() -> sampler.getSampleCollector() != null);
+
+ SampleCollector sampleCollector = sampler.getSampleCollector();
+ assertNotNull(sampleCollector);
+
+ StatArchiveHandler archiveHandler = sampleCollector.getStatArchiveHandler();
+ assertNotNull(archiveHandler);
+ assertTrue(archiveHandler.isArchiving());
+
+ // create cache and region with UpdateListener
+ Cache cache = getCache();
+ RegionFactory<String, Number> factory = cache.createRegionFactory();
+ factory.setScope(Scope.DISTRIBUTED_ACK);
+
+ CacheListener<String, Number> cl = new UpdateListener(statistics);
+ factory.addCacheListener(cl);
+ Region<String, Number> region = factory.create(regionName);
+
+ // create the keys
+ if (region.getAttributes().getScope() == Scope.DISTRIBUTED_ACK) {
+ for (int key = 0; key < NUM_KEYS; key++) {
+ region.create("KEY-"+key, null);
+ }
+ }
+
+ assertEquals(0, statistics.getUpdateEvents());
+ return system.getDistributedMember();
+ });
+
+ for (int i = 0; i < NUM_PUBS; i++) {
+ final int pubVM = i;
+ AsyncInvocation[] publishers = new AsyncInvocation[NUM_PUB_THREADS];
+ for (int j = 0; j < NUM_PUB_THREADS; j++) {
+ final int pubThread = j;
+ publishers[pubThread] = pubs[pubVM].invokeAsync("pub-connect-and-put-data-" + pubVM + "-thread-" + pubThread, () -> {
+ PubSubStats statistics = new PubSubStats(basicGetSystem(), "pub-" + pubThread, pubVM);
+ pubStatsRef.set(pubThread, statistics);
+
+ RegionMembershipListener rml = rmlRef.get();
+ Region<String, Number> region = getCache().getRegion(regionName);
+
+ // assert that sub is in rml membership
+ assertNotNull(rml);
+
+ await("awaiting Membership to contain subMember").atMost(30, SECONDS).until(() -> rml.contains(subMember) && rml.size() == NUM_PUBS);
+
+ // publish lots of puts cycling through the NUM_KEYS
+ assertEquals(0, statistics.getPuts());
+
+ // cycle through the keys randomly
+ if (RANDOMIZE_PUTS) {
+ Random randomGenerator = new Random();
+ int key = 0;
+ for (int idx = 0; idx < MAX_PUTS; idx++) {
+ long start = statistics.startPut();
+ key = randomGenerator.nextInt(NUM_KEYS);
+ region.put("KEY-"+key, idx);
+ statistics.endPut(start);
+ }
+
+ // cycle through he keys in order and wrapping back around
+ } else {
+ int key = 0;
+ for (int idx = 0; idx < MAX_PUTS; idx++) {
+ long start = statistics.startPut();
+ region.put("KEY-"+key, idx);
+ key++; // cycle through the keys...
+ if (key >= NUM_KEYS) {
+ key = 0;
+ }
+ statistics.endPut(start);
+ }
+ }
+ assertEquals(MAX_PUTS, statistics.getPuts());
+
+ // wait for 2 samples to ensure all stats have been archived
+ StatisticsType statSamplerType = getSystem().findType("StatSampler");
+ Statistics[] statsArray = getSystem().findStatisticsByType(statSamplerType);
+ assertEquals(1, statsArray.length);
+
+ Statistics statSamplerStats = statsArray[0];
+ int initialSampleCount = statSamplerStats.getInt(StatSamplerStats.SAMPLE_COUNT);
+
+ await("awaiting sampleCount >= 2").atMost(30, SECONDS).until(() -> statSamplerStats.getInt(StatSamplerStats.SAMPLE_COUNT) >= initialSampleCount + 2);
+ });
+ }
+
+ for (int pubThread = 0; pubThread < publishers.length; pubThread++) {
+ publishers[pubThread].join();
+ if (publishers[pubThread].exceptionOccurred()) {
+ fail("Test failed", publishers[pubThread].getException());
+ }
+ }
+ }
+
+ sub.invoke("sub-wait-for-samples", () -> {
+ // wait for 2 samples to ensure all stats have been archived
+ StatisticsType statSamplerType = getSystem().findType("StatSampler");
+ Statistics[] statsArray = getSystem().findStatisticsByType(statSamplerType);
+ assertEquals(1, statsArray.length);
+
+ Statistics statSamplerStats = statsArray[0];
+ int initialSampleCount = statSamplerStats.getInt(StatSamplerStats.SAMPLE_COUNT);
+
+ await("awaiting sampleCount >= 2").atMost(30, SECONDS).until(() -> statSamplerStats.getInt(StatSamplerStats.SAMPLE_COUNT) >= initialSampleCount + 2);
+
+ // now post total updateEvents to static
+ PubSubStats statistics = subStatsRef.get();
+ assertNotNull(statistics);
+ updateEvents.set(statistics.getUpdateEvents());
+ });
+
+ // validate pub values against sub values
+ int totalUpdateEvents = sub.invoke(() -> getUpdateEvents());
+
+ // validate pub values against pub statistics against pub archive
+ for (int i = 0; i < NUM_PUBS; i++) {
+ final int pubIdx = i;
+ pubs[pubIdx].invoke("pub-validation", () -> {
+ // add up all the puts
+ assertEquals(NUM_PUB_THREADS, pubStatsRef.length());
+ int totalPuts = 0;
+ for (int pubThreadIdx = 0; pubThreadIdx < NUM_PUB_THREADS; pubThreadIdx++) {
+ PubSubStats statistics = pubStatsRef.get(pubThreadIdx);
+ assertNotNull(statistics);
+ totalPuts += statistics.getPuts();
+ }
+
+ // assert that total puts adds up to max puts times num threads
+ assertEquals(MAX_PUTS * NUM_PUB_THREADS, totalPuts);
+
+ // assert that archive file contains same values as statistics
+ File archive = new File(pubArchives[pubIdx]);
+ assertTrue(archive.exists());
+
+ StatArchiveReader reader = new StatArchiveReader(new File[]{archive}, null, false);
+
+ double combinedPuts = 0;
+
+ List resources = reader.getResourceInstList();
+ assertNotNull(resources);
+ assertFalse(resources.isEmpty());
+
+ for (Iterator<ResourceInst> iter = resources.iterator(); iter.hasNext();) {
+ ResourceInst ri = iter.next();
+ if (!ri.getType().getName().equals(PubSubStats.TYPE_NAME)) {
+ continue;
+ }
+
+ StatValue[] statValues = ri.getStatValues();
+ for (int idx = 0; idx < statValues.length; idx++) {
+ String statName = ri.getType().getStats()[idx].getName();
+ assertNotNull(statName);
+
+ if (statName.equals(PubSubStats.PUTS)) {
+ StatValue sv = statValues[idx];
+ sv.setFilter(StatValue.FILTER_NONE);
+
+ double mostRecent = sv.getSnapshotsMostRecent();
+ double min = sv.getSnapshotsMinimum();
+ double max = sv.getSnapshotsMaximum();
+ double maxMinusMin = sv.getSnapshotsMaximum() - sv.getSnapshotsMinimum();
+ double mean = sv.getSnapshotsAverage();
+ double stdDev = sv.getSnapshotsStandardDeviation();
+
+ assertEquals(mostRecent, max, 0f);
+
+ double summation = 0;
+ double[] rawSnapshots = sv.getRawSnapshots();
+ for (int j = 0; j < rawSnapshots.length; j++) {
+ summation += rawSnapshots[j];
+ }
+ assertEquals(mean, summation / sv.getSnapshotsSize(), 0);
+
+ combinedPuts += mostRecent;
+ }
+ }
+ }
+
+ // assert that sum of mostRecent values for all puts equals totalPuts
+ assertEquals((double)totalPuts, combinedPuts, 0);
+ puts.getAndAdd(totalPuts);
+ });
+ }
+
+ // validate pub values against sub values
+ int totalCombinedPuts = 0;
+ for (int i = 0; i < NUM_PUBS; i++) {
+ int pubIdx = i;
+ int totalPuts = pubs[pubIdx].invoke(() -> getPuts());
+ assertEquals(MAX_PUTS * NUM_PUB_THREADS, totalPuts);
+ totalCombinedPuts += totalPuts;
+ }
+ assertEquals(totalCombinedPuts, totalUpdateEvents);
+ assertEquals(MAX_PUTS * NUM_PUB_THREADS * NUM_PUBS, totalCombinedPuts);
+
+ // validate sub values against sub statistics against sub archive
+ final int totalPuts = totalCombinedPuts;
+ sub.invoke("sub-validation", () -> {
+ PubSubStats statistics = subStatsRef.get();
+ assertNotNull(statistics);
+ int updateEvents = statistics.getUpdateEvents();
+ assertEquals(totalPuts, updateEvents);
+ assertEquals(totalUpdateEvents, updateEvents);
+ assertEquals(MAX_PUTS * NUM_PUB_THREADS * NUM_PUBS, updateEvents);
+
+ // assert that archive file contains same values as statistics
+ File archive = new File(subArchive);
+ assertTrue(archive.exists());
+
+ StatArchiveReader reader = new StatArchiveReader(new File[]{archive}, null, false);
+
+ double combinedUpdateEvents = 0;
+
+ List resources = reader.getResourceInstList();
+ for (Iterator<ResourceInst> iter = resources.iterator(); iter.hasNext();) {
+ ResourceInst ri = iter.next();
+ if (!ri.getType().getName().equals(PubSubStats.TYPE_NAME)) {
+ continue;
+ }
+
+ StatValue[] statValues = ri.getStatValues();
+ for (int i = 0; i < statValues.length; i++) {
+ String statName = ri.getType().getStats()[i].getName();
+ assertNotNull(statName);
+
+ if (statName.equals(PubSubStats.UPDATE_EVENTS)) {
+ StatValue sv = statValues[i];
+ sv.setFilter(StatValue.FILTER_NONE);
+
+ double mostRecent = sv.getSnapshotsMostRecent();
+ double min = sv.getSnapshotsMinimum();
+ double max = sv.getSnapshotsMaximum();
+ double maxMinusMin = sv.getSnapshotsMaximum() - sv.getSnapshotsMinimum();
+ double mean = sv.getSnapshotsAverage();
+ double stdDev = sv.getSnapshotsStandardDeviation();
+
+ assertEquals(mostRecent, max,0);
+
+ double summation = 0;
+ double[] rawSnapshots = sv.getRawSnapshots();
+ for (int j = 0; j < rawSnapshots.length; j++) {
+ summation += rawSnapshots[j];
+ }
+ assertEquals(mean, summation / sv.getSnapshotsSize(),0);
+
+ combinedUpdateEvents += mostRecent;
+ }
+ }
+ }
+ assertEquals((double)totalUpdateEvents, combinedUpdateEvents,0);
+ });
+
+ int updateEvents = sub.invoke(() -> readIntStat(new File(subArchive), "PubSubStats", "updateEvents"));
+ assertTrue(updateEvents > 0);
+ assertEquals(MAX_PUTS * NUM_PUB_THREADS * NUM_PUBS, updateEvents);
+
+ int puts = 0;
+ for (int pubVM = 0; pubVM < NUM_PUBS; pubVM++) {
+ int currentPubVM = pubVM;
+ int vmPuts = pubs[pubVM].invoke(() -> readIntStat(new File(pubArchives[currentPubVM]), "PubSubStats", "puts"));
+ assertTrue(vmPuts > 0);
+ assertEquals(MAX_PUTS * NUM_PUB_THREADS, vmPuts);
+ puts += vmPuts;
+ }
+ assertTrue(puts > 0);
+ assertEquals(MAX_PUTS * NUM_PUB_THREADS * NUM_PUBS, puts);
+
+ // use regex "testPubAndSubCustomStats"
+
+ MultipleArchiveReader reader = new MultipleArchiveReader(this.directory, ".*" + getTestMethodName() + ".*\\.gfs");
+
+ int combinedUpdateEvents = reader.readIntStat(PubSubStats.TYPE_NAME, PubSubStats.UPDATE_EVENTS);
+ assertTrue("Failed to read updateEvents stat values", combinedUpdateEvents > 0);
+
+ int combinedPuts = reader.readIntStat(PubSubStats.TYPE_NAME, PubSubStats.PUTS);
+ assertTrue("Failed to read puts stat values", combinedPuts > 0);
+
+ assertTrue("updateEvents is " + combinedUpdateEvents + " but puts is " + combinedPuts,
+ combinedUpdateEvents == combinedPuts);
+ }
+
+ static int readIntStat(final File archive, final String typeName, final String statName) throws IOException {
+ MultipleArchiveReader reader = new MultipleArchiveReader(archive);
+ return reader.readIntStat(typeName, statName);
+ }
+
+ /** invoked by reflection */
+ private static void cleanup() {
+ updateEvents.set(0);
+ rmlRef.set(null);
+ }
+
+ /** invoked by reflection */
+ private static int getUpdateEvents() {
+ return updateEvents.get();
+ }
+
+ /** invoked by reflection */
+ private static int getPuts() {
+ return puts.get();
+ }
+
+ public static void main(final String[] args) throws Exception {
+ if (args.length == 2) {
+ final String statType = args[0];
+ final String statName = args[1];
+
+ MultipleArchiveReader reader = new MultipleArchiveReader(new File("."));
+ int value = reader.readIntStat(statType, statName);
+ System.out.println(statType + "#" + statName + "=" + value);
+
+ } else if (args.length == 3) {
+ final String archiveName = args[0];
+ final String statType = args[1];
+ final String statName = args[2];
+
+ File archive = new File(archiveName).getAbsoluteFile();
+ assertTrue("File " + archive + " does not exist!", archive.exists());
+ assertTrue(archive + " exists but is not a file!", archive.isFile());
+
+ MultipleArchiveReader reader = new MultipleArchiveReader(archive);
+ int value = reader.readIntStat(statType, statName);
+ System.out.println(archive + ": " + statType + "#" + statName + "=" + value);
+
+ } else if (args.length == 4) {
+ final String statType1 = args[0];
+ final String statName1 = args[1];
+ final String statType2 = args[2];
+ final String statName2 = args[3];
+
+ MultipleArchiveReader reader = new MultipleArchiveReader(new File("."));
+ int value1 = reader.readIntStat(statType1, statName1);
+ int value2 = reader.readIntStat(statType2, statName2);
+
+ assertTrue(statType1 + "#" + statName1 + "=" + value1 + " does not equal " + statType2 + "#" + statName2 + "=" + value2,
+ value1 == value2);
+ } else {
+ assertEquals("Minimum two args are required: statType statName", 2, args.length);
+ }
+ }
+
+ /**
+ * @since GemFire 7.0
+ */
+ static class PubSubStats {
+
+ private static final String TYPE_NAME = "PubSubStats";
+ private static final String TYPE_DESCRIPTION = "Statistics for StatisticsDistributedTest with Pub/Sub.";
+
+ private static final String INSTANCE_PREFIX = "pubSubStats_";
+
+ private static final String PUTS = "puts";
+ private static final String PUT_TIME = "putTime";
+
+ private static final String UPDATE_EVENTS = "updateEvents";
+
+ private static StatisticsType createType(final StatisticsFactory f) {
+ StatisticsTypeFactory stf = StatisticsTypeFactoryImpl.singleton();
+ StatisticsType type = stf.createType(TYPE_NAME, TYPE_DESCRIPTION, createDescriptors(f));
+ return type;
+ }
+
+ private static StatisticDescriptor[] createDescriptors(final StatisticsFactory f) {
+ boolean largerIsBetter = true;
+ return new StatisticDescriptor[] {
+ f.createIntCounter
+ (
+ PUTS,
+ "Number of puts completed.",
+ "operations",
+ largerIsBetter
+ ),
+ f.createLongCounter
+ (
+ PUT_TIME,
+ "Total time spent doing puts.",
+ "nanoseconds",
+ !largerIsBetter
+ ),
+ f.createIntCounter
+ (
+ UPDATE_EVENTS,
+ "Number of update events.",
+ "events",
+ largerIsBetter
+ )
+ };
+ }
+
+ private final Statistics statistics;
+
+ PubSubStats(final StatisticsFactory f, final String name, final int id) {
+ this.statistics = f.createAtomicStatistics(createType(f), INSTANCE_PREFIX + "_" + name, id);
+ }
+
+ Statistics statistics() {
+ return this.statistics;
+ }
+
+ void close() {
+ this.statistics.close();
+ }
+
+ int getUpdateEvents() {
+ return statistics().getInt(UPDATE_EVENTS);
+ }
+
+ void incUpdateEvents() {
+ incUpdateEvents(1);
+ }
+
+ void incUpdateEvents(final int amount) {
+ incStat(UPDATE_EVENTS, amount);
+ }
+
+ int getPuts() {
+ return statistics().getInt(PUTS);
+ }
+
+ void incPuts() {
+ incPuts(1);
+ }
+
+ void incPuts(final int amount) {
+ incStat(PUTS, amount);
+ }
+
+ void incPutTime(final long amount) {
+ incStat(PUT_TIME, amount);
+ }
+
+ long startPut() {
+ return NanoTimer.getTime();
+ }
+
+ void endPut(final long start) {
+ endPut(start, 1);
+ }
+
+ void endPut(final long start, final int amount) {
+ long elapsed = NanoTimer.getTime() - start;
+ incPuts(amount);
+ incPutTime(elapsed);
+ }
+
+ private void incStat(final String statName, final int intValue) {
+ statistics().incInt(statName, intValue);
+ }
+
+ private void incStat(final String statName, final long longValue) {
+ statistics().incLong(statName, longValue);
+ }
+ }
+
+ /**
+ * @since GemFire 7.0
+ */
+ static class UpdateListener extends CacheListenerAdapter<String, Number> {
+
+ private final PubSubStats statistics;
+
+ UpdateListener(final PubSubStats statistics) {
+ this.statistics = statistics;
+ }
+
+ @Override
+ public void afterUpdate(final EntryEvent<String, Number> event) {
+ this.statistics.incUpdateEvents( 1 );
+ }
+ }
+
+ /**
+ * @since GemFire 7.0
+ */
+ static class RegionMembershipListener extends RegionMembershipListenerAdapter<String, Number> {
+
+ private final List<DistributedMember> members = new ArrayList<>();
+
+ int size() {
+ return this.members.size();
+ }
+
+ List<DistributedMember> getMembers() {
+ return Collections.unmodifiableList(new ArrayList<>(this.members));
+ }
+
+ boolean containsId(final DistributedMember member) {
+ for (DistributedMember peer : getMembers()) {
+ if (peer.getId().equals(member.getId())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ boolean contains(final DistributedMember member) {
+ return this.members.contains(member);
+ }
+
+ String debugContains(final DistributedMember member) {
+ StringBuilder sb = new StringBuilder();
+ for (DistributedMember peer : getMembers()) {
+ if (!peer.equals(member)) {
+ InternalDistributedMember peerIDM = (InternalDistributedMember)peer;
+ InternalDistributedMember memberIDM = (InternalDistributedMember)member;
+ sb.append("peer port=").append(peerIDM.getPort()).append(" ");
+ sb.append("member port=").append(memberIDM.getPort()).append(" ");
+ }
+ }
+ return sb.toString();
+ }
+
+ @Override
+ public void initialMembers(final Region<String, Number> region, final DistributedMember[] initialMembers) {
+ for (int i = 0; i < initialMembers.length; i++) {
+ this.members.add(initialMembers[i]);
+ }
+ }
+
+ @Override
+ public void afterRemoteRegionCreate(final RegionEvent<String, Number> event) {
+ this.members.add(event.getDistributedMember());
+ }
+
+ @Override
+ public void afterRemoteRegionDeparture(final RegionEvent<String, Number> event) {
+ this.members.remove(event.getDistributedMember());
+ }
+
+ @Override
+ public void afterRemoteRegionCrash(final RegionEvent<String, Number> event) {
+ this.members.remove(event.getDistributedMember());
+ }
+ }
+
+ static class MultipleArchiveReader {
+
+ private final File dir;
+ private final String regex;
+
+ MultipleArchiveReader(final File dir, final String regex) {
+ this.dir = dir;
+ this.regex = regex;
+ }
+
+ MultipleArchiveReader(final File dir) {
+ this.dir = dir;
+ this.regex = null;
+ }
+
+ int readIntStat(final String typeName, final String statName) throws IOException {
+ // directory (maybe directories) with one or more archives
+ if (this.dir.exists() && this.dir.isDirectory()) {
+ List<File> archives = findFilesWithSuffix(this.dir, this.regex, ".gfs");
+ return readIntStatFromArchives(archives, typeName, statName);
+
+ // one archive file
+ } else if (this.dir.exists() && this.dir.isFile()) {
+ List<File> archives = new ArrayList<File>();
+ archives.add(this.dir);
+ return readIntStatFromArchives(archives, typeName, statName);
+
+ // failure
+ } else {
+ throw new IllegalStateException(this.dir + " does not exist!");
+ }
+ }
+
+ private int readIntStatFromArchives(final List<File> archives, final String typeName, final String statName) throws IOException {
+ StatValue[] statValues = readStatValues(archives, typeName, statName);
+ assertNotNull("statValues is null!", statValues);
+ assertTrue("statValues is empty!", statValues.length > 0);
+
+ int value = 0;
+ for (int i = 0; i < statValues.length; i++) {
+ statValues[i].setFilter(StatValue.FILTER_NONE);
+ value += (int)statValues[i].getSnapshotsMaximum();
+ }
+ return value;
+ }
+
+ private static List<File> findFilesWithSuffix(final File dir, final String regex, final String suffix) {
+ Pattern p = null;
+ if (regex != null) {
+ p = Pattern.compile(regex);
+ }
+ final Pattern pattern = p;
+
+ return findFiles(
+ dir,
+ (final File file) -> {
+ boolean value = true;
+ if (regex != null) {
+ final Matcher matcher = pattern.matcher(file.getName());
+ value = matcher.matches();
+ }
+ if (suffix != null) {
+ value = value && file.getName().endsWith(suffix);
+ }
+ return value;
+ },
+ true);
+ }
+
+ private static List<File> findFiles(final File dir, final FileFilter filter, final boolean recursive) {
+ File[] tmpfiles = dir.listFiles(filter);
+ List<File> matches;
+ if (tmpfiles == null) {
+ matches = new ArrayList<>();
+ } else {
+ matches = new ArrayList<>(Arrays.asList(tmpfiles));
+ }
+ if (recursive) {
+ File[] files = dir.listFiles();
+ if (files != null) {
+ for (int i = 0; i < files.length; i++) {
+ File file = files[i];
+ if (file.isDirectory()) {
+ matches.addAll(findFiles(file, filter, recursive));
+ }
+ }
+ }
+ }
+ return matches;
+ }
+
+ private static StatValue[] readStatValues(final List<File> archives, final String typeName, final String statName) throws IOException {
+ final StatSpec statSpec = new StatSpec() {
+ @Override
+ public boolean archiveMatches(File value) {
+ return true;
+ }
+ @Override
+ public boolean typeMatches(String value) {
+ return typeName.equals(value);
+ }
+ @Override
+ public boolean statMatches(String value) {
+ return statName.equals(value);
+ }
+ @Override
+ public boolean instanceMatches(String textId, long numericId) {
+ return true;
+ }
+ @Override
+ public int getCombineType() {
+ return StatSpec.FILE;
+ }
+ };
+
+ File[] archiveFiles = archives.toArray(new File[archives.size()]);
+ StatSpec[] filters = new StatSpec[] { statSpec };
+ StatArchiveReader reader = new StatArchiveReader(archiveFiles, filters, true);
+ StatValue[] values = reader.matchSpec(statSpec);
+ return values;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsImplTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsImplTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsImplTest.java
new file mode 100644
index 0000000..ab8d587
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsImplTest.java
@@ -0,0 +1,136 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+import java.util.function.DoubleSupplier;
+import java.util.function.IntSupplier;
+import java.util.function.LongSupplier;
+
+import org.apache.logging.log4j.Logger;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.ExpectedException;
+
+import com.gemstone.gemfire.test.junit.categories.UnitTest;
+
+/**
+ * Unit tests for {@link StatisticsImpl}.
+ */
+@Category(UnitTest.class)
+public class StatisticsImplTest {
+ @Rule
+ public ExpectedException thrown = ExpectedException.none();
+
+ private StatisticsImpl stats;
+
+ @Before
+ public void createStats() {
+ final StatisticsTypeImpl type = mock(StatisticsTypeImpl.class);
+ when(type.getIntStatCount()).thenReturn(5);
+ when(type.getDoubleStatCount()).thenReturn(5);
+ when(type.getLongStatCount()).thenReturn(5);
+ final String textId = "";
+ final long numbericId = 0;
+ final long uniqueId = 0;
+ final int osStatFlags = 0;
+ final boolean atomicIncrements = false;
+ final StatisticsManager system = mock(StatisticsManager.class);
+ stats = new LocalStatisticsImpl(type, textId, numbericId, uniqueId, atomicIncrements, osStatFlags, system);
+ }
+
+ @Test
+ public void invokeIntSuppliersShouldUpdateStats() {
+ IntSupplier supplier1 = mock(IntSupplier.class);
+ when(supplier1.getAsInt()).thenReturn(23);
+ stats.setIntSupplier(4, supplier1);
+ assertEquals(0, stats.invokeSuppliers());
+
+ verify(supplier1).getAsInt();
+ assertEquals(23, stats.getInt(4));
+ }
+
+ @Test
+ public void invokeLongSuppliersShouldUpdateStats() {
+ LongSupplier supplier1 = mock(LongSupplier.class);
+ when(supplier1.getAsLong()).thenReturn(23L);
+ stats.setLongSupplier(4, supplier1);
+ assertEquals(0, stats.invokeSuppliers());
+
+ verify(supplier1).getAsLong();
+ assertEquals(23L, stats.getLong(4));
+ }
+
+ @Test
+ public void invokeDoubleSuppliersShouldUpdateStats() {
+ DoubleSupplier supplier1 = mock(DoubleSupplier.class);
+ when(supplier1.getAsDouble()).thenReturn(23.3);
+ stats.setDoubleSupplier(4, supplier1);
+ assertEquals(0, stats.invokeSuppliers());
+
+ verify(supplier1).getAsDouble();
+ assertEquals(23.3, stats.getDouble(4), 0.1f);
+ }
+
+ @Test
+ public void getSupplierCountShouldReturnCorrectCount() {
+ IntSupplier supplier1 = mock(IntSupplier.class);
+ stats.setIntSupplier(4, supplier1);
+ assertEquals(1, stats.getSupplierCount());
+ }
+
+ @Test
+ public void invokeSuppliersShouldCatchSupplierErrorsAndReturnCount() {
+ IntSupplier supplier1 = mock(IntSupplier.class);
+ when(supplier1.getAsInt()).thenThrow(NullPointerException.class);
+ stats.setIntSupplier(4, supplier1);
+ assertEquals(1, stats.invokeSuppliers());
+
+ verify(supplier1).getAsInt();
+ }
+
+ @Test
+ public void invokeSuppliersShouldLogErrorOnlyOnce() {
+ final Logger originalLogger = StatisticsImpl.logger;
+ try {
+ final Logger logger = mock(Logger.class);
+ StatisticsImpl.logger = logger;
+ IntSupplier supplier1 = mock(IntSupplier.class);
+ when(supplier1.getAsInt()).thenThrow(NullPointerException.class);
+ stats.setIntSupplier(4, supplier1);
+ assertEquals(1, stats.invokeSuppliers());
+ verify(logger, times(1)).warn(anyString(), anyString(), anyInt(), isA(NullPointerException.class));
+ assertEquals(1, stats.invokeSuppliers());
+ //Make sure the logger isn't invoked again
+ verify(logger, times(1)).warn(anyString(), anyString(), anyInt(), isA(NullPointerException.class));
+ } finally {
+ StatisticsImpl.logger = originalLogger;
+ }
+ }
+
+ @Test
+ public void badSupplierParamShouldThrowError() {
+ IntSupplier supplier1 = mock(IntSupplier.class);
+ when(supplier1.getAsInt()).thenReturn(23);
+ thrown.expect(IllegalArgumentException.class);
+ stats.setIntSupplier(23, supplier1);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsMonitorJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsMonitorJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsMonitorJUnitTest.java
deleted file mode 100755
index b995451..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsMonitorJUnitTest.java
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal.statistics;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-
-import java.io.File;
-import java.util.List;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.test.junit.categories.UnitTest;
-
-/**
- * Unit tests for the StatisticsMonitor class. No disk IO.
- *
- * @since GemFire 7.0
- */
-@Category(UnitTest.class)
-public class StatisticsMonitorJUnitTest {
-
- private TestStatisticsManager manager;
- private SampleCollector sampleCollector;
-
- @Before
- public void setUp() throws Exception {
- final long startTime = System.currentTimeMillis();
- this.manager = new TestStatisticsManager(1, getClass().getSimpleName(), startTime);
-
- final StatArchiveHandlerConfig mockStatArchiveHandlerConfig = mock(StatArchiveHandlerConfig.class, getClass().getSimpleName() + "$" + StatArchiveHandlerConfig.class.getSimpleName());
- when(mockStatArchiveHandlerConfig.getArchiveFileName()).thenReturn(new File(""));
- when(mockStatArchiveHandlerConfig.getArchiveFileSizeLimit()).thenReturn(0L);
- when(mockStatArchiveHandlerConfig.getArchiveDiskSpaceLimit()).thenReturn(0L);
- when(mockStatArchiveHandlerConfig.getSystemId()).thenReturn(0L);
- when(mockStatArchiveHandlerConfig.getSystemStartTime()).thenReturn(0L);
- when(mockStatArchiveHandlerConfig.getSystemDirectoryPath()).thenReturn("");
- when(mockStatArchiveHandlerConfig.getProductDescription()).thenReturn(getClass().getSimpleName());
-
- StatisticsSampler sampler = new TestStatisticsSampler(manager);
- this.sampleCollector = new SampleCollector(sampler);
- this.sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime());
- }
-
- @After
- public void tearDown() throws Exception {
- if (this.sampleCollector != null) {
- this.sampleCollector.close();
- this.sampleCollector = null;
- }
- this.manager = null;
- }
-
- @Test
- public void testAddListener() {
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
- StatisticsListener listener = new StatisticsListener() {
- @Override
- public void handleNotification(StatisticsNotification notification) {
- }
- };
-
- assertNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
-
- monitor.addListener(listener);
-
- assertFalse(monitor.getStatisticsListenersSnapshot().isEmpty());
- assertTrue(monitor.getStatisticsListenersSnapshot().contains(listener));
- assertEquals(1, monitor.getStatisticsListenersSnapshot().size());
-
- assertNotNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
- assertFalse(this.sampleCollector.getStatMonitorHandlerSnapshot().getMonitorsSnapshot().isEmpty());
- }
-
- @Test
- public void testAddExistingListener() {
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
- StatisticsListener listener = new StatisticsListener() {
- @Override
- public void handleNotification(StatisticsNotification notification) {
- }
- };
-
- monitor.addListener(listener);
- assertFalse(monitor.getStatisticsListenersSnapshot().isEmpty());
- assertTrue(monitor.getStatisticsListenersSnapshot().contains(listener));
- assertEquals(1, monitor.getStatisticsListenersSnapshot().size());
-
- monitor.addListener(listener);
- assertFalse(monitor.getStatisticsListenersSnapshot().isEmpty());
- assertTrue(monitor.getStatisticsListenersSnapshot().contains(listener));
- assertEquals(1, monitor.getStatisticsListenersSnapshot().size());
- }
-
- @Test
- public void testRemoveListener() {
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
- StatisticsListener listener = new StatisticsListener() {
- @Override
- public void handleNotification(StatisticsNotification notification) {
- }
- };
-
- assertNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
-
- monitor.addListener(listener);
- assertFalse(monitor.getStatisticsListenersSnapshot().isEmpty());
- assertTrue(monitor.getStatisticsListenersSnapshot().contains(listener));
- assertEquals(1, monitor.getStatisticsListenersSnapshot().size());
-
- assertNotNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
- assertFalse(this.sampleCollector.getStatMonitorHandlerSnapshot().getMonitorsSnapshot().isEmpty());
-
- monitor.removeListener(listener);
- assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
- assertFalse(monitor.getStatisticsListenersSnapshot().contains(listener));
-
- assertNotNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
- assertTrue(this.sampleCollector.getStatMonitorHandlerSnapshot().getMonitorsSnapshot().isEmpty());
- }
-
- @Test
- public void testRemoveMissingListener() {
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
- StatisticsListener listener = new StatisticsListener() {
- @Override
- public void handleNotification(StatisticsNotification notification) {
- }
- };
-
- assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
- assertFalse(monitor.getStatisticsListenersSnapshot().contains(listener));
-
- monitor.removeListener(listener);
-
- assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
- assertFalse(monitor.getStatisticsListenersSnapshot().contains(listener));
- }
-
- // TODO: test addStatistic
- // TODO: test removeStatistic
- // TODO: test monitor and/or monitorStatisticIds
- // TODO: test notifyListeners
-
- /**
- * @since GemFire 7.0
- */
- static class TestStatisticsMonitor extends StatisticsMonitor {
- private volatile long timeStamp;
- private volatile List<ResourceInstance> resourceInstances;
- private volatile int notificationCount;
-
- public TestStatisticsMonitor() {
- super();
- }
-
- @Override
- protected void monitor(long timeStamp, List<ResourceInstance> resourceInstances) {
- this.timeStamp = timeStamp;
- this.resourceInstances = resourceInstances;
- this.notificationCount++;
- }
-
- long getTimeStamp() {
- return this.timeStamp;
- }
-
- List<ResourceInstance> getResourceInstances() {
- return this.resourceInstances;
- }
-
- int getNotificationCount() {
- return this.notificationCount;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsMonitorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsMonitorTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsMonitorTest.java
new file mode 100755
index 0000000..bfd27c4
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsMonitorTest.java
@@ -0,0 +1,198 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+import java.io.File;
+import java.util.List;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import com.gemstone.gemfire.internal.NanoTimer;
+import com.gemstone.gemfire.test.junit.categories.UnitTest;
+
+/**
+ * Unit tests for the StatisticsMonitor class. No disk IO.
+ *
+ * @since GemFire 7.0
+ */
+@Category(UnitTest.class)
+public class StatisticsMonitorTest {
+
+ private TestStatisticsManager manager;
+ private SampleCollector sampleCollector;
+
+ @Before
+ public void setUp() throws Exception {
+ final long startTime = System.currentTimeMillis();
+ this.manager = new TestStatisticsManager(1, getClass().getSimpleName(), startTime);
+
+ final StatArchiveHandlerConfig mockStatArchiveHandlerConfig = mock(StatArchiveHandlerConfig.class, getClass().getSimpleName() + "$" + StatArchiveHandlerConfig.class.getSimpleName());
+ when(mockStatArchiveHandlerConfig.getArchiveFileName()).thenReturn(new File(""));
+ when(mockStatArchiveHandlerConfig.getArchiveFileSizeLimit()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getArchiveDiskSpaceLimit()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getSystemId()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getSystemStartTime()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getSystemDirectoryPath()).thenReturn("");
+ when(mockStatArchiveHandlerConfig.getProductDescription()).thenReturn(getClass().getSimpleName());
+
+ StatisticsSampler sampler = new TestStatisticsSampler(manager);
+ this.sampleCollector = new SampleCollector(sampler);
+ this.sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime());
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ if (this.sampleCollector != null) {
+ this.sampleCollector.close();
+ this.sampleCollector = null;
+ }
+ this.manager = null;
+ }
+
+ @Test
+ public void testAddListener() {
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
+ StatisticsListener listener = new StatisticsListener() {
+ @Override
+ public void handleNotification(StatisticsNotification notification) {
+ }
+ };
+
+ assertNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
+
+ monitor.addListener(listener);
+
+ assertFalse(monitor.getStatisticsListenersSnapshot().isEmpty());
+ assertTrue(monitor.getStatisticsListenersSnapshot().contains(listener));
+ assertEquals(1, monitor.getStatisticsListenersSnapshot().size());
+
+ assertNotNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
+ assertFalse(this.sampleCollector.getStatMonitorHandlerSnapshot().getMonitorsSnapshot().isEmpty());
+ }
+
+ @Test
+ public void testAddExistingListener() {
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
+ StatisticsListener listener = new StatisticsListener() {
+ @Override
+ public void handleNotification(StatisticsNotification notification) {
+ }
+ };
+
+ monitor.addListener(listener);
+ assertFalse(monitor.getStatisticsListenersSnapshot().isEmpty());
+ assertTrue(monitor.getStatisticsListenersSnapshot().contains(listener));
+ assertEquals(1, monitor.getStatisticsListenersSnapshot().size());
+
+ monitor.addListener(listener);
+ assertFalse(monitor.getStatisticsListenersSnapshot().isEmpty());
+ assertTrue(monitor.getStatisticsListenersSnapshot().contains(listener));
+ assertEquals(1, monitor.getStatisticsListenersSnapshot().size());
+ }
+
+ @Test
+ public void testRemoveListener() {
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
+ StatisticsListener listener = new StatisticsListener() {
+ @Override
+ public void handleNotification(StatisticsNotification notification) {
+ }
+ };
+
+ assertNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
+
+ monitor.addListener(listener);
+ assertFalse(monitor.getStatisticsListenersSnapshot().isEmpty());
+ assertTrue(monitor.getStatisticsListenersSnapshot().contains(listener));
+ assertEquals(1, monitor.getStatisticsListenersSnapshot().size());
+
+ assertNotNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
+ assertFalse(this.sampleCollector.getStatMonitorHandlerSnapshot().getMonitorsSnapshot().isEmpty());
+
+ monitor.removeListener(listener);
+ assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
+ assertFalse(monitor.getStatisticsListenersSnapshot().contains(listener));
+
+ assertNotNull(this.sampleCollector.getStatMonitorHandlerSnapshot());
+ assertTrue(this.sampleCollector.getStatMonitorHandlerSnapshot().getMonitorsSnapshot().isEmpty());
+ }
+
+ @Test
+ public void testRemoveMissingListener() {
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
+ StatisticsListener listener = new StatisticsListener() {
+ @Override
+ public void handleNotification(StatisticsNotification notification) {
+ }
+ };
+
+ assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
+ assertFalse(monitor.getStatisticsListenersSnapshot().contains(listener));
+
+ monitor.removeListener(listener);
+
+ assertTrue(monitor.getStatisticsListenersSnapshot().isEmpty());
+ assertFalse(monitor.getStatisticsListenersSnapshot().contains(listener));
+ }
+
+ // TODO: test addStatistic
+ // TODO: test removeStatistic
+ // TODO: test monitor and/or monitorStatisticIds
+ // TODO: test notifyListeners
+
+ /**
+ * @since GemFire 7.0
+ */
+ static class TestStatisticsMonitor extends StatisticsMonitor {
+ private volatile long timeStamp;
+ private volatile List<ResourceInstance> resourceInstances;
+ private volatile int notificationCount;
+
+ public TestStatisticsMonitor() {
+ super();
+ }
+
+ @Override
+ protected void monitor(long timeStamp, List<ResourceInstance> resourceInstances) {
+ this.timeStamp = timeStamp;
+ this.resourceInstances = resourceInstances;
+ this.notificationCount++;
+ }
+
+ long getTimeStamp() {
+ return this.timeStamp;
+ }
+
+ List<ResourceInstance> getResourceInstances() {
+ return this.resourceInstances;
+ }
+
+ int getNotificationCount() {
+ return this.notificationCount;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatArchiveWriter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatArchiveWriter.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatArchiveWriter.java
index 81d963e..bc3be89 100755
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatArchiveWriter.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatArchiveWriter.java
@@ -18,10 +18,6 @@ package com.gemstone.gemfire.internal.statistics;
import java.util.TimeZone;
-import com.gemstone.gemfire.i18n.LogWriterI18n;
-import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.internal.StatArchiveWriter;
-
/**
* @since GemFire 7.0
*/
@@ -32,7 +28,7 @@ public class TestStatArchiveWriter extends StatArchiveWriter {
public static final String WRITER_OS_INFO = "Linux 2.6.18-262.el5";
public static final String WRITER_MACHINE_INFO = "i386 kuwait";
- public TestStatArchiveWriter(StatArchiveDescriptor archiveDescriptor, LogWriterI18n logger) {
+ public TestStatArchiveWriter(final StatArchiveDescriptor archiveDescriptor) {
super(archiveDescriptor);
initialize(WRITER_PREVIOUS_TIMESTAMP_NANOS);
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsManager.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsManager.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsManager.java
index fbb3dce..01c59f1 100755
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsManager.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsManager.java
@@ -18,24 +18,19 @@ package com.gemstone.gemfire.internal.statistics;
import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.AbstractStatisticsFactory;
-import com.gemstone.gemfire.internal.OsStatisticsFactory;
-import com.gemstone.gemfire.internal.StatisticsManager;
+import com.gemstone.gemfire.internal.statistics.platform.OsStatisticsFactory;
/**
* @since GemFire 7.0
*/
-public class TestStatisticsManager extends AbstractStatisticsFactory
- implements StatisticsManager, OsStatisticsFactory {
+public class TestStatisticsManager extends AbstractStatisticsFactory implements StatisticsManager, OsStatisticsFactory {
- public TestStatisticsManager(long id, String name, long startTime) {
+ public TestStatisticsManager(final long id, final String name, final long startTime) {
super(id, name, startTime);
}
@Override
- public Statistics createOsStatistics(StatisticsType type, String textId,
- long numericId, int osStatFlags) {
- // TODO ?
+ public Statistics createOsStatistics(final StatisticsType type, final String textId, final long numericId, final int osStatFlags) {
return null;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsSampler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsSampler.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsSampler.java
index 0905167..b69d480 100755
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsSampler.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/TestStatisticsSampler.java
@@ -19,16 +19,16 @@ package com.gemstone.gemfire.internal.statistics;
import java.util.List;
import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.internal.StatisticsManager;
/**
* @since GemFire 7.0
*/
+@SuppressWarnings("unchecked")
public class TestStatisticsSampler implements StatisticsSampler {
private final StatisticsManager manager;
- public TestStatisticsSampler(StatisticsManager manager) {
+ public TestStatisticsSampler(final StatisticsManager manager) {
this.manager = manager;
}
@@ -39,20 +39,19 @@ public class TestStatisticsSampler implements StatisticsSampler {
@Override
public Statistics[] getStatistics() {
- @SuppressWarnings("unchecked")
- List<Statistics> statsList = (List<Statistics>)this.manager.getStatsList();
+ List<Statistics> statsList = this.manager.getStatsList();
synchronized (statsList) {
- return (Statistics[])statsList.toArray(new Statistics[statsList.size()]);
+ return statsList.toArray(new Statistics[statsList.size()]);
}
}
@Override
- public boolean waitForSample(long timeout) throws InterruptedException {
+ public boolean waitForSample(final long timeout) throws InterruptedException {
return false;
}
@Override
- public SampleCollector waitForSampleCollector(long timeout) throws InterruptedException {
+ public SampleCollector waitForSampleCollector(final long timeout) throws InterruptedException {
return null;
}
}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ValueMonitorIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ValueMonitorIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ValueMonitorIntegrationTest.java
new file mode 100755
index 0000000..9afbe22
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ValueMonitorIntegrationTest.java
@@ -0,0 +1,367 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.gemstone.gemfire.test.dunit.Wait.*;
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.jmock.Expectations;
+import org.jmock.Mockery;
+import org.jmock.lib.legacy.ClassImposteriser;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.NanoTimer;
+import com.gemstone.gemfire.internal.statistics.StatisticsNotification.Type;
+import com.gemstone.gemfire.test.dunit.WaitCriterion;
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+
+/**
+ * Integration test for the SampleCollector class.
+ *
+ * @since GemFire 7.0
+ */
+@Category(IntegrationTest.class)
+public class ValueMonitorIntegrationTest {
+
+ private Mockery mockContext;
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUp() throws Exception {
+ this.mockContext = new Mockery() {{
+ setImposteriser(ClassImposteriser.INSTANCE);
+ }};
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ this.mockContext.assertIsSatisfied();
+ this.mockContext = null;
+ }
+
+ @Test
+ public void testAddRemoveListener() throws Exception {
+ long startTime = System.currentTimeMillis();
+ List<Statistics> statsList = new ArrayList<Statistics>();
+ StatisticsManager mockStatisticsManager = this.mockContext.mock(StatisticsManager.class, testName.getMethodName() + "$StatisticsManager");
+ this.mockContext.checking(new Expectations() {{
+ allowing(mockStatisticsManager).getName();
+ will(returnValue("mockStatisticsManager"));
+ allowing(mockStatisticsManager).getId();
+ will(returnValue(1));
+ allowing(mockStatisticsManager).getStartTime();
+ will(returnValue(startTime));
+ allowing(mockStatisticsManager).getStatListModCount();
+ will(returnValue(0));
+ allowing(mockStatisticsManager).getStatsList();
+ will(returnValue(statsList));
+ }});
+
+ StatisticsSampler mockStatisticsSampler = this.mockContext.mock(StatisticsSampler.class, testName.getMethodName() + "$StatisticsSampler");
+ this.mockContext.checking(new Expectations() {{
+ allowing(mockStatisticsSampler).getStatisticsModCount();
+ will(returnValue(0));
+ allowing(mockStatisticsSampler).getStatistics();
+ will(returnValue(new Statistics[]{}));
+ }});
+
+ StatArchiveHandlerConfig mockStatArchiveHandlerConfig = this.mockContext.mock(StatArchiveHandlerConfig.class, testName.getMethodName() + "$StatArchiveHandlerConfig");
+ this.mockContext.checking(new Expectations() {{
+ allowing(mockStatArchiveHandlerConfig).getArchiveFileName();
+ will(returnValue(new File("")));
+ allowing(mockStatArchiveHandlerConfig).getArchiveFileSizeLimit();
+ will(returnValue(0));
+ allowing(mockStatArchiveHandlerConfig).getArchiveDiskSpaceLimit();
+ will(returnValue(0));
+ allowing(mockStatArchiveHandlerConfig).getSystemId();
+ will(returnValue(1));
+ allowing(mockStatArchiveHandlerConfig).getSystemStartTime();
+ will(returnValue(startTime));
+ allowing(mockStatArchiveHandlerConfig).getSystemDirectoryPath();
+ will(returnValue(""));
+ allowing(mockStatArchiveHandlerConfig).getProductDescription();
+ will(returnValue("testAddRemoveListener"));
+ }});
+
+ // need a real SampleCollector for this test or the monitor can't get the handler
+ SampleCollector sampleCollector = new SampleCollector(mockStatisticsSampler);
+ sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime());
+
+ List<StatisticsNotification> notifications = new ArrayList<>();
+ StatisticsListener listener = (final StatisticsNotification notification) -> {
+ notifications.add(notification);
+ };
+ ValueMonitor monitor = new ValueMonitor();
+
+ long timeStamp = System.currentTimeMillis();
+ Type type = Type.VALUE_CHANGED;
+ Number value = 43;
+
+ StatisticsNotification notification = createStatisticsNotification(timeStamp, type, value);
+ monitor.notifyListeners(notification);
+
+ assertTrue(notifications.isEmpty());
+
+ monitor.addListener(listener);
+ monitor.notifyListeners(notification);
+
+ assertEquals(1, notifications.size());
+ notification = notifications.remove(0);
+ assertNotNull(notification);
+
+ assertEquals(timeStamp, notification.getTimeStamp());
+ assertEquals(type, notification.getType());
+ StatisticId statId = createStatisticId(null, null);
+ assertEquals(value, notification.getValue(statId));
+
+ monitor.removeListener(listener);
+ monitor.notifyListeners(notification);
+
+ assertTrue(notifications.isEmpty());
+ }
+
+ @Test
+ public void testValueMonitorListener() throws Exception {
+ long startTime = System.currentTimeMillis();
+ TestStatisticsManager manager = new TestStatisticsManager(1, "ValueMonitorIntegrationTest", startTime);
+ StatisticsSampler sampler = new TestStatisticsSampler(manager);
+
+ StatArchiveHandlerConfig mockStatArchiveHandlerConfig = this.mockContext.mock(StatArchiveHandlerConfig.class, testName.getMethodName() + "$StatArchiveHandlerConfig");
+ this.mockContext.checking(new Expectations() {{
+ allowing(mockStatArchiveHandlerConfig).getArchiveFileName();
+ will(returnValue(new File("")));
+ allowing(mockStatArchiveHandlerConfig).getArchiveFileSizeLimit();
+ will(returnValue(0));
+ allowing(mockStatArchiveHandlerConfig).getArchiveDiskSpaceLimit();
+ will(returnValue(0));
+ allowing(mockStatArchiveHandlerConfig).getSystemId();
+ will(returnValue(1));
+ allowing(mockStatArchiveHandlerConfig).getSystemStartTime();
+ will(returnValue(startTime));
+ allowing(mockStatArchiveHandlerConfig).getSystemDirectoryPath();
+ will(returnValue(""));
+ allowing(mockStatArchiveHandlerConfig).getProductDescription();
+ will(returnValue("testFoo"));
+ }});
+
+ SampleCollector sampleCollector = new SampleCollector(sampler);
+ sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime());
+
+ StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createDoubleCounter("double_counter_1", "double_counter_1_desc", "double_counter_1_units"),
+ manager.createIntCounter( "int_counter_2", "int_counter_2_desc", "int_counter_2_units"),
+ manager.createLongCounter( "long_counter_3", "long_counter_3_desc", "long_counter_3_units")
+ };
+ StatisticsType ST1 = manager.createType("ST1_name", "ST1_desc", statsST1);
+ Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1_text", 1);
+ Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2_text", 2);
+
+ st1_1.incDouble("double_counter_1", 1000.0001);
+ st1_1.incInt("int_counter_2", 2);
+ st1_1.incLong("long_counter_3", 3333333333L);
+
+ st1_2.incDouble("double_counter_1", 2000.0002);
+ st1_2.incInt("int_counter_2", 3);
+ st1_2.incLong("long_counter_3", 4444444444L);
+
+ List<StatisticsNotification> notifications = new ArrayList<>();
+ StatisticsListener listener = (final StatisticsNotification notification) -> {
+ notifications.add(notification);
+ };
+ ValueMonitor monitor = new ValueMonitor().addStatistics(st1_1);
+ monitor.addListener(listener);
+
+ assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
+
+ long timeStamp = NanoTimer.getTime();
+ sampleCollector.sample(timeStamp);
+
+ awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
+ assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
+
+ StatisticsNotification notification = notifications.remove(0);
+ assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
+
+ // validate 1 notification occurs with all 3 stats of st1_1
+
+ st1_1.incDouble("double_counter_1", 1.1);
+ st1_1.incInt("int_counter_2", 2);
+ st1_1.incLong("long_counter_3", 3);
+
+ timeStamp += NanoTimer.millisToNanos(1000);
+ sampleCollector.sample(timeStamp);
+
+ awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
+ assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
+
+ notification = notifications.remove(0);
+ assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
+
+ int statCount = 0;
+ Map<String, Number> expectedValues = new HashMap<>();
+ expectedValues.put("double_counter_1", 1001.1001);
+ expectedValues.put("int_counter_2", 4);
+ expectedValues.put("long_counter_3", 3333333336L);
+
+ for (StatisticId statId : notification) {
+ Number value = expectedValues.remove(statId.getStatisticDescriptor().getName());
+ assertNotNull(value);
+ assertEquals(value, notification.getValue(statId));
+ statCount++;
+ }
+ assertEquals(3, statCount);
+
+ // validate no notification occurs when no stats are updated
+
+ timeStamp += NanoTimer.millisToNanos(1000);
+ sampleCollector.sample(timeStamp);
+
+ awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
+ assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
+
+ // validate no notification occurs when only other stats are updated
+
+ st1_2.incDouble("double_counter_1", 3.3);
+ st1_2.incInt("int_counter_2", 1);
+ st1_2.incLong("long_counter_3", 2);
+
+ timeStamp += NanoTimer.millisToNanos(1000);
+ sampleCollector.sample(timeStamp);
+
+ awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
+ assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
+
+ // validate notification only contains stats added to monitor
+
+ st1_1.incInt("int_counter_2", 100);
+ st1_2.incInt("int_counter_2", 200);
+
+ assertEquals(2, sampleCollector.currentHandlersForTesting().size());
+
+ timeStamp += NanoTimer.millisToNanos(1000);
+ sampleCollector.sample(timeStamp);
+
+ awaitAtLeastTimeoutOrUntilNotifications(notifications, 2 * 1000);
+ assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
+
+ notification = notifications.remove(0);
+ assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
+
+ statCount = 0;
+ expectedValues = new HashMap<>();
+ expectedValues.put("int_counter_2", 104);
+
+ for (StatisticId statId : notification) {
+ Number value = expectedValues.remove(statId.getStatisticDescriptor().getName());
+ assertNotNull(value);
+ assertEquals(value, notification.getValue(statId));
+ statCount++;
+ }
+ assertEquals(1, statCount);
+ }
+
+ private StatisticId createStatisticId(final StatisticDescriptor descriptor, final Statistics stats) {
+ return new StatisticId() {
+
+ @Override
+ public StatisticDescriptor getStatisticDescriptor() {
+ return descriptor;
+ }
+
+ @Override
+ public Statistics getStatistics() {
+ return stats;
+ }
+ };
+ }
+
+ protected StatisticsNotification createStatisticsNotification(final long timeStamp, final Type type, final Number value) {
+ return new StatisticsNotification() {
+
+ @Override
+ public long getTimeStamp() {
+ return timeStamp;
+ }
+
+ @Override
+ public Type getType() {
+ return type;
+ }
+
+ @Override
+ public Iterator<StatisticId> iterator() {
+ return null;
+ }
+
+ @Override
+ public Iterator<StatisticId> iterator(final StatisticDescriptor statDesc) {
+ return null;
+ }
+
+ @Override
+ public Iterator<StatisticId> iterator(final Statistics statistics) {
+ return null;
+ }
+
+ @Override
+ public Iterator<StatisticId> iterator(final StatisticsType statisticsType) {
+ return null;
+ }
+
+ @Override
+ public Number getValue(final StatisticId statId) throws StatisticNotFoundException {
+ return value;
+ }
+ };
+ }
+
+ /**
+ * Wait for at least the specified time or until notifications is >0.
+ */
+ private static void awaitAtLeastTimeoutOrUntilNotifications(final List<StatisticsNotification> notifications, final long timeoutMillis) {
+ long pollingIntervalMillis = 10;
+ boolean throwOnTimeout = false;
+ WaitCriterion wc = new WaitCriterion() {
+ @Override
+ public boolean done() {
+ return notifications.size() > 0;
+ }
+ @Override
+ public String description() {
+ return "waiting for notification";
+ }
+ };
+ waitForCriterion(wc, timeoutMillis, pollingIntervalMillis, throwOnTimeout);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ValueMonitorJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ValueMonitorJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ValueMonitorJUnitTest.java
deleted file mode 100755
index b671250..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/ValueMonitorJUnitTest.java
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal.statistics;
-
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import com.gemstone.gemfire.StatisticDescriptor;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.internal.StatisticsManager;
-import com.gemstone.gemfire.internal.statistics.StatisticsNotification.Type;
-import com.gemstone.gemfire.test.dunit.Wait;
-import com.gemstone.gemfire.test.dunit.WaitCriterion;
-import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
-
-/**
- * Integration test for the SampleCollector class.
- *
- * @since GemFire 7.0
- */
-@Category(IntegrationTest.class)
-public class ValueMonitorJUnitTest {
-
- private Mockery mockContext;
-
- @Before
- public void setUp() throws Exception {
- this.mockContext = new Mockery() {{
- setImposteriser(ClassImposteriser.INSTANCE);
- }};
- }
-
- @After
- public void tearDown() throws Exception {
- this.mockContext.assertIsSatisfied();
- this.mockContext = null;
- }
-
- @Test
- public void testAddRemoveListener() throws Exception {
- final long startTime = System.currentTimeMillis();
- final List<Statistics> statsList = new ArrayList<Statistics>();
- final StatisticsManager mockStatisticsManager = this.mockContext.mock(StatisticsManager.class, "testAddRemoveListener$StatisticsManager");
- this.mockContext.checking(new Expectations() {{
- allowing(mockStatisticsManager).getName();
- will(returnValue("mockStatisticsManager"));
- allowing(mockStatisticsManager).getId();
- will(returnValue(1));
- allowing(mockStatisticsManager).getStartTime();
- will(returnValue(startTime));
- allowing(mockStatisticsManager).getStatListModCount();
- will(returnValue(0));
- allowing(mockStatisticsManager).getStatsList();
- will(returnValue(statsList));
- }});
-
- final StatisticsSampler mockStatisticsSampler = this.mockContext.mock(StatisticsSampler.class, "testAddRemoveListener$StatisticsSampler");
- this.mockContext.checking(new Expectations() {{
- allowing(mockStatisticsSampler).getStatisticsModCount();
- will(returnValue(0));
- allowing(mockStatisticsSampler).getStatistics();
- will(returnValue(new Statistics[]{}));
- }});
-
- final StatArchiveHandlerConfig mockStatArchiveHandlerConfig = this.mockContext.mock(StatArchiveHandlerConfig.class, "testAddRemoveListener$StatArchiveHandlerConfig");
- this.mockContext.checking(new Expectations() {{
- allowing(mockStatArchiveHandlerConfig).getArchiveFileName();
- will(returnValue(new File("")));
- allowing(mockStatArchiveHandlerConfig).getArchiveFileSizeLimit();
- will(returnValue(0));
- allowing(mockStatArchiveHandlerConfig).getArchiveDiskSpaceLimit();
- will(returnValue(0));
- allowing(mockStatArchiveHandlerConfig).getSystemId();
- will(returnValue(1));
- allowing(mockStatArchiveHandlerConfig).getSystemStartTime();
- will(returnValue(startTime));
- allowing(mockStatArchiveHandlerConfig).getSystemDirectoryPath();
- will(returnValue(""));
- allowing(mockStatArchiveHandlerConfig).getProductDescription();
- will(returnValue("testAddRemoveListener"));
- }});
-
- // need a real SampleCollector for this test or the monitor can't get the handler
- SampleCollector sampleCollector = new SampleCollector(mockStatisticsSampler);
- sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime());
-
- final List<StatisticsNotification> notifications = new ArrayList<StatisticsNotification>();
- StatisticsListener listener = new StatisticsListener() {
- @Override
- public void handleNotification(StatisticsNotification notification) {
- notifications.add(notification);
- }
- };
- ValueMonitor monitor = new ValueMonitor();
-
- long timeStamp = System.currentTimeMillis();
- Type type = Type.VALUE_CHANGED;
- Number value = 43;
-
- StatisticsNotification notification = createStatisticsNotification(timeStamp, type, value);
- monitor.notifyListeners(notification);
-
- assertTrue(notifications.isEmpty());
-
- monitor.addListener(listener);
- monitor.notifyListeners(notification);
-
- assertEquals(1, notifications.size());
- notification = notifications.remove(0);
- assertNotNull(notification);
-
- assertEquals(timeStamp, notification.getTimeStamp());
- assertEquals(type, notification.getType());
- StatisticId statId = createStatisticId(null, null);
- assertEquals(value, notification.getValue(statId));
-
- monitor.removeListener(listener);
- monitor.notifyListeners(notification);
-
- assertTrue(notifications.isEmpty());
- }
-
- @Test
- public void testValueMonitorListener() throws Exception {
- final long startTime = System.currentTimeMillis();
- TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "ValueMonitorJUnitTest",
- startTime);
- StatisticsSampler sampler = new TestStatisticsSampler(manager);
-
- final StatArchiveHandlerConfig mockStatArchiveHandlerConfig =
- this.mockContext.mock(StatArchiveHandlerConfig.class, "testFoo$StatArchiveHandlerConfig");
- this.mockContext.checking(new Expectations() {{
- allowing(mockStatArchiveHandlerConfig).getArchiveFileName();
- will(returnValue(new File("")));
- allowing(mockStatArchiveHandlerConfig).getArchiveFileSizeLimit();
- will(returnValue(0));
- allowing(mockStatArchiveHandlerConfig).getArchiveDiskSpaceLimit();
- will(returnValue(0));
- allowing(mockStatArchiveHandlerConfig).getSystemId();
- will(returnValue(1));
- allowing(mockStatArchiveHandlerConfig).getSystemStartTime();
- will(returnValue(startTime));
- allowing(mockStatArchiveHandlerConfig).getSystemDirectoryPath();
- will(returnValue(""));
- allowing(mockStatArchiveHandlerConfig).getProductDescription();
- will(returnValue("testFoo"));
- }});
-
- SampleCollector sampleCollector = new SampleCollector(sampler);
- sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime());
-
- StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createDoubleCounter("double_counter_1", "double_counter_1_desc", "double_counter_1_units"),
- manager.createIntCounter( "int_counter_2", "int_counter_2_desc", "int_counter_2_units"),
- manager.createLongCounter( "long_counter_3", "long_counter_3_desc", "long_counter_3_units")
- };
- StatisticsType ST1 = manager.createType("ST1_name", "ST1_desc", statsST1);
- Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1_text", 1);
- Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2_text", 2);
-
- st1_1.incDouble("double_counter_1", 1000.0001);
- st1_1.incInt("int_counter_2", 2);
- st1_1.incLong("long_counter_3", 3333333333L);
-
- st1_2.incDouble("double_counter_1", 2000.0002);
- st1_2.incInt("int_counter_2", 3);
- st1_2.incLong("long_counter_3", 4444444444L);
-
- final List<StatisticsNotification> notifications = new ArrayList<StatisticsNotification>();
- StatisticsListener listener = new StatisticsListener() {
- @Override
- public void handleNotification(StatisticsNotification notification) {
- notifications.add(notification);
- }
- };
- ValueMonitor monitor = new ValueMonitor().addStatistics(st1_1);
- monitor.addListener(listener);
-
- assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
-
- long timeStamp = NanoTimer.getTime();
- sampleCollector.sample(timeStamp);
-
- waitForNotification(notifications, 2*1000, 10, false);
- assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
-
- StatisticsNotification notification = notifications.remove(0);
- assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
-
- // validate 1 notification occurs with all 3 stats of st1_1
-
- st1_1.incDouble("double_counter_1", 1.1);
- st1_1.incInt("int_counter_2", 2);
- st1_1.incLong("long_counter_3", 3);
-
- timeStamp += NanoTimer.millisToNanos(1000);
- sampleCollector.sample(timeStamp);
-
- waitForNotification(notifications, 2*1000, 10, false);
- assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
-
- notification = notifications.remove(0);
- assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
-
- int statCount = 0;
- Map<String, Number> expectedValues = new HashMap<String, Number>();
- expectedValues.put("double_counter_1", 1001.1001);
- expectedValues.put("int_counter_2", 4);
- expectedValues.put("long_counter_3", 3333333336L);
-
- for (StatisticId statId : notification) {
- Number value = expectedValues.remove(statId.getStatisticDescriptor().getName());
- assertNotNull(value);
- assertEquals(value, notification.getValue(statId));
- statCount++;
- }
- assertEquals(3, statCount);
-
- // validate no notification occurs when no stats are updated
-
- timeStamp += NanoTimer.millisToNanos(1000);
- sampleCollector.sample(timeStamp);
-
- waitForNotification(notifications, 2*1000, 10, false);
- assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
-
- // validate no notification occurs when only other stats are updated
-
- st1_2.incDouble("double_counter_1", 3.3);
- st1_2.incInt("int_counter_2", 1);
- st1_2.incLong("long_counter_3", 2);
-
- timeStamp += NanoTimer.millisToNanos(1000);
- sampleCollector.sample(timeStamp);
-
- waitForNotification(notifications, 2*1000, 10, false);
- assertTrue("Unexpected notifications: " + notifications, notifications.isEmpty());
-
- // validate notification only contains stats added to monitor
-
- st1_1.incInt("int_counter_2", 100);
- st1_2.incInt("int_counter_2", 200);
-
- assertEquals(2, sampleCollector.currentHandlersForTesting().size());
-
- timeStamp += NanoTimer.millisToNanos(1000);
- sampleCollector.sample(timeStamp);
-
- waitForNotification(notifications, 2*1000, 10, false);
- assertEquals("Unexpected notifications: " + notifications, 1, notifications.size());
-
- notification = notifications.remove(0);
- assertEquals(StatisticsNotification.Type.VALUE_CHANGED, notification.getType());
-
- statCount = 0;
- expectedValues = new HashMap<String, Number>();
- expectedValues.put("int_counter_2", 104);
-
- for (StatisticId statId : notification) {
- Number value = expectedValues.remove(statId.getStatisticDescriptor().getName());
- assertNotNull(value);
- assertEquals(value, notification.getValue(statId));
- statCount++;
- }
- assertEquals(1, statCount);
- }
-
- private StatisticId createStatisticId(final StatisticDescriptor descriptor, final Statistics stats) {
- return new StatisticId() {
-
- @Override
- public StatisticDescriptor getStatisticDescriptor() {
- return descriptor;
- }
-
- @Override
- public Statistics getStatistics() {
- return stats;
- }
-
- };
- }
-
- protected StatisticsNotification createStatisticsNotification(final long timeStamp, final Type type, final Number value) {
- return new StatisticsNotification() {
-
- @Override
- public long getTimeStamp() {
- return timeStamp;
- }
-
- @Override
- public Type getType() {
- return type;
- }
-
- @Override
- public Iterator<StatisticId> iterator() {
- return null;
- }
-
- @Override
- public Iterator<StatisticId> iterator(StatisticDescriptor statDesc) {
- return null;
- }
-
- @Override
- public Iterator<StatisticId> iterator(Statistics statistics) {
- return null;
- }
-
- @Override
- public Iterator<StatisticId> iterator(StatisticsType statisticsType) {
- return null;
- }
-
- @Override
- public Number getValue(StatisticId statId) throws StatisticNotFoundException {
- return value;
- }
-
- };
- }
-
- private static void waitForNotification(final List<StatisticsNotification> notifications, long ms, long interval, boolean throwOnTimeout) {
- WaitCriterion wc = new WaitCriterion() {
- @Override
- public boolean done() {
- return notifications.size() > 0;
- }
- @Override
- public String description() {
- return "waiting for notification";
- }
- };
- Wait.waitForCriterion(wc, ms, interval, throwOnTimeout);
- }
-}
[19/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveFormat.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveFormat.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveFormat.java
deleted file mode 100644
index d1e67f9..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveFormat.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-/**
- * StatArchiveFormat defines constants related to the statistic archive
- * file format.
- */
-public interface StatArchiveFormat {
- /**
- * ARCHIVE_VERSION identifies the format of the contents of the archive.
- * It should be changed any time an incompatible change is made.
- * Its current value is <code>3</code>.
- * <p>
- * <ol>
- * <li> Changed from 2 to 3 with addition of <code>RESOURCE_INSTANCE_INITIALIZE_TOKEN</code>
- * <li> Changed from 3 to 4 with addition of largerBetter boolean in statistic descriptor
- * </ol>
- */
- public static final byte ARCHIVE_VERSION=4;
-
- /**
- * Token consists of a timestamp and any statistic value changes.
- */
- public static final byte SAMPLE_TOKEN=0;
- /**
- * Token defines a new resource type.
- */
- public static final byte RESOURCE_TYPE_TOKEN=1;
- /**
- * Token defines a new resource instance.
- */
- public static final byte RESOURCE_INSTANCE_CREATE_TOKEN=2;
- /**
- * Token notes that a previous resource instance no longer exists
- * and thus will have any more samples of its statistic values taken.
- */
- public static final byte RESOURCE_INSTANCE_DELETE_TOKEN=3;
- /**
- * Token defines a new resource instance with initial data.
- */
- public static final byte RESOURCE_INSTANCE_INITIALIZE_TOKEN=4;
- /**
- * Token defines a new archive and provides some global information
- * about the environment the archive was created in.
- */
- public static final byte HEADER_TOKEN=77;
-
- /**
- * The value used to signal the end of a list of resource instances.
- */
- public static final int ILLEGAL_RESOURCE_INST_ID=-1;
- /**
- * The maximum value a resource inst id can have and still be stored
- * in the archive as an unsigned byte.
- */
- public static final int MAX_BYTE_RESOURCE_INST_ID=252;
- /**
- * Used to say that the next two bytes contain the resource inst id
- * as an unsigned short.
- */
- public static final int SHORT_RESOURCE_INST_ID_TOKEN=253;
- /**
- * Used to say that the next four bytes contain the resource inst id
- * as an int.
- */
- public static final int INT_RESOURCE_INST_ID_TOKEN=254;
- /**
- * Used to say that the current byte represents the ILLEGAL_RESOURCE_INST_ID.
- */
- public static final int ILLEGAL_RESOURCE_INST_ID_TOKEN=255;
- /**
- * The maximum value a resource inst id can have and still be stored
- * in the archive as an unsigned short.
- */
- public static final int MAX_SHORT_RESOURCE_INST_ID=65535;
- /**
- * The value used to signal the end of a list of statistic samples.
- */
- public static final int ILLEGAL_STAT_OFFSET=255;
-
- /**
- * The maximum value a timestamp can have and still be stored
- * in the archive as an unsigned short.
- */
- public static final int MAX_SHORT_TIMESTAMP=65534;
- /**
- * Means the next 4 bytes contain the timestamp as an int.
- */
- public static final int INT_TIMESTAMP_TOKEN=65535;
-
- /**
- * The maximum value a compact value can have and still be stored
- * in the archive as one byte.
- */
- public static final int MAX_1BYTE_COMPACT_VALUE=Byte.MAX_VALUE;
- /**
- * The minimum value a compact value can have and still be stored
- * in the archive as one byte.
- */
- public static final int MIN_1BYTE_COMPACT_VALUE=Byte.MIN_VALUE+7;
- /**
- * The maximum value a compact value can have and still be stored
- * in the archive as two bytes.
- */
- public static final int MAX_2BYTE_COMPACT_VALUE=Short.MAX_VALUE;
- /**
- * The minimum value a compact value can have and still be stored
- * in the archive as two bytes.
- */
- public static final int MIN_2BYTE_COMPACT_VALUE=Short.MIN_VALUE;
-
- /**
- * Means the next 2 bytes hold the compact value's data.
- */
- public static final int COMPACT_VALUE_2_TOKEN=Byte.MIN_VALUE;
- /**
- * Means the next 3 bytes hold the compact value's data.
- */
- public static final int COMPACT_VALUE_3_TOKEN=Byte.MIN_VALUE+1;
- /**
- * Means the next 4 bytes hold the compact value's data.
- */
- public static final int COMPACT_VALUE_4_TOKEN=Byte.MIN_VALUE+2;
- /**
- * Means the next 5 bytes hold the compact value's data.
- */
- public static final int COMPACT_VALUE_5_TOKEN=Byte.MIN_VALUE+3;
- /**
- * Means the next 6 bytes hold the compact value's data.
- */
- public static final int COMPACT_VALUE_6_TOKEN=Byte.MIN_VALUE+4;
- /**
- * Means the next 7 bytes hold the compact value's data.
- */
- public static final int COMPACT_VALUE_7_TOKEN=Byte.MIN_VALUE+5;
- /**
- * Means the next 8 bytes hold the compact value's data.
- */
- public static final int COMPACT_VALUE_8_TOKEN=Byte.MIN_VALUE+6;
-
- /**
- * Statistic represents a <code>boolean</code> java primitive.
- */
- public static final int BOOLEAN_CODE = 1;
- /**
- * Statistic represents a <code>char</code> java primitive.
- */
- public static final int CHAR_CODE = 2;
- /**
- * Statistic represents a <code>char</code> java primitive.
- */
- public static final int WCHAR_CODE = 12;
- /**
- * Statistic represents a <code>byte</code> java primitive.
- */
- public static final int BYTE_CODE = 3;
- /**
- * Statistic represents a <code>short</code> java primitive.
- */
- public static final int SHORT_CODE = 4;
- /**
- * Statistic represents a <code>int</code> java primitive.
- */
- public static final int INT_CODE = 5;
- /**
- * Statistic represents a <code>long</code> java primitive.
- */
- public static final int LONG_CODE = 6;
- /**
- * Statistic represents a <code>float</code> java primitive.
- */
- public static final int FLOAT_CODE = 7;
- /**
- * Statistic represents a <code>double</code> java primitive.
- */
- public static final int DOUBLE_CODE = 8;
- /**
- * Number of nanoseconds in one millisecond
- */
- public static final long NANOS_PER_MILLI = 1000000;
-
-}
[24/24] incubator-geode git commit: GEODE-1781: fix javadocs found
during review of changes for GEODE-1781
Posted by kl...@apache.org.
GEODE-1781: fix javadocs found during review of changes for GEODE-1781
Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/81c1c982
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/81c1c982
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/81c1c982
Branch: refs/heads/feature/GEODE-1781-02
Commit: 81c1c982e40c964861f95035fb6d0f9de3d4ec6b
Parents: 55c5df5
Author: Kirk Lund <kl...@apache.org>
Authored: Tue Aug 16 17:22:11 2016 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Wed Aug 17 15:44:52 2016 -0700
----------------------------------------------------------------------
.../gemfire/internal/cache/tier/sockets/CacheServerStats.java | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/81c1c982/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java
index 360a87c..658b35e 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java
@@ -26,7 +26,7 @@ import com.gemstone.gemfire.distributed.internal.PoolStatHelper;
import com.gemstone.gemfire.internal.SocketCreator;
/**
- * Bridge Server statistic definitions
+ * Cache Server statistic definitions
*/
public class CacheServerStats implements MessageStats {
[05/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderIntegrationTest.java
new file mode 100755
index 0000000..69ec1fb
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderIntegrationTest.java
@@ -0,0 +1,1634 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.gemstone.gemfire.internal.statistics.StatArchiveFormat.NANOS_PER_MILLI;
+import static com.gemstone.gemfire.internal.statistics.TestStatArchiveWriter.*;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.NanoTimer;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatValue;
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+import com.gemstone.gemfire.util.test.TestUtil;
+
+/**
+ * Integration tests for {@link StatArchiveWriter} and {@link StatArchiveReader}.
+ *
+ * @since GemFire 7.0
+ */
+@Category(IntegrationTest.class)
+@SuppressWarnings({ "rawtypes","unused" })
+public class StatArchiveWriterReaderIntegrationTest {
+
+ private static final Logger logger = LogManager.getLogger();
+
+ private File dir;
+ private Map<String,String> statisticTypes;
+ private Map<String,Map<String,Number>> allStatistics;
+ private String archiveFileName;
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUp() throws Exception {
+ this.statisticTypes = new HashMap<>();
+ this.allStatistics = new HashMap<>();
+ this.dir = this.temporaryFolder.getRoot();
+ this.archiveFileName = this.dir.getAbsolutePath() + File.separator + this.testName.getMethodName() + ".gfs";
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ this.statisticTypes = null;
+ this.allStatistics = null;
+ StatisticsTypeFactoryImpl.clear();
+ }
+
+ @Test
+ public void testDoubleCounterOneSample() throws Exception {
+ final TestStatisticsManager manager = new TestStatisticsManager(1, getUniqueName(), WRITER_INITIAL_DATE_MILLIS);
+
+ final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
+ final SampleCollector sampleCollector = new SampleCollector(sampler);
+
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+ sampleCollector.addSampleHandler(writer);
+
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createDoubleCounter("long_double_1", "d1", "u1")
+ };
+
+ final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
+ final double value = 32317.716467;
+ incDouble(st1_1, "long_double_1", value);
+
+ final long sampleIncNanos = NANOS_PER_MILLI * 1000;
+ final long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
+ sampleCollector.sample(sampleTimeNanos);
+
+ writer.close();
+
+ final StatisticDescriptor[] sds = ST1.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ assertEquals(value, st1_1.get(sds[i].getName()));
+ }
+
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{new File(this.archiveFileName)}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ final List resources = reader.getResourceInstList();
+ assertNotNull(resources);
+ assertEquals(1, resources.size());
+
+ final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
+ assertNotNull(ri);
+ final String statsName = ri.getName();
+ assertNotNull(statsName);
+ assertEquals("st1_1", statsName);
+ assertEquals("ST1", ri.getType().getName());
+
+ final StatValue[] statValues = ri.getStatValues();
+ assertNotNull(statValues);
+ assertEquals(1, statValues.length);
+
+ final String statName = ri.getType().getStats()[0].getName();
+ assertNotNull(statName);
+ assertEquals("long_double_1", statName);
+ assertEquals(statName, statValues[0].getDescriptor().getName());
+ assertEquals(1, statValues[0].getSnapshotsSize());
+ assertEquals(value, statValues[0].getSnapshotsMostRecent(), 0.01);
+
+ final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
+ assertNotNull(timeStampsMillis);
+ assertEquals(1, timeStampsMillis.length);
+
+ final long initPreviousTimeStampMillis = NanoTimer.nanosToMillis(WRITER_PREVIOUS_TIMESTAMP_NANOS);
+ final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
+ final long deltaMillis = timeStampMillis - initPreviousTimeStampMillis;
+ assertEquals(NanoTimer.nanosToMillis(sampleIncNanos), deltaMillis);
+
+ final long expectedTimeStampMillis = deltaMillis + WRITER_INITIAL_DATE_MILLIS;
+ assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
+
+ final double[] snapshots = statValues[0].getRawSnapshots();
+ assertNotNull(snapshots);
+ assertEquals(1, snapshots.length);
+ assertEquals(value, snapshots[0], 0.01);
+ }
+
+ @Test
+ public void testIntCounterOneSample() throws Exception {
+ final TestStatisticsManager manager = new TestStatisticsManager(
+ 1,
+ getUniqueName(),
+ WRITER_INITIAL_DATE_MILLIS);
+
+ final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
+ final SampleCollector sampleCollector = new SampleCollector(sampler);
+
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+ sampleCollector.addSampleHandler(writer);
+
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createIntCounter("int_counter_1", "d1", "u1")
+ };
+
+ final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
+ final int value = 5;
+ incInt(st1_1, "int_counter_1", value);
+
+ final long sampleIncNanos = NANOS_PER_MILLI*1000;
+ final long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
+ sampleCollector.sample(sampleTimeNanos);
+
+ writer.close();
+
+ final StatisticDescriptor[] sds = ST1.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ assertEquals(value, st1_1.get(sds[i].getName()));
+ }
+
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{new File(this.archiveFileName)}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ final List resources = reader.getResourceInstList();
+ assertNotNull(resources);
+ assertEquals(1, resources.size());
+
+ final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
+ assertNotNull(ri);
+ final String statsName = ri.getName();
+ assertNotNull(statsName);
+ assertEquals("st1_1", statsName);
+ assertEquals("ST1", ri.getType().getName());
+
+ final StatValue[] statValues = ri.getStatValues();
+ assertNotNull(statValues);
+ assertEquals(1, statValues.length);
+
+ final String statName = ri.getType().getStats()[0].getName();
+ assertNotNull(statName);
+ assertEquals("int_counter_1", statName);
+ assertEquals(statName, statValues[0].getDescriptor().getName());
+ assertEquals(1, statValues[0].getSnapshotsSize());
+ assertEquals((double)value, statValues[0].getSnapshotsMostRecent(), 0.01);
+
+ final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
+ assertNotNull(timeStampsMillis);
+ assertEquals(1, timeStampsMillis.length);
+
+ final long initPreviousTimeStampMillis = NanoTimer.nanosToMillis(WRITER_PREVIOUS_TIMESTAMP_NANOS);
+ final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
+ final long deltaMillis = timeStampMillis - initPreviousTimeStampMillis;
+ assertEquals(NanoTimer.nanosToMillis(sampleIncNanos), deltaMillis);
+
+ final long expectedTimeStampMillis = deltaMillis + WRITER_INITIAL_DATE_MILLIS;
+ assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
+
+ final double[] snapshots = statValues[0].getRawSnapshots();
+ assertNotNull(snapshots);
+ assertEquals(1, snapshots.length);
+ assertEquals((double)value, snapshots[0], 0.01);
+ }
+
+ @Test
+ public void testIntGaugeOneSample() throws Exception {
+ final TestStatisticsManager manager = new TestStatisticsManager(
+ 1,
+ getUniqueName(),
+ WRITER_INITIAL_DATE_MILLIS);
+
+ final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
+ final SampleCollector sampleCollector = new SampleCollector(sampler);
+
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+ sampleCollector.addSampleHandler(writer);
+
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createIntGauge("int_gauge_1", "d1", "u1")
+ };
+
+ final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
+ final int value = 5;
+ incInt(st1_1, "int_gauge_1", value);
+
+ final long sampleIncNanos = NANOS_PER_MILLI*1000;
+ final long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
+ sampleCollector.sample(sampleTimeNanos);
+
+ writer.close();
+
+ final StatisticDescriptor[] sds = ST1.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ assertEquals(value, st1_1.get(sds[i].getName()));
+ }
+
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{new File(this.archiveFileName)}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ final List resources = reader.getResourceInstList();
+ assertNotNull(resources);
+ assertEquals(1, resources.size());
+
+ final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
+ assertNotNull(ri);
+ final String statsName = ri.getName();
+ assertNotNull(statsName);
+ assertEquals("st1_1", statsName);
+ assertEquals("ST1", ri.getType().getName());
+
+ final StatValue[] statValues = ri.getStatValues();
+ assertNotNull(statValues);
+ assertEquals(1, statValues.length);
+
+ final String statName = ri.getType().getStats()[0].getName();
+ assertNotNull(statName);
+ assertEquals("int_gauge_1", statName);
+ assertEquals(statName, statValues[0].getDescriptor().getName());
+ assertEquals(1, statValues[0].getSnapshotsSize());
+ assertEquals((double)value, statValues[0].getSnapshotsMostRecent(), 0.01);
+
+ final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
+ assertNotNull(timeStampsMillis);
+ assertEquals(1, timeStampsMillis.length);
+
+ final long initialPreviousTimeStampMillis = NanoTimer.nanosToMillis(WRITER_PREVIOUS_TIMESTAMP_NANOS);
+ final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
+ final long deltaMillis = timeStampMillis - initialPreviousTimeStampMillis;
+ assertEquals(NanoTimer.nanosToMillis(sampleIncNanos), deltaMillis);
+
+ final long expectedTimeStampMillis = deltaMillis + WRITER_INITIAL_DATE_MILLIS;
+ assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
+
+ final double[] snapshots = statValues[0].getRawSnapshots();
+ assertNotNull(snapshots);
+ assertEquals(1, snapshots.length);
+ assertEquals((double)value, snapshots[0], 0.01);
+ }
+
+ @Test
+ public void testLongCounterOneSample() throws Exception {
+ final TestStatisticsManager manager = new TestStatisticsManager(
+ 1,
+ getUniqueName(),
+ WRITER_INITIAL_DATE_MILLIS);
+
+ final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
+ final SampleCollector sampleCollector = new SampleCollector(sampler);
+
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+ sampleCollector.addSampleHandler(writer);
+
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createLongCounter("long_counter_1", "d1", "u1")
+ };
+
+ final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
+ final long value = 5;
+ incLong(st1_1, "long_counter_1", value);
+
+ final long sampleIncNanos = NANOS_PER_MILLI*1000;
+ final long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
+ sampleCollector.sample(sampleTimeNanos);
+
+ writer.close();
+
+ final StatisticDescriptor[] sds = ST1.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ assertEquals(value, st1_1.get(sds[i].getName()));
+ }
+
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{new File(this.archiveFileName)}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ final List resources = reader.getResourceInstList();
+ assertNotNull(resources);
+ assertEquals(1, resources.size());
+
+ final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
+ assertNotNull(ri);
+ final String statsName = ri.getName();
+ assertNotNull(statsName);
+ assertEquals("st1_1", statsName);
+ assertEquals("ST1", ri.getType().getName());
+
+ final StatValue[] statValues = ri.getStatValues();
+ assertNotNull(statValues);
+ assertEquals(1, statValues.length);
+
+ final String statName = ri.getType().getStats()[0].getName();
+ assertNotNull(statName);
+ assertEquals("long_counter_1", statName);
+ assertEquals(statName, statValues[0].getDescriptor().getName());
+ assertEquals(1, statValues[0].getSnapshotsSize());
+ assertEquals((double)value, statValues[0].getSnapshotsMostRecent(), 0.01);
+
+ final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
+ assertNotNull(timeStampsMillis);
+ assertEquals(1, timeStampsMillis.length);
+
+ final long initialPreviousTimeStampMillis = NanoTimer.nanosToMillis(WRITER_PREVIOUS_TIMESTAMP_NANOS);
+ final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
+ final long deltaMillis = timeStampMillis - initialPreviousTimeStampMillis;
+ assertEquals(NanoTimer.nanosToMillis(sampleIncNanos), deltaMillis);
+
+ final long expectedTimeStampMillis = deltaMillis + WRITER_INITIAL_DATE_MILLIS;
+ assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
+
+ final double[] snapshots = statValues[0].getRawSnapshots();
+ assertNotNull(snapshots);
+ assertEquals(1, snapshots.length);
+ assertEquals((double)value, snapshots[0], 0.01);
+ }
+
+ @Test
+ public void testLongGaugeOneSample() throws Exception {
+ final TestStatisticsManager manager = new TestStatisticsManager(
+ 1,
+ getUniqueName(),
+ WRITER_INITIAL_DATE_MILLIS);
+
+ final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
+ final SampleCollector sampleCollector = new SampleCollector(sampler);
+
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+ sampleCollector.addSampleHandler(writer);
+
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createLongGauge("long_gauge_1", "d1", "u1")
+ };
+
+ final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
+ incLong(st1_1, "long_gauge_1", 5);
+
+ final long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + NANOS_PER_MILLI*2;
+ sampleCollector.sample(sampleTimeNanos);
+
+ writer.close();
+
+ final StatisticDescriptor[] sds = ST1.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ assertEquals(5L, st1_1.get(sds[i].getName()));
+ }
+
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{new File(this.archiveFileName)}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ final List resources = reader.getResourceInstList();
+ assertNotNull(resources);
+ assertEquals(1, resources.size());
+
+ final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
+ assertNotNull(ri);
+ final String statsName = ri.getName();
+ assertNotNull(statsName);
+ assertEquals("st1_1", statsName);
+ assertEquals("ST1", ri.getType().getName());
+
+ final StatValue[] statValues = ri.getStatValues();
+ assertNotNull(statValues);
+ assertEquals(1, statValues.length);
+
+ final String statName = ri.getType().getStats()[0].getName();
+ assertNotNull(statName);
+ assertEquals("long_gauge_1", statName);
+ assertEquals(statName, statValues[0].getDescriptor().getName());
+ assertEquals(1, statValues[0].getSnapshotsSize());
+ assertEquals(5.0, statValues[0].getSnapshotsMostRecent(), 0.01);
+
+ final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
+ assertNotNull(timeStampsMillis);
+ assertEquals(1, timeStampsMillis.length);
+
+ final long initialPreviousTimeStampMillis = NanoTimer.nanosToMillis(WRITER_PREVIOUS_TIMESTAMP_NANOS);
+ final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
+ final long deltaMillis = timeStampMillis - initialPreviousTimeStampMillis;
+ assertEquals(2, deltaMillis);
+
+ final long expectedTimeStampMillis = deltaMillis + WRITER_INITIAL_DATE_MILLIS;
+ assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
+
+ final double[] snapshots = statValues[0].getRawSnapshots();
+ assertNotNull(snapshots);
+ assertEquals(1, snapshots.length);
+ assertEquals(5.0, snapshots[0], 0.01);
+ }
+
+ @Test
+ public void testLongCounterTwoSamples() throws Exception {
+ final TestStatisticsManager manager = new TestStatisticsManager(
+ 1,
+ getUniqueName(),
+ WRITER_INITIAL_DATE_MILLIS);
+
+ final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
+ final SampleCollector sampleCollector = new SampleCollector(sampler);
+
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+ sampleCollector.addSampleHandler(writer);
+
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createLongCounter("long_counter_1", "d1", "u1")
+ };
+
+ final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
+ final long value1 = 5;
+ incLong(st1_1, "long_counter_1", value1);
+
+ final long sampleIncNanos = NANOS_PER_MILLI*1000;
+ long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
+ sampleCollector.sample(sampleTimeNanos);
+
+ final long value2 = 15;
+ incLong(st1_1, "long_counter_1", value2);
+ sampleTimeNanos += sampleIncNanos;
+ sampleCollector.sample(sampleTimeNanos);
+
+ writer.close();
+
+ final StatisticDescriptor[] sds = ST1.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ assertEquals(value1 + value2, st1_1.get(sds[i].getName()));
+ }
+
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{new File(this.archiveFileName)}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ final List resources = reader.getResourceInstList();
+ assertNotNull(resources);
+ assertEquals(1, resources.size());
+
+ final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
+ assertNotNull(ri);
+ final String statsName = ri.getName();
+ assertNotNull(statsName);
+ assertEquals("st1_1", statsName);
+ assertEquals("ST1", ri.getType().getName());
+
+ final StatValue[] statValues = ri.getStatValues();
+ assertNotNull(statValues);
+ assertEquals(1, statValues.length);
+
+ statValues[0].setFilter(StatValue.FILTER_NONE);
+
+ final String statName = ri.getType().getStats()[0].getName();
+ assertNotNull(statName);
+ assertEquals("long_counter_1", statName);
+ assertEquals(statName, statValues[0].getDescriptor().getName());
+ assertEquals(2, statValues[0].getSnapshotsSize());
+ assertEquals((double)(value1+value2), statValues[0].getSnapshotsMostRecent(), 0.01);
+
+ final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
+ assertNotNull(timeStampsMillis);
+ assertEquals(2, timeStampsMillis.length);
+
+ final long initialPreviousTimeStampMillis = NanoTimer.nanosToMillis(WRITER_PREVIOUS_TIMESTAMP_NANOS);
+ final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
+ final long deltaMillis = timeStampMillis - initialPreviousTimeStampMillis;
+ assertEquals(NanoTimer.nanosToMillis(sampleIncNanos*2), deltaMillis);
+
+ long expectedTimeStampMillis = WRITER_INITIAL_DATE_MILLIS;
+ for (int i = 0; i < timeStampsMillis.length; i++) {
+ expectedTimeStampMillis += 1000;
+ assertEquals("expectedTimeStampMillis for " + i + " is wrong", expectedTimeStampMillis, timeStampsMillis[i]);
+ }
+
+ final double[] snapshots = statValues[0].getRawSnapshots();
+ assertNotNull(snapshots);
+ assertEquals(2, snapshots.length);
+ assertEquals((double)value1, snapshots[0], 0.01);
+ assertEquals((double)(value1+value2), snapshots[1], 0.01);
+ }
+
+ /**
+ * Tests the stat archive file written by StatArchiveWriter.
+ */
+ @Test
+ public void testWriteAfterSamplingBegins() throws Exception {
+ final TestStatisticsManager manager = new TestStatisticsManager(
+ 1,
+ getUniqueName(),
+ WRITER_INITIAL_DATE_MILLIS);
+
+ final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
+ final SampleCollector sampleCollector = new SampleCollector(sampler);
+
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS - 2000)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+ sampleCollector.addSampleHandler(writer);
+
+ long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + NANOS_PER_MILLI*1000;
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 1) create ST1 and st1_1
+
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createDoubleCounter("double_counter_1", "d1", "u1"),
+ manager.createDoubleCounter("double_counter_2", "d2", "u2", true),
+ manager.createDoubleGauge( "double_gauge_3", "d3", "u3"),
+ manager.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
+ manager.createIntCounter( "int_counter_5", "d5", "u5"),
+ manager.createIntCounter( "int_counter_6", "d6", "u6", true),
+ manager.createIntGauge( "int_gauge_7", "d7", "u7"),
+ manager.createIntGauge( "int_gauge_8", "d8", "u8", false),
+ manager.createLongCounter( "long_counter_9", "d9", "u9"),
+ manager.createLongCounter( "long_counter_10", "d10", "u10", true),
+ manager.createLongGauge( "long_gauge_11", "d11", "u11"),
+ manager.createLongGauge( "long_gauge_12", "d12", "u12", false)
+ };
+ final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
+
+ // 2) create st1_2
+
+ final Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2", 2);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 3) some new values
+
+ incDouble(st1_1, "double_counter_1", 18347.94880);
+ incDouble(st1_1, "double_gauge_4", 24885.02346);
+ incInt(st1_1, "int_counter_5", 3);
+ incInt(st1_1, "int_gauge_8", 4);
+ incLong(st1_1, "long_counter_9", 1073741824);
+ incLong(st1_1, "long_gauge_12", 154367897);
+
+ incDouble(st1_2, "double_counter_2", 346.95);
+ incDouble(st1_2, "double_gauge_3", 9865.23008);
+ incInt(st1_2, "int_counter_6", 4);
+ incInt(st1_2, "int_gauge_7", 3);
+ incLong(st1_2, "long_counter_10", 3497536);
+ incLong(st1_2, "long_gauge_11", 103909646);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 4) all new values
+
+ incDouble(st1_1, "double_counter_1", 1.098367);
+ incDouble(st1_1, "double_counter_2", 50247.0983254);
+ incDouble(st1_1, "double_gauge_3", 987654.2344);
+ incDouble(st1_1, "double_gauge_4", 23.097);
+ incInt(st1_1, "int_counter_5", 3);
+ incInt(st1_1, "int_counter_6", 4);
+ incInt(st1_1, "int_gauge_7", 3);
+ incInt(st1_1, "int_gauge_8", 4);
+ incLong(st1_1, "long_counter_9", 5);
+ incLong(st1_1, "long_counter_10", 465793);
+ incLong(st1_1, "long_gauge_11", -203050);
+ incLong(st1_1, "long_gauge_12", 6);
+
+ incDouble(st1_2, "double_counter_1", 0.000846643);
+ incDouble(st1_2, "double_counter_2", 4.0);
+ incDouble(st1_2, "double_gauge_3", -4.0);
+ incDouble(st1_2, "double_gauge_4", 19276.0346624);
+ incInt(st1_2, "int_counter_5", 1);
+ incInt(st1_2, "int_counter_6", 2);
+ incInt(st1_2, "int_gauge_7", -1);
+ incInt(st1_2, "int_gauge_8", -2);
+ incLong(st1_2, "long_counter_9", 309876);
+ incLong(st1_2, "long_counter_10", 4);
+ incLong(st1_2, "long_gauge_11", -4);
+ incLong(st1_2, "long_gauge_12", 1098764);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 5) no new values
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 6) some new values
+
+ incDouble(st1_1, "double_counter_2", 10.255);
+ incDouble(st1_1, "double_gauge_3", -4123.05);
+ incInt(st1_1, "int_counter_6", 2);
+ incInt(st1_1, "int_gauge_7", 3);
+ incLong(st1_1, "long_counter_10", 4);
+ incLong(st1_1, "long_gauge_11", -2);
+
+ incDouble(st1_2, "double_counter_1", 5.00007634);
+ incDouble(st1_2, "double_gauge_4", 16904.06524);
+ incInt(st1_2, "int_counter_5", 4);
+ incInt(st1_2, "int_gauge_8", 1);
+ incLong(st1_2, "long_counter_9", 8);
+ incLong(st1_2, "long_gauge_12", 10);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 7) all new values
+
+ incDouble(st1_1, "double_counter_1", 4065.340);
+ incDouble(st1_1, "double_counter_2", 2.01342568);
+ incDouble(st1_1, "double_gauge_3", 1.367890);
+ incDouble(st1_1, "double_gauge_4", 8.0549003);
+ incInt(st1_1, "int_counter_5", 2);
+ incInt(st1_1, "int_counter_6", 9);
+ incInt(st1_1, "int_gauge_7", 1);
+ incInt(st1_1, "int_gauge_8", 2);
+ incLong(st1_1, "long_counter_9", 6);
+ incLong(st1_1, "long_counter_10", 2);
+ incLong(st1_1, "long_gauge_11", -10);
+ incLong(st1_1, "long_gauge_12", 8);
+
+ incDouble(st1_2, "double_counter_1", 128.2450);
+ incDouble(st1_2, "double_counter_2", 113.550);
+ incDouble(st1_2, "double_gauge_3", 21.0676);
+ incDouble(st1_2, "double_gauge_4", 2.01346);
+ incInt(st1_2, "int_counter_5", 3);
+ incInt(st1_2, "int_counter_6", 4);
+ incInt(st1_2, "int_gauge_7", 4);
+ incInt(st1_2, "int_gauge_8", 2);
+ incLong(st1_2, "long_counter_9", 1);
+ incLong(st1_2, "long_counter_10", 2);
+ incLong(st1_2, "long_gauge_11", 3);
+ incLong(st1_2, "long_gauge_12", -2);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 8) create ST2 and ST3 and st2_1 and st3_1 and st3_2
+
+ final StatisticDescriptor[] statsST2 = new StatisticDescriptor[] {
+ manager.createIntGauge( "int_gauge_7", "d7", "u7"),
+ manager.createIntGauge( "int_gauge_8", "d8", "u8", false),
+ manager.createLongCounter( "long_counter_9", "d9", "u9"),
+ manager.createLongCounter( "long_counter_10", "d10", "u10", true),
+ manager.createLongGauge( "long_gauge_11", "d11", "u11"),
+ manager.createLongGauge( "long_gauge_12", "d12", "u12", false)
+ };
+ final StatisticsType ST2 = manager.createType("ST2", "ST2", statsST2);
+ final Statistics st2_1 = manager.createAtomicStatistics(ST2, "st2_1", 1);
+
+ final StatisticDescriptor[] statsST3 = new StatisticDescriptor[] {
+ manager.createDoubleCounter("double_counter_1", "d1", "u1"),
+ manager.createDoubleCounter("double_counter_2", "d2", "u2", true),
+ manager.createDoubleGauge( "double_gauge_3", "d3", "u3"),
+ manager.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
+ manager.createIntCounter( "int_counter_5", "d5", "u5"),
+ manager.createIntCounter( "int_counter_6", "d6", "u6", true),
+ };
+ final StatisticsType ST3 = manager.createType("ST3", "ST3", statsST3);
+ final Statistics st3_1 = manager.createAtomicStatistics(ST3, "st3_1", 1);
+ final Statistics st3_2 = manager.createAtomicStatistics(ST3, "st3_2", 2);
+
+ // 9) all new values
+
+ incDouble(st1_1, "double_counter_1", 9499.10);
+ incDouble(st1_1, "double_counter_2", 83.0);
+ incDouble(st1_1, "double_gauge_3", -7.05678);
+ incDouble(st1_1, "double_gauge_4", 5111.031);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 3);
+ incInt(st1_1, "int_gauge_7", 9);
+ incInt(st1_1, "int_gauge_8", -3);
+ incLong(st1_1, "long_counter_9", 3);
+ incLong(st1_1, "long_counter_10", 8);
+ incLong(st1_1, "long_gauge_11", 5);
+ incLong(st1_1, "long_gauge_12", 4);
+
+ incDouble(st1_2, "double_counter_1", 2509.0235);
+ incDouble(st1_2, "double_counter_2", 409.10063);
+ incDouble(st1_2, "double_gauge_3", -42.66904);
+ incDouble(st1_2, "double_gauge_4", 21.0098);
+ incInt(st1_2, "int_counter_5", 8);
+ incInt(st1_2, "int_counter_6", 9);
+ incInt(st1_2, "int_gauge_7", -2);
+ incInt(st1_2, "int_gauge_8", 6);
+ incLong(st1_2, "long_counter_9", 4);
+ incLong(st1_2, "long_counter_10", 5);
+ incLong(st1_2, "long_gauge_11", 5);
+ incLong(st1_2, "long_gauge_12", -1);
+
+ incInt(st2_1, "int_gauge_7", 2);
+ incInt(st2_1, "int_gauge_8", -1);
+ incLong(st2_1, "long_counter_9", 1002948);
+ incLong(st2_1, "long_counter_10", 29038856);
+ incLong(st2_1, "long_gauge_11", -2947465);
+ incLong(st2_1, "long_gauge_12", 4934745);
+
+ incDouble(st3_1, "double_counter_1", 562.0458);
+ incDouble(st3_1, "double_counter_2", 14.0086);
+ incDouble(st3_1, "double_gauge_3", -2.0);
+ incDouble(st3_1, "double_gauge_4", 1.0);
+ incInt(st3_1, "int_counter_5", 2);
+ incInt(st3_1, "int_counter_6", 1);
+
+ incDouble(st3_2, "double_counter_1", 33.087);
+ incDouble(st3_2, "double_counter_2", 2.02);
+ incDouble(st3_2, "double_gauge_3", 1.06);
+ incDouble(st3_2, "double_gauge_4", 3.021);
+ incInt(st3_2, "int_counter_5", 1);
+ incInt(st3_2, "int_counter_6", 4);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 10) some new values
+
+ incDouble(st1_1, "double_counter_1", 3.014);
+ incDouble(st1_1, "double_gauge_3", 57.003);
+ incInt(st1_1, "int_counter_5", 3);
+ incInt(st1_1, "int_gauge_7", 5);
+ incLong(st1_1, "long_counter_9", 1);
+ incLong(st1_1, "long_gauge_11", 1);
+
+ incDouble(st1_2, "double_counter_2", 20.107);
+ incDouble(st1_2, "double_gauge_4", 1.5078);
+ incInt(st1_2, "int_counter_6", 1);
+ incInt(st1_2, "int_gauge_8", -1);
+ incLong(st1_2, "long_counter_10", 1073741824);
+ incLong(st1_2, "long_gauge_12", 5);
+
+ incInt(st2_1, "int_gauge_7", 2);
+ incLong(st2_1, "long_counter_9", 2);
+ incLong(st2_1, "long_gauge_11", -2);
+
+ incDouble(st3_1, "double_counter_1", 24.80097);
+ incDouble(st3_1, "double_gauge_3", -22.09834);
+ incInt(st3_1, "int_counter_5", 2);
+
+ incDouble(st3_2, "double_counter_2", 21.0483);
+ incDouble(st3_2, "double_gauge_4", 36310.012);
+ incInt(st3_2, "int_counter_6", 4);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 11) remove ST2 and st2_1
+
+ manager.destroyStatistics(st2_1);
+
+ // 12) some new values
+
+ incDouble(st1_1, "double_counter_1", 339.0803);
+ incDouble(st1_1, "double_counter_2", 21.06);
+ incDouble(st1_1, "double_gauge_3", 12.056);
+ incDouble(st1_1, "double_gauge_4", 27.108);
+ incInt(st1_1, "int_counter_5", 2);
+ incInt(st1_1, "int_counter_6", 4);
+
+ incInt(st1_2, "int_gauge_7", 4);
+ incInt(st1_2, "int_gauge_8", 7);
+ incLong(st1_2, "long_counter_9", 8);
+ incLong(st1_2, "long_counter_10", 4);
+ incLong(st1_2, "long_gauge_11", 2);
+ incLong(st1_2, "long_gauge_12", 1);
+
+ incDouble(st3_1, "double_counter_1", 41.103);
+ incDouble(st3_1, "double_counter_2", 2.0333);
+ incDouble(st3_1, "double_gauge_3", -14.0);
+
+ incDouble(st3_2, "double_gauge_4", 26.01);
+ incInt(st3_2, "int_counter_5", 3);
+ incInt(st3_2, "int_counter_6", 1);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 13) no new values
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 14) remove st1_2
+
+ manager.destroyStatistics(st1_2);
+
+ // 15) all new values
+
+ incDouble(st1_1, "double_counter_1", 62.1350);
+ incDouble(st1_1, "double_counter_2", 33.306);
+ incDouble(st1_1, "double_gauge_3", 41.1340);
+ incDouble(st1_1, "double_gauge_4", -1.04321);
+ incInt(st1_1, "int_counter_5", 2);
+ incInt(st1_1, "int_counter_6", 2);
+ incInt(st1_1, "int_gauge_7", 1);
+ incInt(st1_1, "int_gauge_8", 9);
+ incLong(st1_1, "long_counter_9", 2);
+ incLong(st1_1, "long_counter_10", 5);
+ incLong(st1_1, "long_gauge_11", 3);
+ incLong(st1_1, "long_gauge_12", -2);
+
+ incDouble(st3_1, "double_counter_1", 3461.0153);
+ incDouble(st3_1, "double_counter_2", 5.03167);
+ incDouble(st3_1, "double_gauge_3", -1.31051);
+ incDouble(st3_1, "double_gauge_4", 71.031);
+ incInt(st3_1, "int_counter_5", 4);
+ incInt(st3_1, "int_counter_6", 2);
+
+ incDouble(st3_2, "double_counter_1", 531.5608);
+ incDouble(st3_2, "double_counter_2", 55.0532);
+ incDouble(st3_2, "double_gauge_3", 8.40956);
+ incDouble(st3_2, "double_gauge_4", 23230.0462);
+ incInt(st3_2, "int_counter_5", 9);
+ incInt(st3_2, "int_counter_6", 5);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // close the writer
+
+ writer.close();
+
+ // print out all the stat values
+
+ if (false) {
+ StatisticDescriptor[]
+ sds = ST1.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st1_1#" + sds[i].getName() + "=" + st1_1.get(sds[i].getName()));
+ }
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st1_2#" + sds[i].getName() + "=" + st1_2.get(sds[i].getName()));
+ }
+
+ sds = ST2.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st2_1#" + sds[i].getName() + "=" + st2_1.get(sds[i].getName()));
+ }
+
+ sds = ST3.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st3_1#" + sds[i].getName() + "=" + st3_1.get(sds[i].getName()));
+ }
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st3_2#" + sds[i].getName() + "=" + st3_2.get(sds[i].getName()));
+ }
+ }
+
+ // validate that stat archive file exists
+
+ final File actual = new File(this.archiveFileName);
+ assertTrue(actual.exists());
+
+ // validate content of stat archive file using StatArchiveReader
+
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{actual}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ final List resources = reader.getResourceInstList();
+ for (final Iterator iter = resources.iterator(); iter.hasNext();) {
+ final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
+ final String resourceName = ri.getName();
+ assertNotNull(resourceName);
+
+ final String expectedStatsType = this.statisticTypes.get(resourceName);
+ assertNotNull(expectedStatsType);
+ assertEquals(expectedStatsType, ri.getType().getName());
+
+ final Map<String,Number> expectedStatValues = this.allStatistics.get(resourceName);
+ assertNotNull(expectedStatValues);
+
+ final StatValue[] statValues = ri.getStatValues();
+ for (int i = 0; i < statValues.length; i++) {
+ final String statName = ri.getType().getStats()[i].getName();
+ assertNotNull(statName);
+ assertNotNull(expectedStatValues.get(statName));
+
+ assertEquals(statName, statValues[i].getDescriptor().getName());
+
+ statValues[i].setFilter(StatValue.FILTER_NONE);
+ final double[] rawSnapshots = statValues[i].getRawSnapshots();
+ //for (int j = 0; j < rawSnapshots.length; j++) {
+ // logger.info("DEBUG " + ri.getName() + " " + statName + " rawSnapshots[" + j + "] = " + rawSnapshots[j]);
+ //}
+ assertEquals("Value " + i + " for " + statName + " is wrong: " + expectedStatValues,
+ expectedStatValues.get(statName).doubleValue(),
+ statValues[i].getSnapshotsMostRecent(), 0.01);
+ }
+ }
+
+ // validate byte content of stat archive file against saved expected file
+
+ final File expected = new File(TestUtil.getResourcePath(getClass(), "StatArchiveWriterReaderJUnitTest_" + this.testName.getMethodName() + "_expected.gfs"));
+ assertTrue(expected + " does not exist!", expected.exists());
+ assertEquals(expected.length(), actual.length());
+
+ assertTrue("Actual stat archive file bytes differ from expected stat archive file bytes!",
+ Arrays.equals(readBytes(expected), readBytes(actual)));
+ }
+
+ /**
+ * Tests the stat archive file written by StatArchiveWriter.
+ */
+ @Test
+ public void testWriteWhenSamplingBegins() throws Exception {
+ final TestStatisticsManager manager = new TestStatisticsManager(
+ 1,
+ getUniqueName(),
+ WRITER_INITIAL_DATE_MILLIS);
+
+ final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
+ final SampleCollector sampleCollector = new SampleCollector(sampler);
+
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS - 2000)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+ sampleCollector.addSampleHandler(writer);
+
+ long sampleTimeNanos = WRITER_PREVIOUS_TIMESTAMP_NANOS + NANOS_PER_MILLI*1000;
+
+ // 1) create ST1 and st1_1
+
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createDoubleCounter("double_counter_1", "d1", "u1"),
+ manager.createDoubleCounter("double_counter_2", "d2", "u2", true),
+ manager.createDoubleGauge( "double_gauge_3", "d3", "u3"),
+ manager.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
+ manager.createIntCounter( "int_counter_5", "d5", "u5"),
+ manager.createIntCounter( "int_counter_6", "d6", "u6", true),
+ manager.createIntGauge( "int_gauge_7", "d7", "u7"),
+ manager.createIntGauge( "int_gauge_8", "d8", "u8", false),
+ manager.createLongCounter( "long_counter_9", "d9", "u9"),
+ manager.createLongCounter( "long_counter_10", "d10", "u10", true),
+ manager.createLongGauge( "long_gauge_11", "d11", "u11"),
+ manager.createLongGauge( "long_gauge_12", "d12", "u12", false)
+ };
+ final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
+
+ // 2) create st1_2
+
+ final Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2", 2);
+
+ // 3) some new values
+
+ incDouble(st1_1, "double_counter_1", 18347.94880);
+ incDouble(st1_1, "double_gauge_4", 24885.02346);
+ incInt(st1_1, "int_counter_5", 3);
+ incInt(st1_1, "int_gauge_8", 4);
+ incLong(st1_1, "long_counter_9", 1073741824);
+ incLong(st1_1, "long_gauge_12", 154367897);
+
+ incDouble(st1_2, "double_counter_2", 346.95);
+ incDouble(st1_2, "double_gauge_3", 9865.23008);
+ incInt(st1_2, "int_counter_6", 4);
+ incInt(st1_2, "int_gauge_7", 3);
+ incLong(st1_2, "long_counter_10", 3497536);
+ incLong(st1_2, "long_gauge_11", 103909646);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 4) all new values
+
+ incDouble(st1_1, "double_counter_1", 1.098367);
+ incDouble(st1_1, "double_counter_2", 50247.0983254);
+ incDouble(st1_1, "double_gauge_3", 987654.2344);
+ incDouble(st1_1, "double_gauge_4", 23.097);
+ incInt(st1_1, "int_counter_5", 3);
+ incInt(st1_1, "int_counter_6", 4);
+ incInt(st1_1, "int_gauge_7", 3);
+ incInt(st1_1, "int_gauge_8", 4);
+ incLong(st1_1, "long_counter_9", 5);
+ incLong(st1_1, "long_counter_10", 465793);
+ incLong(st1_1, "long_gauge_11", -203050);
+ incLong(st1_1, "long_gauge_12", 6);
+
+ incDouble(st1_2, "double_counter_1", 0.000846643);
+ incDouble(st1_2, "double_counter_2", 4.0);
+ incDouble(st1_2, "double_gauge_3", -4.0);
+ incDouble(st1_2, "double_gauge_4", 19276.0346624);
+ incInt(st1_2, "int_counter_5", 1);
+ incInt(st1_2, "int_counter_6", 2);
+ incInt(st1_2, "int_gauge_7", -1);
+ incInt(st1_2, "int_gauge_8", -2);
+ incLong(st1_2, "long_counter_9", 309876);
+ incLong(st1_2, "long_counter_10", 4);
+ incLong(st1_2, "long_gauge_11", -4);
+ incLong(st1_2, "long_gauge_12", 1098764);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 5) no new values
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 6) some new values
+
+ incDouble(st1_1, "double_counter_2", 10.255);
+ incDouble(st1_1, "double_gauge_3", -4123.05);
+ incInt(st1_1, "int_counter_6", 2);
+ incInt(st1_1, "int_gauge_7", 3);
+ incLong(st1_1, "long_counter_10", 4);
+ incLong(st1_1, "long_gauge_11", -2);
+
+ incDouble(st1_2, "double_counter_1", 5.00007634);
+ incDouble(st1_2, "double_gauge_4", 16904.06524);
+ incInt(st1_2, "int_counter_5", 4);
+ incInt(st1_2, "int_gauge_8", 1);
+ incLong(st1_2, "long_counter_9", 8);
+ incLong(st1_2, "long_gauge_12", 10);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 7) all new values
+
+ incDouble(st1_1, "double_counter_1", 4065.340);
+ incDouble(st1_1, "double_counter_2", 2.01342568);
+ incDouble(st1_1, "double_gauge_3", 1.367890);
+ incDouble(st1_1, "double_gauge_4", 8.0549003);
+ incInt(st1_1, "int_counter_5", 2);
+ incInt(st1_1, "int_counter_6", 9);
+ incInt(st1_1, "int_gauge_7", 1);
+ incInt(st1_1, "int_gauge_8", 2);
+ incLong(st1_1, "long_counter_9", 6);
+ incLong(st1_1, "long_counter_10", 2);
+ incLong(st1_1, "long_gauge_11", -10);
+ incLong(st1_1, "long_gauge_12", 8);
+
+ incDouble(st1_2, "double_counter_1", 128.2450);
+ incDouble(st1_2, "double_counter_2", 113.550);
+ incDouble(st1_2, "double_gauge_3", 21.0676);
+ incDouble(st1_2, "double_gauge_4", 2.01346);
+ incInt(st1_2, "int_counter_5", 3);
+ incInt(st1_2, "int_counter_6", 4);
+ incInt(st1_2, "int_gauge_7", 4);
+ incInt(st1_2, "int_gauge_8", 2);
+ incLong(st1_2, "long_counter_9", 1);
+ incLong(st1_2, "long_counter_10", 2);
+ incLong(st1_2, "long_gauge_11", 3);
+ incLong(st1_2, "long_gauge_12", -2);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 8) create ST2 and ST3 and st2_1 and st3_1 and st3_2
+
+ final StatisticDescriptor[] statsST2 = new StatisticDescriptor[] {
+ manager.createIntGauge( "int_gauge_7", "d7", "u7"),
+ manager.createIntGauge( "int_gauge_8", "d8", "u8", false),
+ manager.createLongCounter( "long_counter_9", "d9", "u9"),
+ manager.createLongCounter( "long_counter_10", "d10", "u10", true),
+ manager.createLongGauge( "long_gauge_11", "d11", "u11"),
+ manager.createLongGauge( "long_gauge_12", "d12", "u12", false)
+ };
+ final StatisticsType ST2 = manager.createType("ST2", "ST2", statsST2);
+ final Statistics st2_1 = manager.createAtomicStatistics(ST2, "st2_1", 1);
+
+ final StatisticDescriptor[] statsST3 = new StatisticDescriptor[] {
+ manager.createDoubleCounter("double_counter_1", "d1", "u1"),
+ manager.createDoubleCounter("double_counter_2", "d2", "u2", true),
+ manager.createDoubleGauge( "double_gauge_3", "d3", "u3"),
+ manager.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
+ manager.createIntCounter( "int_counter_5", "d5", "u5"),
+ manager.createIntCounter( "int_counter_6", "d6", "u6", true),
+ };
+ final StatisticsType ST3 = manager.createType("ST3", "ST3", statsST3);
+ final Statistics st3_1 = manager.createAtomicStatistics(ST3, "st3_1", 1);
+ final Statistics st3_2 = manager.createAtomicStatistics(ST3, "st3_2", 2);
+
+ // 9) all new values
+
+ incDouble(st1_1, "double_counter_1", 9499.10);
+ incDouble(st1_1, "double_counter_2", 83.0);
+ incDouble(st1_1, "double_gauge_3", -7.05678);
+ incDouble(st1_1, "double_gauge_4", 5111.031);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 3);
+ incInt(st1_1, "int_gauge_7", 9);
+ incInt(st1_1, "int_gauge_8", -3);
+ incLong(st1_1, "long_counter_9", 3);
+ incLong(st1_1, "long_counter_10", 8);
+ incLong(st1_1, "long_gauge_11", 5);
+ incLong(st1_1, "long_gauge_12", 4);
+
+ incDouble(st1_2, "double_counter_1", 2509.0235);
+ incDouble(st1_2, "double_counter_2", 409.10063);
+ incDouble(st1_2, "double_gauge_3", -42.66904);
+ incDouble(st1_2, "double_gauge_4", 21.0098);
+ incInt(st1_2, "int_counter_5", 8);
+ incInt(st1_2, "int_counter_6", 9);
+ incInt(st1_2, "int_gauge_7", -2);
+ incInt(st1_2, "int_gauge_8", 6);
+ incLong(st1_2, "long_counter_9", 4);
+ incLong(st1_2, "long_counter_10", 5);
+ incLong(st1_2, "long_gauge_11", 5);
+ incLong(st1_2, "long_gauge_12", -1);
+
+ incInt(st2_1, "int_gauge_7", 2);
+ incInt(st2_1, "int_gauge_8", -1);
+ incLong(st2_1, "long_counter_9", 1002948);
+ incLong(st2_1, "long_counter_10", 29038856);
+ incLong(st2_1, "long_gauge_11", -2947465);
+ incLong(st2_1, "long_gauge_12", 4934745);
+
+ incDouble(st3_1, "double_counter_1", 562.0458);
+ incDouble(st3_1, "double_counter_2", 14.0086);
+ incDouble(st3_1, "double_gauge_3", -2.0);
+ incDouble(st3_1, "double_gauge_4", 1.0);
+ incInt(st3_1, "int_counter_5", 2);
+ incInt(st3_1, "int_counter_6", 1);
+
+ incDouble(st3_2, "double_counter_1", 33.087);
+ incDouble(st3_2, "double_counter_2", 2.02);
+ incDouble(st3_2, "double_gauge_3", 1.06);
+ incDouble(st3_2, "double_gauge_4", 3.021);
+ incInt(st3_2, "int_counter_5", 1);
+ incInt(st3_2, "int_counter_6", 4);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 10) some new values
+
+ incDouble(st1_1, "double_counter_1", 3.014);
+ incDouble(st1_1, "double_gauge_3", 57.003);
+ incInt(st1_1, "int_counter_5", 3);
+ incInt(st1_1, "int_gauge_7", 5);
+ incLong(st1_1, "long_counter_9", 1);
+ incLong(st1_1, "long_gauge_11", 1);
+
+ incDouble(st1_2, "double_counter_2", 20.107);
+ incDouble(st1_2, "double_gauge_4", 1.5078);
+ incInt(st1_2, "int_counter_6", 1);
+ incInt(st1_2, "int_gauge_8", -1);
+ incLong(st1_2, "long_counter_10", 1073741824);
+ incLong(st1_2, "long_gauge_12", 5);
+
+ incInt(st2_1, "int_gauge_7", 2);
+ incLong(st2_1, "long_counter_9", 2);
+ incLong(st2_1, "long_gauge_11", -2);
+
+ incDouble(st3_1, "double_counter_1", 24.80097);
+ incDouble(st3_1, "double_gauge_3", -22.09834);
+ incInt(st3_1, "int_counter_5", 2);
+
+ incDouble(st3_2, "double_counter_2", 21.0483);
+ incDouble(st3_2, "double_gauge_4", 36310.012);
+ incInt(st3_2, "int_counter_6", 4);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 11) remove ST2 and st2_1
+
+ manager.destroyStatistics(st2_1);
+
+ // 12) some new values
+
+ incDouble(st1_1, "double_counter_1", 339.0803);
+ incDouble(st1_1, "double_counter_2", 21.06);
+ incDouble(st1_1, "double_gauge_3", 12.056);
+ incDouble(st1_1, "double_gauge_4", 27.108);
+ incInt(st1_1, "int_counter_5", 2);
+ incInt(st1_1, "int_counter_6", 4);
+
+ incInt(st1_2, "int_gauge_7", 4);
+ incInt(st1_2, "int_gauge_8", 7);
+ incLong(st1_2, "long_counter_9", 8);
+ incLong(st1_2, "long_counter_10", 4);
+ incLong(st1_2, "long_gauge_11", 2);
+ incLong(st1_2, "long_gauge_12", 1);
+
+ incDouble(st3_1, "double_counter_1", 41.103);
+ incDouble(st3_1, "double_counter_2", 2.0333);
+ incDouble(st3_1, "double_gauge_3", -14.0);
+
+ incDouble(st3_2, "double_gauge_4", 26.01);
+ incInt(st3_2, "int_counter_5", 3);
+ incInt(st3_2, "int_counter_6", 1);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 13) no new values
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // 14) remove st1_2
+
+ manager.destroyStatistics(st1_2);
+
+ // 15) all new values
+
+ incDouble(st1_1, "double_counter_1", 62.1350);
+ incDouble(st1_1, "double_counter_2", 33.306);
+ incDouble(st1_1, "double_gauge_3", 41.1340);
+ incDouble(st1_1, "double_gauge_4", -1.04321);
+ incInt(st1_1, "int_counter_5", 2);
+ incInt(st1_1, "int_counter_6", 2);
+ incInt(st1_1, "int_gauge_7", 1);
+ incInt(st1_1, "int_gauge_8", 9);
+ incLong(st1_1, "long_counter_9", 2);
+ incLong(st1_1, "long_counter_10", 5);
+ incLong(st1_1, "long_gauge_11", 3);
+ incLong(st1_1, "long_gauge_12", -2);
+
+ incDouble(st3_1, "double_counter_1", 3461.0153);
+ incDouble(st3_1, "double_counter_2", 5.03167);
+ incDouble(st3_1, "double_gauge_3", -1.31051);
+ incDouble(st3_1, "double_gauge_4", 71.031);
+ incInt(st3_1, "int_counter_5", 4);
+ incInt(st3_1, "int_counter_6", 2);
+
+ incDouble(st3_2, "double_counter_1", 531.5608);
+ incDouble(st3_2, "double_counter_2", 55.0532);
+ incDouble(st3_2, "double_gauge_3", 8.40956);
+ incDouble(st3_2, "double_gauge_4", 23230.0462);
+ incInt(st3_2, "int_counter_5", 9);
+ incInt(st3_2, "int_counter_6", 5);
+
+ sampleCollector.sample(sampleTimeNanos+=(1000*NANOS_PER_MILLI));
+
+ // close the writer
+
+ writer.close();
+
+ // print out all the stat values
+
+ if (false) {
+ StatisticDescriptor[]
+ sds = ST1.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st1_1#" + sds[i].getName() + "=" + st1_1.get(sds[i].getName()));
+ }
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st1_2#" + sds[i].getName() + "=" + st1_2.get(sds[i].getName()));
+ }
+
+ sds = ST2.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st2_1#" + sds[i].getName() + "=" + st2_1.get(sds[i].getName()));
+ }
+
+ sds = ST3.getStatistics();
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st3_1#" + sds[i].getName() + "=" + st3_1.get(sds[i].getName()));
+ }
+ for (int i = 0; i < sds.length; i++) {
+ logger.info("testWriteAfterSamplingBegins#st3_2#" + sds[i].getName() + "=" + st3_2.get(sds[i].getName()));
+ }
+ }
+
+ // validate that stat archive file exists
+
+ final File actual = new File(this.archiveFileName);
+ assertTrue(actual.exists());
+
+ // validate content of stat archive file using StatArchiveReader
+
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{actual}, null, false);
+
+ // compare all resourceInst values against what was printed above
+
+ final List resources = reader.getResourceInstList();
+ for (final Iterator iter = resources.iterator(); iter.hasNext();) {
+ final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
+ final String resourceName = ri.getName();
+ assertNotNull(resourceName);
+
+ final String expectedStatsType = this.statisticTypes.get(resourceName);
+ assertNotNull(expectedStatsType);
+ assertEquals(expectedStatsType, ri.getType().getName());
+
+ final Map<String,Number> expectedStatValues = this.allStatistics.get(resourceName);
+ assertNotNull(expectedStatValues);
+
+ final StatValue[] statValues = ri.getStatValues();
+ for (int i = 0; i < statValues.length; i++) {
+ final String statName = ri.getType().getStats()[i].getName();
+ assertNotNull(statName);
+ assertNotNull(expectedStatValues.get(statName));
+
+ assertEquals(statName, statValues[i].getDescriptor().getName());
+
+ statValues[i].setFilter(StatValue.FILTER_NONE);
+ final double[] rawSnapshots = statValues[i].getRawSnapshots();
+ //for (int j = 0; j < rawSnapshots.length; j++) {
+ // logger.info("DEBUG " + ri.getName() + " " + statName + " rawSnapshots[" + j + "] = " + rawSnapshots[j]);
+ //}
+ assertEquals("Value " + i + " for " + statName + " is wrong: " + expectedStatValues,
+ expectedStatValues.get(statName).doubleValue(),
+ statValues[i].getSnapshotsMostRecent(), 0.01);
+ }
+ }
+
+ // validate byte content of stat archive file against saved expected file
+
+ final File expected = new File(TestUtil.getResourcePath(getClass(), "StatArchiveWriterReaderJUnitTest_" + this.testName.getMethodName() + "_expected.gfs"));
+ assertTrue(expected + " does not exist!", expected.exists());
+ assertEquals(expected.length(), actual.length());
+
+ assertTrue("Actual stat archive file bytes differ from expected stat archive file bytes!",
+ Arrays.equals(readBytes(expected), readBytes(actual)));
+ }
+
+ /**
+ * Validates that IllegalArgumentException is thrown if sample time stamp is
+ * before the previous time stamp. Tests the fix for cause of bug #45268.
+ */
+ @Test
+ public void testNegativeSampleTimeStamp() throws Exception {
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+
+ final long sampleIncNanos = NANOS_PER_MILLI*1000;
+
+ try {
+ writer.sampled(WRITER_PREVIOUS_TIMESTAMP_NANOS - sampleIncNanos, Collections.emptyList());
+ fail("Expected IllegalArgumentException to be thrown from StatArchiveWriter#writeTimeStamp(long)");
+ } catch (IllegalArgumentException expected) {
+ // test passed
+ } finally {
+ writer.close();
+ }
+ }
+
+ /**
+ * Validates that IllegalArgumentException is thrown if sample time stamp is
+ * same as the previous time stamp. Tests the fix for cause of bug #45268.
+ */
+ @Test
+ public void testPreviousSampleTimeStamp() throws Exception {
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+
+ try {
+ writer.sampled(WRITER_PREVIOUS_TIMESTAMP_NANOS, Collections.emptyList());
+ fail("Expected IllegalArgumentException to be thrown from StatArchiveWriter#writeTimeStamp(long)");
+ } catch (IllegalArgumentException expected) {
+ // test passed
+ } finally {
+ writer.close();
+ }
+
+ writer.close();
+ }
+
+ /**
+ * Verifies fix for bug #45377.
+ */
+ @Test
+ public void testDestroyClosedStatistics() throws Exception {
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS - 2000)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+
+ final StatisticsType statsType = createDummyStatisticsType();
+ final ResourceType rt = new ResourceType(0, statsType);
+ final Statistics statistics = mock(Statistics.class);
+ when(statistics.isClosed()).thenReturn(true);
+ final ResourceInstance ri = new ResourceInstance(0, statistics, rt);
+
+ // if bug #45377 still existed, this call would throw IllegalStateException
+ writer.destroyedResourceInstance(ri);
+ }
+
+ /**
+ * Control which helps verify fix for bug #45377.
+ */
+ @Test
+ public void testDestroyUnallocatedStatistics() throws Exception {
+ final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
+ .setArchiveName(this.archiveFileName)
+ .setSystemId(1)
+ .setSystemStartTime(WRITER_INITIAL_DATE_MILLIS - 2000)
+ .setSystemDirectoryPath(this.testName.getMethodName())
+ .setProductDescription(getClass().getSimpleName())
+ .build();
+ final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor);
+
+ final StatisticsType statsType = createDummyStatisticsType();
+ final ResourceType rt = new ResourceType(0, statsType);
+ final Statistics statistics = mock(Statistics.class);
+ final ResourceInstance ri = new ResourceInstance(0, statistics, rt);
+
+ writer.sampled(WRITER_INITIAL_DATE_MILLIS + 1000, Collections.singletonList(ri));
+
+ writer.destroyedResourceInstance(ri);
+ writer.close();
+
+ // Verify StatArchiveReader.update returns cleanly, without throwing an exception
+ final StatArchiveReader reader = new StatArchiveReader(new File[]{new File(this.archiveFileName)}, null, false);
+ reader.update();
+ reader.close();
+ }
+
+ private void incDouble(Statistics statistics, String stat, double value) {
+ assertFalse(statistics.isClosed());
+ Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
+ if (statValues == null) {
+ statValues = new HashMap<String,Number>();
+ this.allStatistics.put(statistics.getTextId(), statValues);
+ }
+ statistics.incDouble(stat, value);
+ statValues.put(stat, statistics.getDouble(stat));
+ if (this.statisticTypes.get(statistics.getTextId()) == null) {
+ this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
+ }
+ }
+
+ private void incInt(Statistics statistics, String stat, int value) {
+ assertFalse(statistics.isClosed());
+ Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
+ if (statValues == null) {
+ statValues = new HashMap<String,Number>();
+ this.allStatistics.put(statistics.getTextId(), statValues);
+ }
+ statistics.incInt(stat, value);
+ statValues.put(stat, statistics.getInt(stat));
+ if (this.statisticTypes.get(statistics.getTextId()) == null) {
+ this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
+ }
+ }
+
+ private void incLong(Statistics statistics, String stat, long value) {
+ assertFalse(statistics.isClosed());
+ Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
+ if (statValues == null) {
+ statValues = new HashMap<String,Number>();
+ this.allStatistics.put(statistics.getTextId(), statValues);
+ }
+ statistics.incLong(stat, value);
+ statValues.put(stat, statistics.getLong(stat));
+ if (this.statisticTypes.get(statistics.getTextId()) == null) {
+ this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
+ }
+ }
+
+ private byte[] readBytes(File file) throws MalformedURLException, IOException {
+ int byteCount = (int)file.length();
+
+ byte[] input = new byte[byteCount];
+
+ URL url = file.toURL();
+ assertNotNull(url);
+
+ InputStream is = url.openStream();
+ assertNotNull(is);
+
+ BufferedInputStream bis = new BufferedInputStream(is);
+ int bytesRead = bis.read(input);
+ bis.close();
+
+ assertEquals(byteCount, bytesRead);
+ return input;
+ }
+
+ private String getUniqueName() {
+ return getClass().getSimpleName() + "_" + this.testName.getMethodName();
+ }
+
+ private static StatisticsType createDummyStatisticsType() {
+ return new StatisticsType() {
+
+ @Override
+ public String getName() {
+ return null;
+ }
+
+ @Override
+ public String getDescription() {
+ return null;
+ }
+
+ @Override
+ public StatisticDescriptor[] getStatistics() {
+ return new StatisticDescriptor[0];
+ }
+
+ @Override
+ public int nameToId(String name) {
+ return 0;
+ }
+
+ @Override
+ public StatisticDescriptor nameToDescriptor(String name) {
+ return null;
+ }
+ };
+ }
+
+ /* [KEEP] alternative method for getting an expected golden file:
+ Class clazz = getClass();
+ assertNotNull(clazz);
+ URL url = clazz.getResource("StatArchiveWriterReaderIntegrationTest.gfs.expected");
+ assertNotNull(url);
+
+ File expected;
+ try {
+ expected = new File(url.toURI());
+ } catch(URISyntaxException e) {
+ expected = new File(url.getPath());
+ }
+ assertTrue(expected.exists());
+ */
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatMonitorHandlerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatMonitorHandlerJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatMonitorHandlerJUnitTest.java
deleted file mode 100755
index bcb7497..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatMonitorHandlerJUnitTest.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal.statistics;
-
-import static org.junit.Assert.*;
-import static org.junit.Assume.*;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.internal.statistics.StatMonitorHandler.StatMonitorNotifier;
-import com.gemstone.gemfire.internal.util.StopWatch;
-import com.gemstone.gemfire.test.junit.categories.UnitTest;
-
-/**
- * Unit tests for the StatMonitorHandler and its inner classes.
- *
- * @since GemFire 7.0
- */
-@Category(UnitTest.class)
-public class StatMonitorHandlerJUnitTest {
-
- @Test
- public void testAddNewMonitor() throws Exception {
- StatMonitorHandler handler = new StatMonitorHandler();
- assertTrue(handler.getMonitorsSnapshot().isEmpty());
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- assertTrue(handler.addMonitor(monitor));
- assertFalse(handler.getMonitorsSnapshot().isEmpty());
- assertTrue(handler.getMonitorsSnapshot().contains(monitor));
- handler.sampled(NanoTimer.getTime(), Collections.<ResourceInstance>emptyList());
- waitForNotificationCount(monitor, 1, 2*1000, 10, false);
- assertEquals(1, monitor.getNotificationCount());
- }
-
- @Test
- public void testAddExistingMonitorReturnsFalse() throws Exception {
- StatMonitorHandler handler = new StatMonitorHandler();
- assertTrue(handler.getMonitorsSnapshot().isEmpty());
- StatisticsMonitor monitor = new TestStatisticsMonitor();
- assertTrue(handler.addMonitor(monitor));
- assertFalse(handler.getMonitorsSnapshot().isEmpty());
- assertTrue(handler.getMonitorsSnapshot().contains(monitor));
- assertFalse(handler.addMonitor(monitor));
- }
-
- @Test
- public void testRemoveExistingMonitor() throws Exception {
- StatMonitorHandler handler = new StatMonitorHandler();
- assertTrue(handler.getMonitorsSnapshot().isEmpty());
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- assertTrue(handler.addMonitor(monitor));
- assertFalse(handler.getMonitorsSnapshot().isEmpty());
- assertTrue(handler.getMonitorsSnapshot().contains(monitor));
- assertTrue(handler.removeMonitor(monitor));
- assertFalse(handler.getMonitorsSnapshot().contains(monitor));
- assertTrue(handler.getMonitorsSnapshot().isEmpty());
- handler.sampled(NanoTimer.getTime(), Collections.<ResourceInstance>emptyList());
- assertEquals(0, monitor.getNotificationCount());
- }
-
- @Test
- public void testRemoveMissingMonitorReturnsFalse() throws Exception {
- StatMonitorHandler handler = new StatMonitorHandler();
- assertTrue(handler.getMonitorsSnapshot().isEmpty());
- StatisticsMonitor monitor = new TestStatisticsMonitor();
- assertFalse(handler.getMonitorsSnapshot().contains(monitor));
- assertFalse(handler.removeMonitor(monitor));
- assertTrue(handler.getMonitorsSnapshot().isEmpty());
- }
-
- @Test
- public void testNotificationSampleFrequencyDefault() throws Exception {
- final int sampleFrequency = 1;
- StatMonitorHandler handler = new StatMonitorHandler();
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- handler.addMonitor(monitor);
- final int sampleCount = 100;
- for (int i = 0; i < sampleCount; i++) {
- handler.sampled(NanoTimer.getTime(), Collections.<ResourceInstance>emptyList());
- waitForNotificationCount(monitor, 1+i, 2*1000, 10, false);
- }
- assertEquals(sampleCount/sampleFrequency, monitor.getNotificationCount());
- }
-
- @Test
- public void testNotificationSampleTimeMillis() throws Exception {
- final long currentTime = System.currentTimeMillis();
- StatMonitorHandler handler = new StatMonitorHandler();
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- handler.addMonitor(monitor);
- long nanoTimeStamp = NanoTimer.getTime();
- handler.sampled(nanoTimeStamp, Collections.<ResourceInstance>emptyList());
- waitForNotificationCount(monitor, 1, 2*1000, 10, false);
- assertTrue(monitor.getTimeStamp() != nanoTimeStamp);
- assertTrue(monitor.getTimeStamp() >= currentTime);
- }
-
- @Test
- public void testNotificationResourceInstances() throws Exception {
- final int resourceInstanceCount = 100;
- final List<ResourceInstance> resourceInstances = new ArrayList<ResourceInstance>();
- for (int i = 0; i < resourceInstanceCount; i++) {
- resourceInstances.add(new ResourceInstance(i, null, null));
- }
-
- StatMonitorHandler handler = new StatMonitorHandler();
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- handler.addMonitor(monitor);
- handler.sampled(NanoTimer.getTime(), Collections.unmodifiableList(resourceInstances));
-
- waitForNotificationCount(monitor, 1, 2*1000, 10, false);
-
- final List<ResourceInstance> notificationResourceInstances = monitor.getResourceInstances();
- assertNotNull(notificationResourceInstances);
- assertEquals(resourceInstances, notificationResourceInstances);
- assertEquals(resourceInstanceCount, notificationResourceInstances.size());
-
- int i = 0;
- for (ResourceInstance resourceInstance : notificationResourceInstances) {
- assertEquals(i, resourceInstance.getId());
- i++;
- }
- }
-
- @Test
- public void testStatMonitorNotifierAliveButWaiting() throws Exception {
- assumeTrue(StatMonitorHandler.enableMonitorThread);
- StatMonitorHandler handler = new StatMonitorHandler();
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- handler.addMonitor(monitor);
-
- final StatMonitorNotifier notifier = handler.getStatMonitorNotifier();
- assertTrue(notifier.isAlive());
-
- waitUntilWaiting(notifier);
-
- for (int i = 0; i < 20; i++) {
- assert(notifier.isWaiting());
- Thread.sleep(10);
- }
- }
-
- @Test
- public void testStatMonitorNotifierWakesUpForWork() throws Exception {
- assumeTrue(StatMonitorHandler.enableMonitorThread);
- StatMonitorHandler handler = new StatMonitorHandler();
- TestStatisticsMonitor monitor = new TestStatisticsMonitor();
- handler.addMonitor(monitor);
-
- final StatMonitorNotifier notifier = handler.getStatMonitorNotifier();
- assertTrue(notifier.isAlive());
-
- waitUntilWaiting(notifier);
-
- // if notification occurs then notifier woke up...
- assertEquals(0, monitor.getNotificationCount());
- handler.sampled(NanoTimer.getTime(), Collections.<ResourceInstance>emptyList());
-
- waitForNotificationCount(monitor, 1, 2*1000, 10, false);
- assertEquals(1, monitor.getNotificationCount());
-
- // and goes back to waiting...
- waitUntilWaiting(notifier);
- }
-
- private static void waitUntilWaiting(StatMonitorNotifier notifier) throws InterruptedException {
- boolean done = false;
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 2000; done = (notifier.isWaiting())) {
- Thread.sleep(10);
- }
- assertTrue("waiting for notifier to be waiting", done);
- }
-
- private static void waitForNotificationCount(final TestStatisticsMonitor monitor, final int expected, long ms, long interval, boolean throwOnTimeout) throws InterruptedException {
- boolean done = false;
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < ms; done = (monitor.getNotificationCount() >= expected)) {
- Thread.sleep(interval);
- }
- if (throwOnTimeout) {
- assertTrue("waiting for notification count to be " + expected, done);
- }
- }
-
- /**
- * @since GemFire 7.0
- */
- private static class TestStatisticsMonitor extends StatisticsMonitor {
- private volatile long timeStamp;
- private volatile List<ResourceInstance> resourceInstances;
- private volatile int notificationCount;
-
- public TestStatisticsMonitor() {
- super();
- }
-
- @Override
- protected void monitor(long timeStamp, List<ResourceInstance> resourceInstances) {
- this.timeStamp = timeStamp;
- this.resourceInstances = resourceInstances;
- this.notificationCount++;
- }
-
- long getTimeStamp() {
- return this.timeStamp;
- }
-
- List<ResourceInstance> getResourceInstances() {
- return this.resourceInstances;
- }
-
- int getNotificationCount() {
- return this.notificationCount;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatMonitorHandlerTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatMonitorHandlerTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatMonitorHandlerTest.java
new file mode 100755
index 0000000..135b3d0
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatMonitorHandlerTest.java
@@ -0,0 +1,235 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.junit.Assert.*;
+import static org.junit.Assume.*;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import com.gemstone.gemfire.internal.NanoTimer;
+import com.gemstone.gemfire.internal.statistics.StatMonitorHandler.StatMonitorNotifier;
+import com.gemstone.gemfire.internal.util.StopWatch;
+import com.gemstone.gemfire.test.junit.categories.UnitTest;
+
+/**
+ * Unit tests for {@link StatMonitorHandler}.
+ *
+ * @since GemFire 7.0
+ */
+@Category(UnitTest.class)
+public class StatMonitorHandlerTest {
+
+ @Test
+ public void testAddNewMonitor() throws Exception {
+ StatMonitorHandler handler = new StatMonitorHandler();
+ assertTrue(handler.getMonitorsSnapshot().isEmpty());
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ assertTrue(handler.addMonitor(monitor));
+ assertFalse(handler.getMonitorsSnapshot().isEmpty());
+ assertTrue(handler.getMonitorsSnapshot().contains(monitor));
+ handler.sampled(NanoTimer.getTime(), Collections.<ResourceInstance>emptyList());
+ waitForNotificationCount(monitor, 1, 2*1000, 10, false);
+ assertEquals(1, monitor.getNotificationCount());
+ }
+
+ @Test
+ public void testAddExistingMonitorReturnsFalse() throws Exception {
+ StatMonitorHandler handler = new StatMonitorHandler();
+ assertTrue(handler.getMonitorsSnapshot().isEmpty());
+ StatisticsMonitor monitor = new TestStatisticsMonitor();
+ assertTrue(handler.addMonitor(monitor));
+ assertFalse(handler.getMonitorsSnapshot().isEmpty());
+ assertTrue(handler.getMonitorsSnapshot().contains(monitor));
+ assertFalse(handler.addMonitor(monitor));
+ }
+
+ @Test
+ public void testRemoveExistingMonitor() throws Exception {
+ StatMonitorHandler handler = new StatMonitorHandler();
+ assertTrue(handler.getMonitorsSnapshot().isEmpty());
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ assertTrue(handler.addMonitor(monitor));
+ assertFalse(handler.getMonitorsSnapshot().isEmpty());
+ assertTrue(handler.getMonitorsSnapshot().contains(monitor));
+ assertTrue(handler.removeMonitor(monitor));
+ assertFalse(handler.getMonitorsSnapshot().contains(monitor));
+ assertTrue(handler.getMonitorsSnapshot().isEmpty());
+ handler.sampled(NanoTimer.getTime(), Collections.<ResourceInstance>emptyList());
+ assertEquals(0, monitor.getNotificationCount());
+ }
+
+ @Test
+ public void testRemoveMissingMonitorReturnsFalse() throws Exception {
+ StatMonitorHandler handler = new StatMonitorHandler();
+ assertTrue(handler.getMonitorsSnapshot().isEmpty());
+ StatisticsMonitor monitor = new TestStatisticsMonitor();
+ assertFalse(handler.getMonitorsSnapshot().contains(monitor));
+ assertFalse(handler.removeMonitor(monitor));
+ assertTrue(handler.getMonitorsSnapshot().isEmpty());
+ }
+
+ @Test
+ public void testNotificationSampleFrequencyDefault() throws Exception {
+ final int sampleFrequency = 1;
+ StatMonitorHandler handler = new StatMonitorHandler();
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ handler.addMonitor(monitor);
+ final int sampleCount = 100;
+ for (int i = 0; i < sampleCount; i++) {
+ handler.sampled(NanoTimer.getTime(), Collections.<ResourceInstance>emptyList());
+ waitForNotificationCount(monitor, 1+i, 2*1000, 10, false);
+ }
+ assertEquals(sampleCount/sampleFrequency, monitor.getNotificationCount());
+ }
+
+ @Test
+ public void testNotificationSampleTimeMillis() throws Exception {
+ final long currentTime = System.currentTimeMillis();
+ StatMonitorHandler handler = new StatMonitorHandler();
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ handler.addMonitor(monitor);
+ long nanoTimeStamp = NanoTimer.getTime();
+ handler.sampled(nanoTimeStamp, Collections.<ResourceInstance>emptyList());
+ waitForNotificationCount(monitor, 1, 2*1000, 10, false);
+ assertTrue(monitor.getTimeStamp() != nanoTimeStamp);
+ assertTrue(monitor.getTimeStamp() >= currentTime);
+ }
+
+ @Test
+ public void testNotificationResourceInstances() throws Exception {
+ final int resourceInstanceCount = 100;
+ final List<ResourceInstance> resourceInstances = new ArrayList<ResourceInstance>();
+ for (int i = 0; i < resourceInstanceCount; i++) {
+ resourceInstances.add(new ResourceInstance(i, null, null));
+ }
+
+ StatMonitorHandler handler = new StatMonitorHandler();
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ handler.addMonitor(monitor);
+ handler.sampled(NanoTimer.getTime(), Collections.unmodifiableList(resourceInstances));
+
+ waitForNotificationCount(monitor, 1, 2*1000, 10, false);
+
+ final List<ResourceInstance> notificationResourceInstances = monitor.getResourceInstances();
+ assertNotNull(notificationResourceInstances);
+ assertEquals(resourceInstances, notificationResourceInstances);
+ assertEquals(resourceInstanceCount, notificationResourceInstances.size());
+
+ int i = 0;
+ for (ResourceInstance resourceInstance : notificationResourceInstances) {
+ assertEquals(i, resourceInstance.getId());
+ i++;
+ }
+ }
+
+ @Test
+ public void testStatMonitorNotifierAliveButWaiting() throws Exception {
+ assumeTrue(StatMonitorHandler.enableMonitorThread);
+ StatMonitorHandler handler = new StatMonitorHandler();
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ handler.addMonitor(monitor);
+
+ final StatMonitorNotifier notifier = handler.getStatMonitorNotifier();
+ assertTrue(notifier.isAlive());
+
+ waitUntilWaiting(notifier);
+
+ for (int i = 0; i < 20; i++) {
+ assert(notifier.isWaiting());
+ Thread.sleep(10);
+ }
+ }
+
+ @Test
+ public void testStatMonitorNotifierWakesUpForWork() throws Exception {
+ assumeTrue(StatMonitorHandler.enableMonitorThread);
+ StatMonitorHandler handler = new StatMonitorHandler();
+ TestStatisticsMonitor monitor = new TestStatisticsMonitor();
+ handler.addMonitor(monitor);
+
+ final StatMonitorNotifier notifier = handler.getStatMonitorNotifier();
+ assertTrue(notifier.isAlive());
+
+ waitUntilWaiting(notifier);
+
+ // if notification occurs then notifier woke up...
+ assertEquals(0, monitor.getNotificationCount());
+ handler.sampled(NanoTimer.getTime(), Collections.<ResourceInstance>emptyList());
+
+ waitForNotificationCount(monitor, 1, 2*1000, 10, false);
+ assertEquals(1, monitor.getNotificationCount());
+
+ // and goes back to waiting...
+ waitUntilWaiting(notifier);
+ }
+
+ private static void waitUntilWaiting(StatMonitorNotifier notifier) throws InterruptedException {
+ boolean done = false;
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 2000; done = (notifier.isWaiting())) {
+ Thread.sleep(10);
+ }
+ assertTrue("waiting for notifier to be waiting", done);
+ }
+
+ private static void waitForNotificationCount(final TestStatisticsMonitor monitor, final int expected, long ms, long interval, boolean throwOnTimeout) throws InterruptedException {
+ boolean done = false;
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < ms; done = (monitor.getNotificationCount() >= expected)) {
+ Thread.sleep(interval);
+ }
+ if (throwOnTimeout) {
+ assertTrue("waiting for notification count to be " + expected, done);
+ }
+ }
+
+ /**
+ * @since GemFire 7.0
+ */
+ private static class TestStatisticsMonitor extends StatisticsMonitor {
+ private volatile long timeStamp;
+ private volatile List<ResourceInstance> resourceInstances;
+ private volatile int notificationCount;
+
+ public TestStatisticsMonitor() {
+ super();
+ }
+
+ @Override
+ protected void monitor(long timeStamp, List<ResourceInstance> resourceInstances) {
+ this.timeStamp = timeStamp;
+ this.resourceInstances = resourceInstances;
+ this.notificationCount++;
+ }
+
+ long getTimeStamp() {
+ return this.timeStamp;
+ }
+
+ List<ResourceInstance> getResourceInstances() {
+ return this.resourceInstances;
+ }
+
+ int getNotificationCount() {
+ return this.notificationCount;
+ }
+ }
+}
[08/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/SimpleStatSamplerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/SimpleStatSamplerJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/SimpleStatSamplerJUnitTest.java
deleted file mode 100755
index 5d7c9f4..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/SimpleStatSamplerJUnitTest.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.lang.reflect.Method;
-import java.util.List;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TestName;
-
-import com.gemstone.gemfire.CancelCriterion;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.stats50.VMStats50;
-import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
-
-/**
- * Integration tests for SimpleStatSampler.
- *
- * @since GemFire 7.0
- */
-@Category(IntegrationTest.class)
-public class SimpleStatSamplerJUnitTest extends StatSamplerTestCase {
-
- @Rule
- public TestName testName = new TestName();
-
- private LocalStatisticsFactory statisticsFactory;
-
- private File testDir = new File(getClass().getSimpleName());
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- final String dirName = SimpleStatSamplerJUnitTest.class.getSimpleName();
- final File dir = new File(dirName);
- if (dir.exists()) {
- FileUtil.delete(dir);
- }
- }
- @Before
- public void setUp() throws Exception {
- if (!this.testDir.exists()) {
- this.testDir.mkdir();
- }
- assertTrue(this.testDir.exists());
- System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY,
- this.testDir.getName() + File.separator + SimpleStatSampler.DEFAULT_ARCHIVE_FILE_NAME);
- }
-
- @After
- public void tearDown() throws Exception {
- System.clearProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY);
- System.clearProperty(SimpleStatSampler.FILE_SIZE_LIMIT_PROPERTY);
- System.clearProperty(SimpleStatSampler.DISK_SPACE_LIMIT_PROPERTY);
- System.clearProperty(SimpleStatSampler.SAMPLE_RATE_PROPERTY);
- closeStatisticsFactory();
- }
-
- /**
- * Tests the majority of getters and the basic functionality of the sampler.
- */
- @Test
- public void testBasics() throws Exception {
- initStatisticsFactory();
-
- SimpleStatSampler statSampler = getSimpleStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- assertEquals(new File(System.getProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY)),
- statSampler.getArchiveFileName());
- assertEquals(0, statSampler.getArchiveFileSizeLimit());
- assertEquals(0, statSampler.getArchiveDiskSpaceLimit());
- assertEquals(SimpleStatSampler.DEFAULT_SAMPLE_RATE, statSampler.getSampleRate());
- assertEquals(true, statSampler.isSamplingEnabled());
-
- int statsCount = statSampler.getStatisticsManager().getStatisticsCount();
-
- assertEquals(statsCount, statSampler.getStatisticsModCount());
- assertEquals(statsCount, statSampler.getStatisticsManager().getStatisticsCount());
- assertEquals(statsCount, statSampler.getStatistics().length);
-
- assertTrue(statsCount > 0);
-
- assertEquals(getStatisticsManager().getId(), statSampler.getSystemId());
- assertTrue(statSampler.getSystemStartTime() <= System.currentTimeMillis());
- assertEquals(SocketCreator.getHostName(SocketCreator.getLocalHost()),
- statSampler.getSystemDirectoryPath());
-
- VMStatsContract vmStats = statSampler.getVMStats();
- assertNotNull(vmStats);
- assertTrue(vmStats instanceof VMStats50);
- /* NOTE: VMStats50 is not an instance of Statistics but instead its
- * instance contains 3 instances of Statistics:
- * 1) vmStats
- * 2) heapMemStats
- * 3) nonHeapMemStats
- */
-
- Method getProcessStats = null;
- try {
- getProcessStats = SimpleStatSampler.class.getMethod("getProcessStats");
- fail("SimpleStatSampler should not have the method getProcessStats()");
- } catch (NoSuchMethodException exected) {
- // passed
- }
- assertNull(getProcessStats);
-
- assertEquals("Unknown product", statSampler.getProductDescription());
- }
-
- /**
- * Tests that the configured archive file is created and exists.
- */
- @Test
- public void testArchiveFileExists() throws Exception {
- final String dir = this.testDir.getName();
- final String archiveFileName = dir + File.separator + this.testName + ".gfs";
- final File archiveFile1 = new File(dir + File.separator + this.testName + ".gfs");
- System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY, archiveFileName);
- initStatisticsFactory();
-
- SimpleStatSampler statSampler = getSimpleStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- final File archiveFile = statSampler.getArchiveFileName();
- assertNotNull(archiveFile);
- assertEquals(archiveFile1, archiveFile);
-
- waitForFileToExist(archiveFile, 5000, 10);
-
- assertTrue("File name incorrect: archiveFile.getName()=" + archiveFile.getName() +
- " archiveFile.getAbsolutePath()=" + archiveFile.getAbsolutePath() +
- " getCanonicalPath()" + archiveFile.getCanonicalPath(),
- archiveFileName.contains(archiveFile.getName()));
- }
-
- /**
- * Tests the statistics sample rate within an acceptable margin of error.
- */
- @Test
- public void testSampleRate() throws Exception {
- initStatisticsFactory();
-
- SimpleStatSampler statSampler = getSimpleStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- assertEquals(SimpleStatSampler.DEFAULT_SAMPLE_RATE, statSampler.getSampleRate());
-
- assertTrue(getStatisticsManager().getStatListModCount() > 0);
-
- List<Statistics> statistics = getStatisticsManager().getStatsList();
- assertNotNull(statistics);
- assertTrue(statistics.size() > 0);
-
- StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
- Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
- assertEquals(1, statsArray.length);
-
- final Statistics statSamplerStats = statsArray[0];
- final int initialSampleCount = statSamplerStats.getInt("sampleCount");
- final int expectedSampleCount = initialSampleCount + 2;
-
- waitForStatSample(statSamplerStats, expectedSampleCount, 20000, 10);
- }
-
- /**
- * Tests lack of methods for supporting LocalStatListener.
- */
- @Test
- public void testLocalStatListener() throws Exception {
- initStatisticsFactory();
-
- SimpleStatSampler statSampler = getSimpleStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- Method getLocalListeners = null;
- try {
- getLocalListeners = getSimpleStatSampler().getClass().getMethod("getLocalListeners");
- fail("SimpleStatSampler should not have the method getLocalListeners()");
- } catch (NoSuchMethodException exected) {
- // passed
- }
- assertNull(getLocalListeners);
-
- Method addLocalStatListener = null;
- try {
- addLocalStatListener = getSimpleStatSampler().getClass().getMethod("addLocalStatListener", LocalStatListener.class, Statistics.class, String.class);
- fail("SimpleStatSampler should not have the method addLocalStatListener()");
- } catch (NoSuchMethodException exected) {
- // passed
- }
- assertNull(addLocalStatListener);
-
- Method removeLocalStatListener = null;
- try {
- removeLocalStatListener = getSimpleStatSampler().getClass().getMethod("removeLocalStatListener", LocalStatListener.class);
- fail("SimpleStatSampler should not have the method addLocalStatListener()");
- } catch (NoSuchMethodException exected) {
- // passed
- }
- assertNull(removeLocalStatListener);
- }
-
- /**
- * Invokes stop() and then validates that the sampler did in fact stop.
- */
- @Test
- public void testStop() throws Exception {
- initStatisticsFactory();
-
- SimpleStatSampler statSampler = getSimpleStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- // validate the stat sampler is running
- StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
- Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
- assertEquals(1, statsArray.length);
-
- final Statistics statSamplerStats = statsArray[0];
- final int initialSampleCount = statSamplerStats.getInt("sampleCount");
- final int expectedSampleCount = initialSampleCount + 2;
-
- waitForStatSample(statSamplerStats, expectedSampleCount, 20000, 10);
-
- // stop the stat sampler
- statSampler.stop();
-
- // validate the stat sampler has stopped
- final int stoppedSampleCount = statSamplerStats.getInt("sampleCount");
-
- // the following should timeout without completing
- assertStatValueDoesNotChange(statSamplerStats, "sampleCount", stoppedSampleCount, 5000, 10);
-
- assertEquals(stoppedSampleCount, statSamplerStats.getInt("sampleCount"));
- }
-
- /**
- * Verifies that archive rolling works correctly when archive-file-size-limit
- * is specified. This feature is broken in SimpleStatSampler.
- */
- @Test
- public void testArchiveRolling() throws Exception {
- // set the system property to use KB instead of MB for file size
- System.setProperty(HostStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY, "true");
-
- final String dir = this.testDir.getName() + File.separator + this.testName;
- new File(dir).mkdir();
-
- final String archiveFileName = dir + File.separator + this.testName + ".gfs";
- System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY, archiveFileName);
- System.setProperty(SimpleStatSampler.FILE_SIZE_LIMIT_PROPERTY, "1");
- System.setProperty(SimpleStatSampler.DISK_SPACE_LIMIT_PROPERTY, "0");
- System.setProperty(SimpleStatSampler.SAMPLE_RATE_PROPERTY, "1000");
- initStatisticsFactory();
-
- final File archiveFile1 = new File(dir + File.separator + this.testName + "-01-01.gfs");
- final File archiveFile2 = new File(dir + File.separator + this.testName + "-01-02.gfs");
- final File archiveFile3 = new File(dir + File.separator + this.testName + "-01-03.gfs");
- final File archiveFile4 = new File(dir + File.separator + this.testName + "-01-04.gfs");
-
- assertTrue(getSimpleStatSampler().waitForInitialization(5000));
-
- assertTrue(getSimpleStatSampler().fileSizeLimitInKB());
- assertEquals(1024, getSimpleStatSampler().getArchiveFileSizeLimit());
-
- waitForFileToExist(archiveFile1, 4000, 10);
- waitForFileToExist(archiveFile2, 4000, 10);
- waitForFileToExist(archiveFile3, 4000, 10);
- waitForFileToExist(archiveFile4, 4000, 10);
- }
-
- /**
- * Verifies that archive removal works correctly when archive-disk-space-limit
- * is specified. This feature is broken in SimpleStatSampler.
- */
- @Test
- public void testArchiveRemoval() throws Exception {
- // set the system property to use KB instead of MB for file size
- System.setProperty(HostStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY, "true");
-
- final String dir = this.testDir.getName() + File.separator + this.testName;
- new File(dir).mkdir();
-
- final String archiveFileName = dir + File.separator + this.testName + ".gfs";
- final int sampleRate = 1000;
- System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY, archiveFileName);
- System.setProperty(SimpleStatSampler.FILE_SIZE_LIMIT_PROPERTY, "1");
- System.setProperty(SimpleStatSampler.DISK_SPACE_LIMIT_PROPERTY, "12");
- System.setProperty(SimpleStatSampler.SAMPLE_RATE_PROPERTY, String.valueOf(sampleRate));
- initStatisticsFactory();
-
- final File archiveFile1 = new File(dir + File.separator + this.testName + "-01-01.gfs");
- final File archiveFile2 = new File(dir + File.separator + this.testName + "-01-02.gfs");
- final File archiveFile3 = new File(dir + File.separator + this.testName + "-01-03.gfs");
- final File archiveFile4 = new File(dir + File.separator + this.testName + "-01-04.gfs");
- final File archiveFile5 = new File(dir + File.separator + this.testName + "-01-05.gfs");
-
- assertTrue(getSimpleStatSampler().waitForInitialization(5000));
-
- waitForFileToExist(archiveFile1, 4*sampleRate, 10);
- waitForFileToExist(archiveFile2, 4*sampleRate, 10);
- waitForFileToExist(archiveFile3, 4*sampleRate, 10);
- waitForFileToExist(archiveFile4, 4*sampleRate, 10);
- waitForFileToExist(archiveFile5, 4*sampleRate, 10);
- waitForFileToDelete(archiveFile1, 10*sampleRate, 10);
- }
-
- @Override
- protected StatisticsManager getStatisticsManager() {
- return this.statisticsFactory;
- }
-
- private SimpleStatSampler getSimpleStatSampler() {
- return this.statisticsFactory.getStatSampler();
- }
-
- private void initStatisticsFactory() {
- CancelCriterion stopper = new CancelCriterion() {
- public String cancelInProgress() {
- return null;
- }
- public RuntimeException generateCancelledException(Throwable e) {
- return null;
- }
- };
- this.statisticsFactory = new LocalStatisticsFactory(stopper);
- }
-
- private void closeStatisticsFactory() {
- if (this.statisticsFactory != null) {
- this.statisticsFactory.close();
- this.statisticsFactory = null;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest.java
deleted file mode 100755
index ea9ff4b..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest.java
+++ /dev/null
@@ -1,1728 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.*;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import com.gemstone.gemfire.StatisticDescriptor;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.i18n.LogWriterI18n;
-import com.gemstone.gemfire.internal.StatArchiveReader.StatValue;
-import com.gemstone.gemfire.internal.logging.InternalLogWriter;
-import com.gemstone.gemfire.internal.logging.PureLogWriter;
-import com.gemstone.gemfire.internal.statistics.ResourceInstance;
-import com.gemstone.gemfire.internal.statistics.ResourceType;
-import com.gemstone.gemfire.internal.statistics.SampleCollector;
-import com.gemstone.gemfire.internal.statistics.StatArchiveDescriptor;
-import com.gemstone.gemfire.internal.statistics.TestStatArchiveWriter;
-import com.gemstone.gemfire.internal.statistics.TestStatisticsManager;
-import com.gemstone.gemfire.internal.statistics.TestStatisticsSampler;
-import com.gemstone.gemfire.util.test.TestUtil;
-import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
-
-/**
- * Integration tests for StatArchiveWriter and StatArchiveReader. The tests
- * are very redundant and desperately need refactoring.
- *
- * @since GemFire 7.0
- */
-@Category(IntegrationTest.class)
-public class StatArchiveWriterReaderJUnitTest {
-
- private static final String dir = "StatArchiveWriterReaderJUnitTest";
-
- private Map<String,String> statisticTypes;
-
- private Map<String,Map<String,Number>> allStatistics;
-
- @Before
- public void setUp() throws Exception {
- this.statisticTypes = new HashMap<String,String>();
- this.allStatistics = new HashMap<String,Map<String,Number>>();
- new File(dir).mkdir();
- }
-
- @After
- public void tearDown() throws Exception {
- this.statisticTypes = null;
- this.allStatistics = null;
- StatisticsTypeFactoryImpl.clear();
- }
-
- private static void deleteTestOutputDir() {
- try {
- for (File file : new File(dir).listFiles()) {
- file.delete();
- }
- new File(dir).delete();
- } catch (NullPointerException e) {
- // dir probably doesn't exist
- }
- }
-
- @Test
- public void testDoubleCounterOneSample() throws Exception {
- final String testName = "testDoubleCounterOneSample";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final InternalLogWriter log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "StatArchiveWriterReaderJUnitTest_" + testName,
- TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS);
-
- final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
- final SampleCollector sampleCollector = new SampleCollector(sampler);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
- sampleCollector.addSampleHandler(writer);
-
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createDoubleCounter("long_double_1", "d1", "u1")
- };
-
- final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
- final double value = 32317.716467;
- incDouble(st1_1, "long_double_1", value);
-
- final long sampleIncNanos = StatArchiveFormat.NANOS_PER_MILLI*1000;
- final long sampleTimeNanos = TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
- sampleCollector.sample(sampleTimeNanos);
-
- writer.close();
-
- final StatisticDescriptor[] sds = ST1.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- assertEquals(value, st1_1.get(sds[i].getName()));
- }
-
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{new File(archiveFileName)}, null, false);
-
- // compare all resourceInst values against what was printed above
-
- @SuppressWarnings("rawtypes")
- final List resources = reader.getResourceInstList();
- assertNotNull(resources);
- assertEquals(1, resources.size());
-
- final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
- assertNotNull(ri);
- final String statsName = ri.getName();
- assertNotNull(statsName);
- assertEquals("st1_1", statsName);
- assertEquals("ST1", ri.getType().getName());
-
- final StatValue[] statValues = ri.getStatValues();
- assertNotNull(statValues);
- assertEquals(1, statValues.length);
-
- final String statName = ri.getType().getStats()[0].getName();
- assertNotNull(statName);
- assertEquals("long_double_1", statName);
- assertEquals(statName, statValues[0].getDescriptor().getName());
- assertEquals(1, statValues[0].getSnapshotsSize());
- assertEquals(value, statValues[0].getSnapshotsMostRecent(), 0.01);
-
- final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
- assertNotNull(timeStampsMillis);
- assertEquals(1, timeStampsMillis.length);
-
- final long initPreviousTimeStampMillis = NanoTimer.nanosToMillis(TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS);
- final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
- final long deltaMillis = timeStampMillis - initPreviousTimeStampMillis;
- assertEquals(NanoTimer.nanosToMillis(sampleIncNanos), deltaMillis);
-
- final long expectedTimeStampMillis = deltaMillis + TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS;
- assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
-
- final double[] snapshots = statValues[0].getRawSnapshots();
- assertNotNull(snapshots);
- assertEquals(1, snapshots.length);
- assertEquals(value, snapshots[0], 0.01);
- }
-
- @Test
- public void testIntCounterOneSample() throws Exception {
- final String testName = "testIntCounterOneSample";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final InternalLogWriter log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "StatArchiveWriterReaderJUnitTest_" + testName,
- TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS);
-
- final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
- final SampleCollector sampleCollector = new SampleCollector(sampler);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
- sampleCollector.addSampleHandler(writer);
-
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createIntCounter("int_counter_1", "d1", "u1")
- };
-
- final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
- final int value = 5;
- incInt(st1_1, "int_counter_1", value);
-
- final long sampleIncNanos = StatArchiveFormat.NANOS_PER_MILLI*1000;
- final long sampleTimeNanos = TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
- sampleCollector.sample(sampleTimeNanos);
-
- writer.close();
-
- final StatisticDescriptor[] sds = ST1.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- assertEquals(value, st1_1.get(sds[i].getName()));
- }
-
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{new File(archiveFileName)}, null, false);
-
- // compare all resourceInst values against what was printed above
-
- @SuppressWarnings("rawtypes")
- final List resources = reader.getResourceInstList();
- assertNotNull(resources);
- assertEquals(1, resources.size());
-
- final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
- assertNotNull(ri);
- final String statsName = ri.getName();
- assertNotNull(statsName);
- assertEquals("st1_1", statsName);
- assertEquals("ST1", ri.getType().getName());
-
- final StatValue[] statValues = ri.getStatValues();
- assertNotNull(statValues);
- assertEquals(1, statValues.length);
-
- final String statName = ri.getType().getStats()[0].getName();
- assertNotNull(statName);
- assertEquals("int_counter_1", statName);
- assertEquals(statName, statValues[0].getDescriptor().getName());
- assertEquals(1, statValues[0].getSnapshotsSize());
- assertEquals((double)value, statValues[0].getSnapshotsMostRecent(), 0.01);
-
- final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
- assertNotNull(timeStampsMillis);
- assertEquals(1, timeStampsMillis.length);
-
- final long initPreviousTimeStampMillis = NanoTimer.nanosToMillis(TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS);
- final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
- final long deltaMillis = timeStampMillis - initPreviousTimeStampMillis;
- assertEquals(NanoTimer.nanosToMillis(sampleIncNanos), deltaMillis);
-
- final long expectedTimeStampMillis = deltaMillis + TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS;
- assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
-
- final double[] snapshots = statValues[0].getRawSnapshots();
- assertNotNull(snapshots);
- assertEquals(1, snapshots.length);
- assertEquals((double)value, snapshots[0], 0.01);
- }
-
- @Test
- public void testIntGaugeOneSample() throws Exception {
- final String testName = "testIntGaugeOneSample";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final InternalLogWriter log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "StatArchiveWriterReaderJUnitTest_" + testName,
- TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS);
-
- final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
- final SampleCollector sampleCollector = new SampleCollector(sampler);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
- sampleCollector.addSampleHandler(writer);
-
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createIntGauge("int_gauge_1", "d1", "u1")
- };
-
- final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
- final int value = 5;
- incInt(st1_1, "int_gauge_1", value);
-
- final long sampleIncNanos = StatArchiveFormat.NANOS_PER_MILLI*1000;
- final long sampleTimeNanos = TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
- sampleCollector.sample(sampleTimeNanos);
-
- writer.close();
-
- final StatisticDescriptor[] sds = ST1.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- assertEquals(value, st1_1.get(sds[i].getName()));
- }
-
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{new File(archiveFileName)}, null, false);
-
- // compare all resourceInst values against what was printed above
-
- @SuppressWarnings("rawtypes")
- final List resources = reader.getResourceInstList();
- assertNotNull(resources);
- assertEquals(1, resources.size());
-
- final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
- assertNotNull(ri);
- final String statsName = ri.getName();
- assertNotNull(statsName);
- assertEquals("st1_1", statsName);
- assertEquals("ST1", ri.getType().getName());
-
- final StatValue[] statValues = ri.getStatValues();
- assertNotNull(statValues);
- assertEquals(1, statValues.length);
-
- final String statName = ri.getType().getStats()[0].getName();
- assertNotNull(statName);
- assertEquals("int_gauge_1", statName);
- assertEquals(statName, statValues[0].getDescriptor().getName());
- assertEquals(1, statValues[0].getSnapshotsSize());
- assertEquals((double)value, statValues[0].getSnapshotsMostRecent(), 0.01);
-
- final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
- assertNotNull(timeStampsMillis);
- assertEquals(1, timeStampsMillis.length);
-
- final long initialPreviousTimeStampMillis = NanoTimer.nanosToMillis(TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS);
- final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
- final long deltaMillis = timeStampMillis - initialPreviousTimeStampMillis;
- assertEquals(NanoTimer.nanosToMillis(sampleIncNanos), deltaMillis);
-
- final long expectedTimeStampMillis = deltaMillis + TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS;
- assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
-
- final double[] snapshots = statValues[0].getRawSnapshots();
- assertNotNull(snapshots);
- assertEquals(1, snapshots.length);
- assertEquals((double)value, snapshots[0], 0.01);
- }
-
- @Test
- public void testLongCounterOneSample() throws Exception {
- final String testName = "testLongCounterOneSample";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final InternalLogWriter log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "StatArchiveWriterReaderJUnitTest_" + testName,
- TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS);
-
- final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
- final SampleCollector sampleCollector = new SampleCollector(sampler);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
- sampleCollector.addSampleHandler(writer);
-
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createLongCounter("long_counter_1", "d1", "u1")
- };
-
- final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
- final long value = 5;
- incLong(st1_1, "long_counter_1", value);
-
- final long sampleIncNanos = StatArchiveFormat.NANOS_PER_MILLI*1000;
- final long sampleTimeNanos = TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
- sampleCollector.sample(sampleTimeNanos);
-
- writer.close();
-
- final StatisticDescriptor[] sds = ST1.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- assertEquals(value, st1_1.get(sds[i].getName()));
- }
-
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{new File(archiveFileName)}, null, false);
-
- // compare all resourceInst values against what was printed above
-
- @SuppressWarnings("rawtypes")
- final List resources = reader.getResourceInstList();
- assertNotNull(resources);
- assertEquals(1, resources.size());
-
- final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
- assertNotNull(ri);
- final String statsName = ri.getName();
- assertNotNull(statsName);
- assertEquals("st1_1", statsName);
- assertEquals("ST1", ri.getType().getName());
-
- final StatValue[] statValues = ri.getStatValues();
- assertNotNull(statValues);
- assertEquals(1, statValues.length);
-
- final String statName = ri.getType().getStats()[0].getName();
- assertNotNull(statName);
- assertEquals("long_counter_1", statName);
- assertEquals(statName, statValues[0].getDescriptor().getName());
- assertEquals(1, statValues[0].getSnapshotsSize());
- assertEquals((double)value, statValues[0].getSnapshotsMostRecent(), 0.01);
-
- final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
- assertNotNull(timeStampsMillis);
- assertEquals(1, timeStampsMillis.length);
-
- final long initialPreviousTimeStampMillis = NanoTimer.nanosToMillis(TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS);
- final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
- final long deltaMillis = timeStampMillis - initialPreviousTimeStampMillis;
- assertEquals(NanoTimer.nanosToMillis(sampleIncNanos), deltaMillis);
-
- final long expectedTimeStampMillis = deltaMillis + TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS;
- assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
-
- final double[] snapshots = statValues[0].getRawSnapshots();
- assertNotNull(snapshots);
- assertEquals(1, snapshots.length);
- assertEquals((double)value, snapshots[0], 0.01);
- }
-
- @Test
- public void testLongGaugeOneSample() throws Exception {
- final String testName = "testLongGaugeOneSample";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final InternalLogWriter log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "StatArchiveWriterReaderJUnitTest_" + testName,
- TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS);
-
- final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
- final SampleCollector sampleCollector = new SampleCollector(sampler);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
- sampleCollector.addSampleHandler(writer);
-
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createLongGauge("long_gauge_1", "d1", "u1")
- };
-
- final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
- incLong(st1_1, "long_gauge_1", 5);
-
- final long sampleTimeNanos = TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS + StatArchiveFormat.NANOS_PER_MILLI*2;
- sampleCollector.sample(sampleTimeNanos);
-
- writer.close();
-
- final StatisticDescriptor[] sds = ST1.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- assertEquals(5L, st1_1.get(sds[i].getName()));
- }
-
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{new File(archiveFileName)}, null, false);
-
- // compare all resourceInst values against what was printed above
-
- @SuppressWarnings("rawtypes")
- final List resources = reader.getResourceInstList();
- assertNotNull(resources);
- assertEquals(1, resources.size());
-
- final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
- assertNotNull(ri);
- final String statsName = ri.getName();
- assertNotNull(statsName);
- assertEquals("st1_1", statsName);
- assertEquals("ST1", ri.getType().getName());
-
- final StatValue[] statValues = ri.getStatValues();
- assertNotNull(statValues);
- assertEquals(1, statValues.length);
-
- final String statName = ri.getType().getStats()[0].getName();
- assertNotNull(statName);
- assertEquals("long_gauge_1", statName);
- assertEquals(statName, statValues[0].getDescriptor().getName());
- assertEquals(1, statValues[0].getSnapshotsSize());
- assertEquals(5.0, statValues[0].getSnapshotsMostRecent(), 0.01);
-
- final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
- assertNotNull(timeStampsMillis);
- assertEquals(1, timeStampsMillis.length);
-
- final long initialPreviousTimeStampMillis = NanoTimer.nanosToMillis(TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS);
- final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
- final long deltaMillis = timeStampMillis - initialPreviousTimeStampMillis;
- assertEquals(2, deltaMillis);
-
- final long expectedTimeStampMillis = deltaMillis + TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS;
- assertEquals(expectedTimeStampMillis, timeStampsMillis[0]);
-
- final double[] snapshots = statValues[0].getRawSnapshots();
- assertNotNull(snapshots);
- assertEquals(1, snapshots.length);
- assertEquals(5.0, snapshots[0], 0.01);
- }
-
- @Test
- public void testLongCounterTwoSamples() throws Exception {
- final String testName = "testLongCounterTwoSamples";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final InternalLogWriter log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "StatArchiveWriterReaderJUnitTest_" + testName,
- TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS);
-
- final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
- final SampleCollector sampleCollector = new SampleCollector(sampler);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
- sampleCollector.addSampleHandler(writer);
-
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createLongCounter("long_counter_1", "d1", "u1")
- };
-
- final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
- final long value1 = 5;
- incLong(st1_1, "long_counter_1", value1);
-
- final long sampleIncNanos = StatArchiveFormat.NANOS_PER_MILLI*1000;
- long sampleTimeNanos = TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS + sampleIncNanos;
- sampleCollector.sample(sampleTimeNanos);
-
- final long value2 = 15;
- incLong(st1_1, "long_counter_1", value2);
- sampleTimeNanos += sampleIncNanos;
- sampleCollector.sample(sampleTimeNanos);
-
- writer.close();
-
- final StatisticDescriptor[] sds = ST1.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- assertEquals(value1 + value2, st1_1.get(sds[i].getName()));
- }
-
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{new File(archiveFileName)}, null, false);
-
- // compare all resourceInst values against what was printed above
-
- @SuppressWarnings("rawtypes")
- final List resources = reader.getResourceInstList();
- assertNotNull(resources);
- assertEquals(1, resources.size());
-
- final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) resources.get(0);
- assertNotNull(ri);
- final String statsName = ri.getName();
- assertNotNull(statsName);
- assertEquals("st1_1", statsName);
- assertEquals("ST1", ri.getType().getName());
-
- final StatValue[] statValues = ri.getStatValues();
- assertNotNull(statValues);
- assertEquals(1, statValues.length);
-
- statValues[0].setFilter(StatValue.FILTER_NONE);
-
- final String statName = ri.getType().getStats()[0].getName();
- assertNotNull(statName);
- assertEquals("long_counter_1", statName);
- assertEquals(statName, statValues[0].getDescriptor().getName());
- assertEquals(2, statValues[0].getSnapshotsSize());
- assertEquals((double)(value1+value2), statValues[0].getSnapshotsMostRecent(), 0.01);
-
- final long[] timeStampsMillis = statValues[0].getRawAbsoluteTimeStamps();
- assertNotNull(timeStampsMillis);
- assertEquals(2, timeStampsMillis.length);
-
- final long initialPreviousTimeStampMillis = NanoTimer.nanosToMillis(TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS);
- final long timeStampMillis = NanoTimer.nanosToMillis(sampleTimeNanos);
- final long deltaMillis = timeStampMillis - initialPreviousTimeStampMillis;
- assertEquals(NanoTimer.nanosToMillis(sampleIncNanos*2), deltaMillis);
-
- long expectedTimeStampMillis = TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS;
- for (int i = 0; i < timeStampsMillis.length; i++) {
- expectedTimeStampMillis += 1000;
- assertEquals("expectedTimeStampMillis for " + i + " is wrong",
- expectedTimeStampMillis, timeStampsMillis[i]);
- }
-
- final double[] snapshots = statValues[0].getRawSnapshots();
- assertNotNull(snapshots);
- assertEquals(2, snapshots.length);
- assertEquals((double)value1, snapshots[0], 0.01);
- assertEquals((double)(value1+value2), snapshots[1], 0.01);
- }
-
- /**
- * Tests the stat archive file written by StatArchiveWriter.
- */
- @SuppressWarnings("unused")
- @Test
- public void testWriteAfterSamplingBegins() throws Exception {
- final String testName = "testWriteAfterSamplingBegins";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final InternalLogWriter log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "StatArchiveWriterReaderJUnitTest_" + testName,
- TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS);
-
- final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
- final SampleCollector sampleCollector = new SampleCollector(sampler);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS - 2000)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
- sampleCollector.addSampleHandler(writer);
-
- long sampleTimeNanos = TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS + StatArchiveFormat.NANOS_PER_MILLI*1000;
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 1) create ST1 and st1_1
-
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createDoubleCounter("double_counter_1", "d1", "u1"),
- manager.createDoubleCounter("double_counter_2", "d2", "u2", true),
- manager.createDoubleGauge( "double_gauge_3", "d3", "u3"),
- manager.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
- manager.createIntCounter( "int_counter_5", "d5", "u5"),
- manager.createIntCounter( "int_counter_6", "d6", "u6", true),
- manager.createIntGauge( "int_gauge_7", "d7", "u7"),
- manager.createIntGauge( "int_gauge_8", "d8", "u8", false),
- manager.createLongCounter( "long_counter_9", "d9", "u9"),
- manager.createLongCounter( "long_counter_10", "d10", "u10", true),
- manager.createLongGauge( "long_gauge_11", "d11", "u11"),
- manager.createLongGauge( "long_gauge_12", "d12", "u12", false)
- };
- final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
-
- // 2) create st1_2
-
- final Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2", 2);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 3) some new values
-
- incDouble(st1_1, "double_counter_1", 18347.94880);
- incDouble(st1_1, "double_gauge_4", 24885.02346);
- incInt(st1_1, "int_counter_5", 3);
- incInt(st1_1, "int_gauge_8", 4);
- incLong(st1_1, "long_counter_9", 1073741824);
- incLong(st1_1, "long_gauge_12", 154367897);
-
- incDouble(st1_2, "double_counter_2", 346.95);
- incDouble(st1_2, "double_gauge_3", 9865.23008);
- incInt(st1_2, "int_counter_6", 4);
- incInt(st1_2, "int_gauge_7", 3);
- incLong(st1_2, "long_counter_10", 3497536);
- incLong(st1_2, "long_gauge_11", 103909646);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 4) all new values
-
- incDouble(st1_1, "double_counter_1", 1.098367);
- incDouble(st1_1, "double_counter_2", 50247.0983254);
- incDouble(st1_1, "double_gauge_3", 987654.2344);
- incDouble(st1_1, "double_gauge_4", 23.097);
- incInt(st1_1, "int_counter_5", 3);
- incInt(st1_1, "int_counter_6", 4);
- incInt(st1_1, "int_gauge_7", 3);
- incInt(st1_1, "int_gauge_8", 4);
- incLong(st1_1, "long_counter_9", 5);
- incLong(st1_1, "long_counter_10", 465793);
- incLong(st1_1, "long_gauge_11", -203050);
- incLong(st1_1, "long_gauge_12", 6);
-
- incDouble(st1_2, "double_counter_1", 0.000846643);
- incDouble(st1_2, "double_counter_2", 4.0);
- incDouble(st1_2, "double_gauge_3", -4.0);
- incDouble(st1_2, "double_gauge_4", 19276.0346624);
- incInt(st1_2, "int_counter_5", 1);
- incInt(st1_2, "int_counter_6", 2);
- incInt(st1_2, "int_gauge_7", -1);
- incInt(st1_2, "int_gauge_8", -2);
- incLong(st1_2, "long_counter_9", 309876);
- incLong(st1_2, "long_counter_10", 4);
- incLong(st1_2, "long_gauge_11", -4);
- incLong(st1_2, "long_gauge_12", 1098764);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 5) no new values
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 6) some new values
-
- incDouble(st1_1, "double_counter_2", 10.255);
- incDouble(st1_1, "double_gauge_3", -4123.05);
- incInt(st1_1, "int_counter_6", 2);
- incInt(st1_1, "int_gauge_7", 3);
- incLong(st1_1, "long_counter_10", 4);
- incLong(st1_1, "long_gauge_11", -2);
-
- incDouble(st1_2, "double_counter_1", 5.00007634);
- incDouble(st1_2, "double_gauge_4", 16904.06524);
- incInt(st1_2, "int_counter_5", 4);
- incInt(st1_2, "int_gauge_8", 1);
- incLong(st1_2, "long_counter_9", 8);
- incLong(st1_2, "long_gauge_12", 10);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 7) all new values
-
- incDouble(st1_1, "double_counter_1", 4065.340);
- incDouble(st1_1, "double_counter_2", 2.01342568);
- incDouble(st1_1, "double_gauge_3", 1.367890);
- incDouble(st1_1, "double_gauge_4", 8.0549003);
- incInt(st1_1, "int_counter_5", 2);
- incInt(st1_1, "int_counter_6", 9);
- incInt(st1_1, "int_gauge_7", 1);
- incInt(st1_1, "int_gauge_8", 2);
- incLong(st1_1, "long_counter_9", 6);
- incLong(st1_1, "long_counter_10", 2);
- incLong(st1_1, "long_gauge_11", -10);
- incLong(st1_1, "long_gauge_12", 8);
-
- incDouble(st1_2, "double_counter_1", 128.2450);
- incDouble(st1_2, "double_counter_2", 113.550);
- incDouble(st1_2, "double_gauge_3", 21.0676);
- incDouble(st1_2, "double_gauge_4", 2.01346);
- incInt(st1_2, "int_counter_5", 3);
- incInt(st1_2, "int_counter_6", 4);
- incInt(st1_2, "int_gauge_7", 4);
- incInt(st1_2, "int_gauge_8", 2);
- incLong(st1_2, "long_counter_9", 1);
- incLong(st1_2, "long_counter_10", 2);
- incLong(st1_2, "long_gauge_11", 3);
- incLong(st1_2, "long_gauge_12", -2);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 8) create ST2 and ST3 and st2_1 and st3_1 and st3_2
-
- final StatisticDescriptor[] statsST2 = new StatisticDescriptor[] {
- manager.createIntGauge( "int_gauge_7", "d7", "u7"),
- manager.createIntGauge( "int_gauge_8", "d8", "u8", false),
- manager.createLongCounter( "long_counter_9", "d9", "u9"),
- manager.createLongCounter( "long_counter_10", "d10", "u10", true),
- manager.createLongGauge( "long_gauge_11", "d11", "u11"),
- manager.createLongGauge( "long_gauge_12", "d12", "u12", false)
- };
- final StatisticsType ST2 = manager.createType("ST2", "ST2", statsST2);
- final Statistics st2_1 = manager.createAtomicStatistics(ST2, "st2_1", 1);
-
- final StatisticDescriptor[] statsST3 = new StatisticDescriptor[] {
- manager.createDoubleCounter("double_counter_1", "d1", "u1"),
- manager.createDoubleCounter("double_counter_2", "d2", "u2", true),
- manager.createDoubleGauge( "double_gauge_3", "d3", "u3"),
- manager.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
- manager.createIntCounter( "int_counter_5", "d5", "u5"),
- manager.createIntCounter( "int_counter_6", "d6", "u6", true),
- };
- final StatisticsType ST3 = manager.createType("ST3", "ST3", statsST3);
- final Statistics st3_1 = manager.createAtomicStatistics(ST3, "st3_1", 1);
- final Statistics st3_2 = manager.createAtomicStatistics(ST3, "st3_2", 2);
-
- // 9) all new values
-
- incDouble(st1_1, "double_counter_1", 9499.10);
- incDouble(st1_1, "double_counter_2", 83.0);
- incDouble(st1_1, "double_gauge_3", -7.05678);
- incDouble(st1_1, "double_gauge_4", 5111.031);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 3);
- incInt(st1_1, "int_gauge_7", 9);
- incInt(st1_1, "int_gauge_8", -3);
- incLong(st1_1, "long_counter_9", 3);
- incLong(st1_1, "long_counter_10", 8);
- incLong(st1_1, "long_gauge_11", 5);
- incLong(st1_1, "long_gauge_12", 4);
-
- incDouble(st1_2, "double_counter_1", 2509.0235);
- incDouble(st1_2, "double_counter_2", 409.10063);
- incDouble(st1_2, "double_gauge_3", -42.66904);
- incDouble(st1_2, "double_gauge_4", 21.0098);
- incInt(st1_2, "int_counter_5", 8);
- incInt(st1_2, "int_counter_6", 9);
- incInt(st1_2, "int_gauge_7", -2);
- incInt(st1_2, "int_gauge_8", 6);
- incLong(st1_2, "long_counter_9", 4);
- incLong(st1_2, "long_counter_10", 5);
- incLong(st1_2, "long_gauge_11", 5);
- incLong(st1_2, "long_gauge_12", -1);
-
- incInt(st2_1, "int_gauge_7", 2);
- incInt(st2_1, "int_gauge_8", -1);
- incLong(st2_1, "long_counter_9", 1002948);
- incLong(st2_1, "long_counter_10", 29038856);
- incLong(st2_1, "long_gauge_11", -2947465);
- incLong(st2_1, "long_gauge_12", 4934745);
-
- incDouble(st3_1, "double_counter_1", 562.0458);
- incDouble(st3_1, "double_counter_2", 14.0086);
- incDouble(st3_1, "double_gauge_3", -2.0);
- incDouble(st3_1, "double_gauge_4", 1.0);
- incInt(st3_1, "int_counter_5", 2);
- incInt(st3_1, "int_counter_6", 1);
-
- incDouble(st3_2, "double_counter_1", 33.087);
- incDouble(st3_2, "double_counter_2", 2.02);
- incDouble(st3_2, "double_gauge_3", 1.06);
- incDouble(st3_2, "double_gauge_4", 3.021);
- incInt(st3_2, "int_counter_5", 1);
- incInt(st3_2, "int_counter_6", 4);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 10) some new values
-
- incDouble(st1_1, "double_counter_1", 3.014);
- incDouble(st1_1, "double_gauge_3", 57.003);
- incInt(st1_1, "int_counter_5", 3);
- incInt(st1_1, "int_gauge_7", 5);
- incLong(st1_1, "long_counter_9", 1);
- incLong(st1_1, "long_gauge_11", 1);
-
- incDouble(st1_2, "double_counter_2", 20.107);
- incDouble(st1_2, "double_gauge_4", 1.5078);
- incInt(st1_2, "int_counter_6", 1);
- incInt(st1_2, "int_gauge_8", -1);
- incLong(st1_2, "long_counter_10", 1073741824);
- incLong(st1_2, "long_gauge_12", 5);
-
- incInt(st2_1, "int_gauge_7", 2);
- incLong(st2_1, "long_counter_9", 2);
- incLong(st2_1, "long_gauge_11", -2);
-
- incDouble(st3_1, "double_counter_1", 24.80097);
- incDouble(st3_1, "double_gauge_3", -22.09834);
- incInt(st3_1, "int_counter_5", 2);
-
- incDouble(st3_2, "double_counter_2", 21.0483);
- incDouble(st3_2, "double_gauge_4", 36310.012);
- incInt(st3_2, "int_counter_6", 4);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 11) remove ST2 and st2_1
-
- manager.destroyStatistics(st2_1);
-
- // 12) some new values
-
- incDouble(st1_1, "double_counter_1", 339.0803);
- incDouble(st1_1, "double_counter_2", 21.06);
- incDouble(st1_1, "double_gauge_3", 12.056);
- incDouble(st1_1, "double_gauge_4", 27.108);
- incInt(st1_1, "int_counter_5", 2);
- incInt(st1_1, "int_counter_6", 4);
-
- incInt(st1_2, "int_gauge_7", 4);
- incInt(st1_2, "int_gauge_8", 7);
- incLong(st1_2, "long_counter_9", 8);
- incLong(st1_2, "long_counter_10", 4);
- incLong(st1_2, "long_gauge_11", 2);
- incLong(st1_2, "long_gauge_12", 1);
-
- incDouble(st3_1, "double_counter_1", 41.103);
- incDouble(st3_1, "double_counter_2", 2.0333);
- incDouble(st3_1, "double_gauge_3", -14.0);
-
- incDouble(st3_2, "double_gauge_4", 26.01);
- incInt(st3_2, "int_counter_5", 3);
- incInt(st3_2, "int_counter_6", 1);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 13) no new values
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 14) remove st1_2
-
- manager.destroyStatistics(st1_2);
-
- // 15) all new values
-
- incDouble(st1_1, "double_counter_1", 62.1350);
- incDouble(st1_1, "double_counter_2", 33.306);
- incDouble(st1_1, "double_gauge_3", 41.1340);
- incDouble(st1_1, "double_gauge_4", -1.04321);
- incInt(st1_1, "int_counter_5", 2);
- incInt(st1_1, "int_counter_6", 2);
- incInt(st1_1, "int_gauge_7", 1);
- incInt(st1_1, "int_gauge_8", 9);
- incLong(st1_1, "long_counter_9", 2);
- incLong(st1_1, "long_counter_10", 5);
- incLong(st1_1, "long_gauge_11", 3);
- incLong(st1_1, "long_gauge_12", -2);
-
- incDouble(st3_1, "double_counter_1", 3461.0153);
- incDouble(st3_1, "double_counter_2", 5.03167);
- incDouble(st3_1, "double_gauge_3", -1.31051);
- incDouble(st3_1, "double_gauge_4", 71.031);
- incInt(st3_1, "int_counter_5", 4);
- incInt(st3_1, "int_counter_6", 2);
-
- incDouble(st3_2, "double_counter_1", 531.5608);
- incDouble(st3_2, "double_counter_2", 55.0532);
- incDouble(st3_2, "double_gauge_3", 8.40956);
- incDouble(st3_2, "double_gauge_4", 23230.0462);
- incInt(st3_2, "int_counter_5", 9);
- incInt(st3_2, "int_counter_6", 5);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // close the writer
-
- writer.close();
-
- // print out all the stat values
-
- if (false) {
- StatisticDescriptor[]
- sds = ST1.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st1_1#"
- + sds[i].getName() + "=" + st1_1.get(sds[i].getName()));
- }
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st1_2#"
- + sds[i].getName() + "=" + st1_2.get(sds[i].getName()));
- }
-
- sds = ST2.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st2_1#"
- + sds[i].getName() + "=" + st2_1.get(sds[i].getName()));
- }
-
- sds = ST3.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st3_1#"
- + sds[i].getName() + "=" + st3_1.get(sds[i].getName()));
- }
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st3_2#"
- + sds[i].getName() + "=" + st3_2.get(sds[i].getName()));
- }
- }
-
- // validate that stat archive file exists
-
- final File actual = new File(archiveFileName);
- assertTrue(actual.exists());
-
- // validate content of stat archive file using StatArchiveReader
-
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{actual}, null, false);
-
- // compare all resourceInst values against what was printed above
-
- @SuppressWarnings("rawtypes")
- final List resources = reader.getResourceInstList();
- for (@SuppressWarnings("rawtypes")
- final Iterator iter = resources.iterator(); iter.hasNext();) {
- final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
- final String resourceName = ri.getName();
- assertNotNull(resourceName);
-
- final String expectedStatsType = this.statisticTypes.get(resourceName);
- assertNotNull(expectedStatsType);
- assertEquals(expectedStatsType, ri.getType().getName());
-
- final Map<String,Number> expectedStatValues = this.allStatistics.get(resourceName);
- assertNotNull(expectedStatValues);
-
- final StatValue[] statValues = ri.getStatValues();
- for (int i = 0; i < statValues.length; i++) {
- final String statName = ri.getType().getStats()[i].getName();
- assertNotNull(statName);
- assertNotNull(expectedStatValues.get(statName));
-
- assertEquals(statName, statValues[i].getDescriptor().getName());
-
- statValues[i].setFilter(StatValue.FILTER_NONE);
- final double[] rawSnapshots = statValues[i].getRawSnapshots();
- //for (int j = 0; j < rawSnapshots.length; j++) {
- // log.convertToLogWriter().info("DEBUG " + ri.getName() + " " + statName + " rawSnapshots[" + j + "] = " + rawSnapshots[j]);
- //}
- assertEquals("Value " + i + " for " + statName + " is wrong: " + expectedStatValues,
- expectedStatValues.get(statName).doubleValue(),
- statValues[i].getSnapshotsMostRecent(), 0.01);
- }
- }
-
- // validate byte content of stat archive file against saved expected file
-
- final File expected = new File(TestUtil.getResourcePath(getClass(), "StatArchiveWriterReaderJUnitTest_" + testName + "_expected.gfs"));
- assertTrue(expected + " does not exist!", expected.exists());
- assertEquals(expected.length(), actual.length());
-
- assertTrue("Actual stat archive file bytes differ from expected stat archive file bytes!",
- Arrays.equals(readBytes(expected), readBytes(actual)));
- }
-
- /**
- * Tests the stat archive file written by StatArchiveWriter.
- */
- @SuppressWarnings("unused")
- @Test
- public void testWriteWhenSamplingBegins() throws Exception {
- final String testName = "testWriteWhenSamplingBegins";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final InternalLogWriter log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final TestStatisticsManager manager = new TestStatisticsManager(
- 1,
- "StatArchiveWriterReaderJUnitTest_" + testName,
- TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS);
-
- final TestStatisticsSampler sampler = new TestStatisticsSampler(manager);
- final SampleCollector sampleCollector = new SampleCollector(sampler);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS - 2000)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
- sampleCollector.addSampleHandler(writer);
-
- long sampleTimeNanos = TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS + StatArchiveFormat.NANOS_PER_MILLI*1000;
-
- // 1) create ST1 and st1_1
-
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createDoubleCounter("double_counter_1", "d1", "u1"),
- manager.createDoubleCounter("double_counter_2", "d2", "u2", true),
- manager.createDoubleGauge( "double_gauge_3", "d3", "u3"),
- manager.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
- manager.createIntCounter( "int_counter_5", "d5", "u5"),
- manager.createIntCounter( "int_counter_6", "d6", "u6", true),
- manager.createIntGauge( "int_gauge_7", "d7", "u7"),
- manager.createIntGauge( "int_gauge_8", "d8", "u8", false),
- manager.createLongCounter( "long_counter_9", "d9", "u9"),
- manager.createLongCounter( "long_counter_10", "d10", "u10", true),
- manager.createLongGauge( "long_gauge_11", "d11", "u11"),
- manager.createLongGauge( "long_gauge_12", "d12", "u12", false)
- };
- final StatisticsType ST1 = manager.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1", 1);
-
- // 2) create st1_2
-
- final Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2", 2);
-
- // 3) some new values
-
- incDouble(st1_1, "double_counter_1", 18347.94880);
- incDouble(st1_1, "double_gauge_4", 24885.02346);
- incInt(st1_1, "int_counter_5", 3);
- incInt(st1_1, "int_gauge_8", 4);
- incLong(st1_1, "long_counter_9", 1073741824);
- incLong(st1_1, "long_gauge_12", 154367897);
-
- incDouble(st1_2, "double_counter_2", 346.95);
- incDouble(st1_2, "double_gauge_3", 9865.23008);
- incInt(st1_2, "int_counter_6", 4);
- incInt(st1_2, "int_gauge_7", 3);
- incLong(st1_2, "long_counter_10", 3497536);
- incLong(st1_2, "long_gauge_11", 103909646);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 4) all new values
-
- incDouble(st1_1, "double_counter_1", 1.098367);
- incDouble(st1_1, "double_counter_2", 50247.0983254);
- incDouble(st1_1, "double_gauge_3", 987654.2344);
- incDouble(st1_1, "double_gauge_4", 23.097);
- incInt(st1_1, "int_counter_5", 3);
- incInt(st1_1, "int_counter_6", 4);
- incInt(st1_1, "int_gauge_7", 3);
- incInt(st1_1, "int_gauge_8", 4);
- incLong(st1_1, "long_counter_9", 5);
- incLong(st1_1, "long_counter_10", 465793);
- incLong(st1_1, "long_gauge_11", -203050);
- incLong(st1_1, "long_gauge_12", 6);
-
- incDouble(st1_2, "double_counter_1", 0.000846643);
- incDouble(st1_2, "double_counter_2", 4.0);
- incDouble(st1_2, "double_gauge_3", -4.0);
- incDouble(st1_2, "double_gauge_4", 19276.0346624);
- incInt(st1_2, "int_counter_5", 1);
- incInt(st1_2, "int_counter_6", 2);
- incInt(st1_2, "int_gauge_7", -1);
- incInt(st1_2, "int_gauge_8", -2);
- incLong(st1_2, "long_counter_9", 309876);
- incLong(st1_2, "long_counter_10", 4);
- incLong(st1_2, "long_gauge_11", -4);
- incLong(st1_2, "long_gauge_12", 1098764);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 5) no new values
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 6) some new values
-
- incDouble(st1_1, "double_counter_2", 10.255);
- incDouble(st1_1, "double_gauge_3", -4123.05);
- incInt(st1_1, "int_counter_6", 2);
- incInt(st1_1, "int_gauge_7", 3);
- incLong(st1_1, "long_counter_10", 4);
- incLong(st1_1, "long_gauge_11", -2);
-
- incDouble(st1_2, "double_counter_1", 5.00007634);
- incDouble(st1_2, "double_gauge_4", 16904.06524);
- incInt(st1_2, "int_counter_5", 4);
- incInt(st1_2, "int_gauge_8", 1);
- incLong(st1_2, "long_counter_9", 8);
- incLong(st1_2, "long_gauge_12", 10);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 7) all new values
-
- incDouble(st1_1, "double_counter_1", 4065.340);
- incDouble(st1_1, "double_counter_2", 2.01342568);
- incDouble(st1_1, "double_gauge_3", 1.367890);
- incDouble(st1_1, "double_gauge_4", 8.0549003);
- incInt(st1_1, "int_counter_5", 2);
- incInt(st1_1, "int_counter_6", 9);
- incInt(st1_1, "int_gauge_7", 1);
- incInt(st1_1, "int_gauge_8", 2);
- incLong(st1_1, "long_counter_9", 6);
- incLong(st1_1, "long_counter_10", 2);
- incLong(st1_1, "long_gauge_11", -10);
- incLong(st1_1, "long_gauge_12", 8);
-
- incDouble(st1_2, "double_counter_1", 128.2450);
- incDouble(st1_2, "double_counter_2", 113.550);
- incDouble(st1_2, "double_gauge_3", 21.0676);
- incDouble(st1_2, "double_gauge_4", 2.01346);
- incInt(st1_2, "int_counter_5", 3);
- incInt(st1_2, "int_counter_6", 4);
- incInt(st1_2, "int_gauge_7", 4);
- incInt(st1_2, "int_gauge_8", 2);
- incLong(st1_2, "long_counter_9", 1);
- incLong(st1_2, "long_counter_10", 2);
- incLong(st1_2, "long_gauge_11", 3);
- incLong(st1_2, "long_gauge_12", -2);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 8) create ST2 and ST3 and st2_1 and st3_1 and st3_2
-
- final StatisticDescriptor[] statsST2 = new StatisticDescriptor[] {
- manager.createIntGauge( "int_gauge_7", "d7", "u7"),
- manager.createIntGauge( "int_gauge_8", "d8", "u8", false),
- manager.createLongCounter( "long_counter_9", "d9", "u9"),
- manager.createLongCounter( "long_counter_10", "d10", "u10", true),
- manager.createLongGauge( "long_gauge_11", "d11", "u11"),
- manager.createLongGauge( "long_gauge_12", "d12", "u12", false)
- };
- final StatisticsType ST2 = manager.createType("ST2", "ST2", statsST2);
- final Statistics st2_1 = manager.createAtomicStatistics(ST2, "st2_1", 1);
-
- final StatisticDescriptor[] statsST3 = new StatisticDescriptor[] {
- manager.createDoubleCounter("double_counter_1", "d1", "u1"),
- manager.createDoubleCounter("double_counter_2", "d2", "u2", true),
- manager.createDoubleGauge( "double_gauge_3", "d3", "u3"),
- manager.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
- manager.createIntCounter( "int_counter_5", "d5", "u5"),
- manager.createIntCounter( "int_counter_6", "d6", "u6", true),
- };
- final StatisticsType ST3 = manager.createType("ST3", "ST3", statsST3);
- final Statistics st3_1 = manager.createAtomicStatistics(ST3, "st3_1", 1);
- final Statistics st3_2 = manager.createAtomicStatistics(ST3, "st3_2", 2);
-
- // 9) all new values
-
- incDouble(st1_1, "double_counter_1", 9499.10);
- incDouble(st1_1, "double_counter_2", 83.0);
- incDouble(st1_1, "double_gauge_3", -7.05678);
- incDouble(st1_1, "double_gauge_4", 5111.031);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 3);
- incInt(st1_1, "int_gauge_7", 9);
- incInt(st1_1, "int_gauge_8", -3);
- incLong(st1_1, "long_counter_9", 3);
- incLong(st1_1, "long_counter_10", 8);
- incLong(st1_1, "long_gauge_11", 5);
- incLong(st1_1, "long_gauge_12", 4);
-
- incDouble(st1_2, "double_counter_1", 2509.0235);
- incDouble(st1_2, "double_counter_2", 409.10063);
- incDouble(st1_2, "double_gauge_3", -42.66904);
- incDouble(st1_2, "double_gauge_4", 21.0098);
- incInt(st1_2, "int_counter_5", 8);
- incInt(st1_2, "int_counter_6", 9);
- incInt(st1_2, "int_gauge_7", -2);
- incInt(st1_2, "int_gauge_8", 6);
- incLong(st1_2, "long_counter_9", 4);
- incLong(st1_2, "long_counter_10", 5);
- incLong(st1_2, "long_gauge_11", 5);
- incLong(st1_2, "long_gauge_12", -1);
-
- incInt(st2_1, "int_gauge_7", 2);
- incInt(st2_1, "int_gauge_8", -1);
- incLong(st2_1, "long_counter_9", 1002948);
- incLong(st2_1, "long_counter_10", 29038856);
- incLong(st2_1, "long_gauge_11", -2947465);
- incLong(st2_1, "long_gauge_12", 4934745);
-
- incDouble(st3_1, "double_counter_1", 562.0458);
- incDouble(st3_1, "double_counter_2", 14.0086);
- incDouble(st3_1, "double_gauge_3", -2.0);
- incDouble(st3_1, "double_gauge_4", 1.0);
- incInt(st3_1, "int_counter_5", 2);
- incInt(st3_1, "int_counter_6", 1);
-
- incDouble(st3_2, "double_counter_1", 33.087);
- incDouble(st3_2, "double_counter_2", 2.02);
- incDouble(st3_2, "double_gauge_3", 1.06);
- incDouble(st3_2, "double_gauge_4", 3.021);
- incInt(st3_2, "int_counter_5", 1);
- incInt(st3_2, "int_counter_6", 4);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 10) some new values
-
- incDouble(st1_1, "double_counter_1", 3.014);
- incDouble(st1_1, "double_gauge_3", 57.003);
- incInt(st1_1, "int_counter_5", 3);
- incInt(st1_1, "int_gauge_7", 5);
- incLong(st1_1, "long_counter_9", 1);
- incLong(st1_1, "long_gauge_11", 1);
-
- incDouble(st1_2, "double_counter_2", 20.107);
- incDouble(st1_2, "double_gauge_4", 1.5078);
- incInt(st1_2, "int_counter_6", 1);
- incInt(st1_2, "int_gauge_8", -1);
- incLong(st1_2, "long_counter_10", 1073741824);
- incLong(st1_2, "long_gauge_12", 5);
-
- incInt(st2_1, "int_gauge_7", 2);
- incLong(st2_1, "long_counter_9", 2);
- incLong(st2_1, "long_gauge_11", -2);
-
- incDouble(st3_1, "double_counter_1", 24.80097);
- incDouble(st3_1, "double_gauge_3", -22.09834);
- incInt(st3_1, "int_counter_5", 2);
-
- incDouble(st3_2, "double_counter_2", 21.0483);
- incDouble(st3_2, "double_gauge_4", 36310.012);
- incInt(st3_2, "int_counter_6", 4);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 11) remove ST2 and st2_1
-
- manager.destroyStatistics(st2_1);
-
- // 12) some new values
-
- incDouble(st1_1, "double_counter_1", 339.0803);
- incDouble(st1_1, "double_counter_2", 21.06);
- incDouble(st1_1, "double_gauge_3", 12.056);
- incDouble(st1_1, "double_gauge_4", 27.108);
- incInt(st1_1, "int_counter_5", 2);
- incInt(st1_1, "int_counter_6", 4);
-
- incInt(st1_2, "int_gauge_7", 4);
- incInt(st1_2, "int_gauge_8", 7);
- incLong(st1_2, "long_counter_9", 8);
- incLong(st1_2, "long_counter_10", 4);
- incLong(st1_2, "long_gauge_11", 2);
- incLong(st1_2, "long_gauge_12", 1);
-
- incDouble(st3_1, "double_counter_1", 41.103);
- incDouble(st3_1, "double_counter_2", 2.0333);
- incDouble(st3_1, "double_gauge_3", -14.0);
-
- incDouble(st3_2, "double_gauge_4", 26.01);
- incInt(st3_2, "int_counter_5", 3);
- incInt(st3_2, "int_counter_6", 1);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 13) no new values
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // 14) remove st1_2
-
- manager.destroyStatistics(st1_2);
-
- // 15) all new values
-
- incDouble(st1_1, "double_counter_1", 62.1350);
- incDouble(st1_1, "double_counter_2", 33.306);
- incDouble(st1_1, "double_gauge_3", 41.1340);
- incDouble(st1_1, "double_gauge_4", -1.04321);
- incInt(st1_1, "int_counter_5", 2);
- incInt(st1_1, "int_counter_6", 2);
- incInt(st1_1, "int_gauge_7", 1);
- incInt(st1_1, "int_gauge_8", 9);
- incLong(st1_1, "long_counter_9", 2);
- incLong(st1_1, "long_counter_10", 5);
- incLong(st1_1, "long_gauge_11", 3);
- incLong(st1_1, "long_gauge_12", -2);
-
- incDouble(st3_1, "double_counter_1", 3461.0153);
- incDouble(st3_1, "double_counter_2", 5.03167);
- incDouble(st3_1, "double_gauge_3", -1.31051);
- incDouble(st3_1, "double_gauge_4", 71.031);
- incInt(st3_1, "int_counter_5", 4);
- incInt(st3_1, "int_counter_6", 2);
-
- incDouble(st3_2, "double_counter_1", 531.5608);
- incDouble(st3_2, "double_counter_2", 55.0532);
- incDouble(st3_2, "double_gauge_3", 8.40956);
- incDouble(st3_2, "double_gauge_4", 23230.0462);
- incInt(st3_2, "int_counter_5", 9);
- incInt(st3_2, "int_counter_6", 5);
-
- sampleCollector.sample(sampleTimeNanos+=(1000*StatArchiveFormat.NANOS_PER_MILLI));
-
- // close the writer
-
- writer.close();
-
- // print out all the stat values
-
- if (false) {
- StatisticDescriptor[]
- sds = ST1.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st1_1#"
- + sds[i].getName() + "=" + st1_1.get(sds[i].getName()));
- }
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st1_2#"
- + sds[i].getName() + "=" + st1_2.get(sds[i].getName()));
- }
-
- sds = ST2.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st2_1#"
- + sds[i].getName() + "=" + st2_1.get(sds[i].getName()));
- }
-
- sds = ST3.getStatistics();
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st3_1#"
- + sds[i].getName() + "=" + st3_1.get(sds[i].getName()));
- }
- for (int i = 0; i < sds.length; i++) {
- log.convertToLogWriter().info("testWriteAfterSamplingBegins#st3_2#"
- + sds[i].getName() + "=" + st3_2.get(sds[i].getName()));
- }
- }
-
- // validate that stat archive file exists
-
- final File actual = new File(archiveFileName);
- assertTrue(actual.exists());
-
- // validate content of stat archive file using StatArchiveReader
-
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{actual}, null, false);
-
- // compare all resourceInst values against what was printed above
-
- @SuppressWarnings("rawtypes")
- final List resources = reader.getResourceInstList();
- for (@SuppressWarnings("rawtypes")
- final Iterator iter = resources.iterator(); iter.hasNext();) {
- final StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
- final String resourceName = ri.getName();
- assertNotNull(resourceName);
-
- final String expectedStatsType = this.statisticTypes.get(resourceName);
- assertNotNull(expectedStatsType);
- assertEquals(expectedStatsType, ri.getType().getName());
-
- final Map<String,Number> expectedStatValues = this.allStatistics.get(resourceName);
- assertNotNull(expectedStatValues);
-
- final StatValue[] statValues = ri.getStatValues();
- for (int i = 0; i < statValues.length; i++) {
- final String statName = ri.getType().getStats()[i].getName();
- assertNotNull(statName);
- assertNotNull(expectedStatValues.get(statName));
-
- assertEquals(statName, statValues[i].getDescriptor().getName());
-
- statValues[i].setFilter(StatValue.FILTER_NONE);
- final double[] rawSnapshots = statValues[i].getRawSnapshots();
- //for (int j = 0; j < rawSnapshots.length; j++) {
- // log.convertToLogWriter().info("DEBUG " + ri.getName() + " " + statName + " rawSnapshots[" + j + "] = " + rawSnapshots[j]);
- //}
- assertEquals("Value " + i + " for " + statName + " is wrong: " + expectedStatValues,
- expectedStatValues.get(statName).doubleValue(),
- statValues[i].getSnapshotsMostRecent(), 0.01);
- }
- }
-
- // validate byte content of stat archive file against saved expected file
-
- final File expected = new File(TestUtil.getResourcePath(getClass(), "StatArchiveWriterReaderJUnitTest_" + testName + "_expected.gfs"));
- assertTrue(expected + " does not exist!", expected.exists());
- assertEquals(expected.length(), actual.length());
-
- assertTrue("Actual stat archive file bytes differ from expected stat archive file bytes!",
- Arrays.equals(readBytes(expected), readBytes(actual)));
- }
-
- /**
- * Validates that IllegalArgumentException is thrown if sample time stamp is
- * before the previous time stamp. Tests the fix for cause of bug #45268.
- */
- @Test
- public void testNegativeSampleTimeStamp() throws Exception {
- final String testName = "testNegativeSampleTimeStamp";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final LogWriterI18n log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
-
- final long sampleIncNanos = StatArchiveFormat.NANOS_PER_MILLI*1000;
-
- try {
- writer.sampled(TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS - sampleIncNanos,
- Collections.<ResourceInstance>emptyList());
- fail("Expected IllegalArgumentException to be thrown from StatArchiveWriter#writeTimeStamp(long)");
- } catch (IllegalArgumentException expected) {
- // test passed
- } finally {
- writer.close();
- }
- }
-
- /**
- * Validates that IllegalArgumentException is thrown if sample time stamp is
- * same as the previous time stamp. Tests the fix for cause of bug #45268.
- */
- @Test
- public void testPreviousSampleTimeStamp() throws Exception {
- final String testName = "testPreviousSampleTimeStamp";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final LogWriterI18n log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
-
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
-
- try {
- writer.sampled(TestStatArchiveWriter.WRITER_PREVIOUS_TIMESTAMP_NANOS,
- Collections.<ResourceInstance>emptyList());
- fail("Expected IllegalArgumentException to be thrown from StatArchiveWriter#writeTimeStamp(long)");
- } catch (IllegalArgumentException expected) {
- // test passed
- } finally {
- writer.close();
- }
-
- writer.close();
- }
-
- /**
- * Verifies fix for bug #45377.
- */
- @Test
- public void testDestroyClosedStatistics() throws Exception {
- final String testName = "testDestroyClosedStatistics";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final LogWriterI18n log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS - 2000)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
-
- final StatisticsType statsType = createDummyStatisticsType();
- final ResourceType rt = new ResourceType(0, statsType);
- final Statistics statistics = mock(Statistics.class);
- when(statistics.isClosed()).thenReturn(true);
- final ResourceInstance ri = new ResourceInstance(0, statistics, rt);
-
- // if bug #45377 still existed, this call would throw IllegalStateException
- writer.destroyedResourceInstance(ri);
- }
-
- /**
- * Control which helps verify fix for bug #45377.
- */
- @Test
- public void testDestroyUnallocatedStatistics() throws Exception {
- final String testName = "testDestroyUnallocatedStatistics";
- final String archiveFileName = dir + File.separator + testName + ".gfs";
-
- final LogWriterI18n log = new PureLogWriter(InternalLogWriter.CONFIG_LEVEL);
- final StatArchiveDescriptor archiveDescriptor = new StatArchiveDescriptor.Builder()
- .setArchiveName(archiveFileName)
- .setSystemId(1)
- .setSystemStartTime(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS - 2000)
- .setSystemDirectoryPath(testName)
- .setProductDescription("StatArchiveWriterReaderJUnitTest")
- .build();
- final StatArchiveWriter writer = new TestStatArchiveWriter(archiveDescriptor, log);
-
- final StatisticsType statsType = createDummyStatisticsType();
- final ResourceType rt = new ResourceType(0, statsType);
- final Statistics statistics = mock(Statistics.class);
- final ResourceInstance ri = new ResourceInstance(0, statistics, rt);
-
- writer.sampled(TestStatArchiveWriter.WRITER_INITIAL_DATE_MILLIS + 1000,
- Collections.<ResourceInstance>singletonList(ri));
-
- writer.destroyedResourceInstance(ri);
- writer.close();
-
- // Verify StatArchiveRader.update returns cleanly, without throwing an exception
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{new File(archiveFileName)}, null, false);
- reader.update();
- reader.close();
- }
-
- private void incDouble(Statistics statistics, String stat, double value) {
- assertFalse(statistics.isClosed());
- Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
- if (statValues == null) {
- statValues = new HashMap<String,Number>();
- this.allStatistics.put(statistics.getTextId(), statValues);
- }
- statistics.incDouble(stat, value);
- statValues.put(stat, statistics.getDouble(stat));
- if (this.statisticTypes.get(statistics.getTextId()) == null) {
- this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
- }
- }
-
- private void incInt(Statistics statistics, String stat, int value) {
- assertFalse(statistics.isClosed());
- Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
- if (statValues == null) {
- statValues = new HashMap<String,Number>();
- this.allStatistics.put(statistics.getTextId(), statValues);
- }
- statistics.incInt(stat, value);
- statValues.put(stat, statistics.getInt(stat));
- if (this.statisticTypes.get(statistics.getTextId()) == null) {
- this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
- }
- }
-
- private void incLong(Statistics statistics, String stat, long value) {
- assertFalse(statistics.isClosed());
- Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
- if (statValues == null) {
- statValues = new HashMap<String,Number>();
- this.allStatistics.put(statistics.getTextId(), statValues);
- }
- statistics.incLong(stat, value);
- statValues.put(stat, statistics.getLong(stat));
- if (this.statisticTypes.get(statistics.getTextId()) == null) {
- this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
- }
- }
-
- private byte[] readBytes(File file) throws MalformedURLException, IOException {
- int byteCount = (int)file.length();
-
- byte[] input = new byte[byteCount];
-
- @SuppressWarnings("deprecation")
- URL url = file.toURL();
- assertNotNull(url);
-
- InputStream is = url.openStream();
- assertNotNull(is);
-
- BufferedInputStream bis = new BufferedInputStream(is);
- int bytesRead = bis.read(input);
- bis.close();
-
- assertEquals(byteCount, bytesRead);
- return input;
- }
-
- private static StatisticsType createDummyStatisticsType() {
- return new StatisticsType() {
-
- @Override
- public String getName() {
- return null;
- }
-
- @Override
- public String getDescription() {
- return null;
- }
-
- @Override
- public StatisticDescriptor[] getStatistics() {
- return new StatisticDescriptor[0];
- }
-
- @Override
- public int nameToId(String name) {
- return 0;
- }
-
- @Override
- public StatisticDescriptor nameToDescriptor(String name) {
- return null;
- }
- };
- }
-
- /* [KEEP] alternative method for getting an expected golden file:
- Class clazz = getClass();
- assertNotNull(clazz);
- URL url = clazz.getResource("StatArchiveWriterReaderJUnitTest.gfs.expected");
- assertNotNull(url);
-
- File expected;
- try {
- expected = new File(url.toURI());
- } catch(URISyntaxException e) {
- expected = new File(url.getPath());
- }
- assertTrue(expected.exists());
- */
-}
[06/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SampleCollectorJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SampleCollectorJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SampleCollectorJUnitTest.java
deleted file mode 100755
index 1babbc1..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SampleCollectorJUnitTest.java
+++ /dev/null
@@ -1,322 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal.statistics;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-
-import java.io.File;
-import java.util.List;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import com.gemstone.gemfire.StatisticDescriptor;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.internal.statistics.TestSampleHandler.Info;
-import com.gemstone.gemfire.internal.statistics.TestSampleHandler.ResourceInstanceInfo;
-import com.gemstone.gemfire.internal.statistics.TestSampleHandler.ResourceTypeInfo;
-import com.gemstone.gemfire.internal.statistics.TestSampleHandler.SampledInfo;
-import com.gemstone.gemfire.test.junit.categories.UnitTest;
-
-/**
- * Unit tests for the SampleCollector class. No disk IO.
- *
- * @since GemFire 7.0
- */
-@Category(UnitTest.class)
-public class SampleCollectorJUnitTest {
-
- private TestStatisticsManager manager;
- private SampleCollector sampleCollector;
-
- @Before
- public void setUp() throws Exception {
- final long startTime = System.currentTimeMillis();
- this.manager = new TestStatisticsManager(1, getClass().getSimpleName(), startTime);
-
- final StatArchiveHandlerConfig mockStatArchiveHandlerConfig = mock(StatArchiveHandlerConfig.class, getClass().getSimpleName() + "$" + StatArchiveHandlerConfig.class.getSimpleName());
- when(mockStatArchiveHandlerConfig.getArchiveFileName()).thenReturn(new File(""));
- when(mockStatArchiveHandlerConfig.getArchiveFileSizeLimit()).thenReturn(0L);
- when(mockStatArchiveHandlerConfig.getArchiveDiskSpaceLimit()).thenReturn(0L);
- when(mockStatArchiveHandlerConfig.getSystemId()).thenReturn(0L);
- when(mockStatArchiveHandlerConfig.getSystemStartTime()).thenReturn(startTime);
- when(mockStatArchiveHandlerConfig.getSystemDirectoryPath()).thenReturn("");
- when(mockStatArchiveHandlerConfig.getProductDescription()).thenReturn(getClass().getSimpleName());
-
- final StatisticsSampler sampler = new TestStatisticsSampler(manager);
- this.sampleCollector = new SampleCollector(sampler);
- this.sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime());
- }
-
- @After
- public void tearDown() throws Exception {
- if (this.sampleCollector != null) {
- this.sampleCollector.close();
- this.sampleCollector = null;
- }
- this.manager = null;
- }
-
- @Test
- public void testAddHandlerBeforeSample() {
- TestSampleHandler handler = new TestSampleHandler();
- this.sampleCollector.addSampleHandler(handler);
-
- StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createIntCounter("ST1_1_name", "ST1_1_desc", "ST1_1_units")
- };
- StatisticsType ST1 = manager.createType("ST1_name", "ST1_desc", statsST1);
- Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1_text", 1);
-
- this.sampleCollector.sample(NanoTimer.getTime());
-
- assertEquals(3, handler.getNotificationCount());
- List<Info> notifications = handler.getNotifications();
-
- // validate the allocatedResourceType notification
- assertTrue(notifications.get(0) instanceof ResourceTypeInfo);
- ResourceTypeInfo allocatedResourceTypeInfo = (ResourceTypeInfo) notifications.get(0);
- assertNotNull(allocatedResourceTypeInfo);
- assertEquals("allocatedResourceType", allocatedResourceTypeInfo.getName());
- ResourceType resourceType = allocatedResourceTypeInfo.getResourceType();
- assertNotNull(resourceType);
- assertEquals(0, resourceType.getId());
- assertEquals(1, resourceType.getStatisticDescriptors().length);
- StatisticsType statisticsType = resourceType.getStatisticsType();
- assertNotNull(statisticsType);
- assertTrue(statisticsType == ST1);
- assertEquals("ST1_name", statisticsType.getName());
- assertEquals("ST1_desc", statisticsType.getDescription());
- assertEquals(1, statisticsType.getStatistics().length);
-
- // validate the allocatedResourceInstance notification
- assertTrue(notifications.get(1) instanceof ResourceInstanceInfo);
- ResourceInstanceInfo allocatedResourceInstanceInfo = (ResourceInstanceInfo) notifications.get(1);
- assertNotNull(allocatedResourceInstanceInfo);
- assertEquals("allocatedResourceInstance", allocatedResourceInstanceInfo.getName());
- ResourceInstance resourceInstance = allocatedResourceInstanceInfo.getResourceInstance();
- assertNotNull(resourceInstance);
- assertEquals(0, resourceInstance.getId());
- assertEquals(1, resourceInstance.getUpdatedStats().length);
- assertEquals(1, resourceInstance.getLatestStatValues().length); // TODO: is this correct?
- Statistics statistics = resourceInstance.getStatistics();
- assertNotNull(statistics);
- assertTrue(statistics == st1_1);
- assertEquals(1, statistics.getUniqueId());
- assertEquals(1, statistics.getNumericId());
- assertEquals("st1_1_text", statistics.getTextId());
- assertEquals("ST1_name", statistics.getType().getName());
- assertTrue(resourceType == resourceInstance.getResourceType());
-
- // validate the sampled notification
- assertTrue(notifications.get(2) instanceof SampledInfo);
- SampledInfo sampledInfo = (SampledInfo) notifications.get(2);
- assertNotNull(sampledInfo);
- assertEquals("sampled", sampledInfo.getName());
- assertEquals(1, sampledInfo.getResourceCount());
- }
-
- @Test
- public void testAddHandlerAfterSamples() {
- StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- manager.createIntCounter("ST1_1_name", "ST1_1_desc", "ST1_1_units")
- };
- StatisticsType ST1 = manager.createType("ST1_name", "ST1_desc", statsST1);
- Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1_text", 1);
- Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2_text", 1);
-
- StatisticDescriptor[] statsST2 = new StatisticDescriptor[] {
- manager.createIntCounter("ST2_1_name", "ST2_1_desc", "ST2_1_units")
- };
- StatisticsType ST2 = manager.createType("ST2_name", "ST2_desc", statsST2);
- Statistics st2_1 = manager.createAtomicStatistics(ST2, "st2_1_text", 1);
-
- st1_1.incInt("ST1_1_name", 1);
- st1_2.incInt("ST1_1_name", 1);
- st2_1.incInt("ST2_1_name", 1);
- long sampleTime = NanoTimer.getTime();
- this.sampleCollector.sample(sampleTime);
-
- st1_1.incInt("ST1_1_name", 2);
- st2_1.incInt("ST2_1_name", 1);
- sampleTime += NanoTimer.millisToNanos(1000);
- this.sampleCollector.sample(sampleTime);
-
- st1_1.incInt("ST1_1_name", 1);
- st1_1.incInt("ST1_1_name", 2);
- sampleTime += NanoTimer.millisToNanos(1000);
- this.sampleCollector.sample(sampleTime);
-
- TestSampleHandler handler = new TestSampleHandler();
- this.sampleCollector.addSampleHandler(handler);
-
- assertEquals("TestSampleHandler = " + handler, 0, handler.getNotificationCount());
-
- st1_2.incInt("ST1_1_name", 1);
- st2_1.incInt("ST2_1_name", 1);
- sampleTime += NanoTimer.millisToNanos(1000);
- this.sampleCollector.sample(sampleTime);
-
- assertEquals(6, handler.getNotificationCount());
- List<Info> notifications = handler.getNotifications();
-
- // validate the allocatedResourceType notification for ST1
- int notificationIdx = 0;
- assertTrue(notifications.get(notificationIdx) instanceof ResourceTypeInfo);
- ResourceTypeInfo allocatedResourceTypeInfo = (ResourceTypeInfo) notifications.get(notificationIdx);
- assertNotNull(allocatedResourceTypeInfo);
- assertEquals("allocatedResourceType", allocatedResourceTypeInfo.getName());
- ResourceType resourceType = allocatedResourceTypeInfo.getResourceType();
- assertNotNull(resourceType);
- assertEquals(0, resourceType.getId());
- assertEquals(1, resourceType.getStatisticDescriptors().length);
- StatisticsType statisticsType = resourceType.getStatisticsType();
- assertNotNull(statisticsType);
- assertTrue(statisticsType == ST1);
- assertEquals("ST1_name", statisticsType.getName());
- assertEquals("ST1_desc", statisticsType.getDescription());
- assertEquals(1, statisticsType.getStatistics().length);
-
- // validate the allocatedResourceInstance notification for st1_1
- notificationIdx++;
- assertTrue(notifications.get(notificationIdx) instanceof ResourceInstanceInfo);
- ResourceInstanceInfo allocatedResourceInstanceInfo = (ResourceInstanceInfo) notifications.get(notificationIdx);
- assertNotNull(allocatedResourceInstanceInfo);
- assertEquals("allocatedResourceInstance", allocatedResourceInstanceInfo.getName());
- ResourceInstance resourceInstance = allocatedResourceInstanceInfo.getResourceInstance();
- assertNotNull(resourceInstance);
- assertEquals(0, resourceInstance.getId());
- assertEquals(0, resourceInstance.getUpdatedStats().length);
- assertEquals(1, resourceInstance.getLatestStatValues().length); // TODO: is this correct?
- Statistics statistics = resourceInstance.getStatistics();
- assertNotNull(statistics);
- assertTrue(statistics == st1_1);
- assertEquals(1, statistics.getUniqueId());
- assertEquals(1, statistics.getNumericId());
- assertEquals("st1_1_text", statistics.getTextId());
- assertEquals("ST1_name", statistics.getType().getName());
- assertTrue(resourceType == resourceInstance.getResourceType());
-
- // validate the allocatedResourceInstance notification for st1_2
- notificationIdx++;
- assertTrue(notifications.get(notificationIdx) instanceof ResourceInstanceInfo);
- allocatedResourceInstanceInfo = (ResourceInstanceInfo) notifications.get(notificationIdx);
- assertNotNull(allocatedResourceInstanceInfo);
- assertEquals("allocatedResourceInstance", allocatedResourceInstanceInfo.getName());
- resourceInstance = allocatedResourceInstanceInfo.getResourceInstance();
- assertNotNull(resourceInstance);
- assertEquals(1, resourceInstance.getId());
- assertEquals(1, resourceInstance.getUpdatedStats().length);
- assertEquals(1, resourceInstance.getLatestStatValues().length); // TODO: is this correct?
- statistics = resourceInstance.getStatistics();
- assertNotNull(statistics);
- assertTrue(statistics == st1_2);
- assertEquals(2, statistics.getUniqueId());
- assertEquals(1, statistics.getNumericId());
- assertEquals("st1_2_text", statistics.getTextId());
- assertEquals("ST1_name", statistics.getType().getName());
- assertTrue(resourceType == resourceInstance.getResourceType());
-
- // validate the allocatedResourceType notification for ST2
- notificationIdx++;
- assertTrue(notifications.get(notificationIdx) instanceof ResourceTypeInfo);
- allocatedResourceTypeInfo = (ResourceTypeInfo) notifications.get(notificationIdx);
- assertNotNull(allocatedResourceTypeInfo);
- assertEquals("allocatedResourceType", allocatedResourceTypeInfo.getName());
- resourceType = allocatedResourceTypeInfo.getResourceType();
- assertNotNull(resourceType);
- assertEquals(1, resourceType.getId());
- assertEquals(1, resourceType.getStatisticDescriptors().length);
- statisticsType = resourceType.getStatisticsType();
- assertNotNull(statisticsType);
- assertTrue(statisticsType == ST2);
- assertEquals("ST2_name", statisticsType.getName());
- assertEquals("ST2_desc", statisticsType.getDescription());
- assertEquals(1, statisticsType.getStatistics().length);
-
- // validate the allocatedResourceInstance notification for st2_1
- notificationIdx++;
- assertTrue(notifications.get(notificationIdx) instanceof ResourceInstanceInfo);
- allocatedResourceInstanceInfo = (ResourceInstanceInfo) notifications.get(notificationIdx);
- assertNotNull(allocatedResourceInstanceInfo);
- assertEquals("allocatedResourceInstance", allocatedResourceInstanceInfo.getName());
- resourceInstance = allocatedResourceInstanceInfo.getResourceInstance();
- assertNotNull(resourceInstance);
- assertEquals(2, resourceInstance.getId());
- assertEquals(1, resourceInstance.getUpdatedStats().length);
- assertEquals(1, resourceInstance.getLatestStatValues().length); // TODO: is this correct?
- statistics = resourceInstance.getStatistics();
- assertNotNull(statistics);
- assertTrue(statistics == st2_1);
- assertEquals(3, statistics.getUniqueId());
- assertEquals(1, statistics.getNumericId());
- assertEquals("st2_1_text", statistics.getTextId());
- assertEquals("ST2_name", statistics.getType().getName());
- assertTrue(resourceType == resourceInstance.getResourceType());
-
- // validate the sampled notification
- notificationIdx++;
- assertTrue(notifications.get(notificationIdx) instanceof SampledInfo);
- SampledInfo sampledInfo = (SampledInfo) notifications.get(notificationIdx);
- assertNotNull(sampledInfo);
- assertEquals("sampled", sampledInfo.getName());
- assertEquals(3, sampledInfo.getResourceCount());
- }
-
- @Test
- public void testGetStatMonitorHandler() {
- StatMonitorHandler handler = SampleCollector.getStatMonitorHandler();
- assertNotNull(handler);
- assertTrue(handler.getMonitorsSnapshot().isEmpty());
- assertNull(handler.getStatMonitorNotifier());
- }
-
- @Test
- public void testGetStatMonitorHandlerAfterClose() {
- this.sampleCollector.close();
- try {
- /*StatMonitorHandler handler =*/ SampleCollector.getStatMonitorHandler();
- fail("getStatMonitorHandler should throw IllegalStateException when SampleCollector is closed");
- } catch (IllegalStateException expected) {
- // passed
- }
- }
-
- @Test
- public void testGetStatMonitorHandlerBeforeAndAfterClose() {
- StatMonitorHandler handler = SampleCollector.getStatMonitorHandler();
- assertNotNull(handler);
- this.sampleCollector.close();
- try {
- handler = SampleCollector.getStatMonitorHandler();
- fail("getStatMonitorHandler should throw IllegalStateException when SampleCollector is closed");
- } catch (IllegalStateException expected) {
- // passed
- }
- }
-
- @Test
- public void testGetStatArchiveHandler() {
- StatArchiveHandler handler = this.sampleCollector.getStatArchiveHandler();
- assertNotNull(handler);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SampleCollectorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SampleCollectorTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SampleCollectorTest.java
new file mode 100755
index 0000000..dd6de34
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SampleCollectorTest.java
@@ -0,0 +1,322 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.*;
+
+import java.io.File;
+import java.util.List;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.NanoTimer;
+import com.gemstone.gemfire.internal.statistics.TestSampleHandler.Info;
+import com.gemstone.gemfire.internal.statistics.TestSampleHandler.ResourceInstanceInfo;
+import com.gemstone.gemfire.internal.statistics.TestSampleHandler.ResourceTypeInfo;
+import com.gemstone.gemfire.internal.statistics.TestSampleHandler.SampledInfo;
+import com.gemstone.gemfire.test.junit.categories.UnitTest;
+
+/**
+ * Unit tests for {@link SampleCollector}.
+ *
+ * @since GemFire 7.0
+ */
+@Category(UnitTest.class)
+public class SampleCollectorTest {
+
+ private TestStatisticsManager manager;
+ private SampleCollector sampleCollector;
+
+ @Before
+ public void setUp() throws Exception {
+ final long startTime = System.currentTimeMillis();
+ this.manager = new TestStatisticsManager(1, getClass().getSimpleName(), startTime);
+
+ final StatArchiveHandlerConfig mockStatArchiveHandlerConfig = mock(StatArchiveHandlerConfig.class, getClass().getSimpleName() + "$" + StatArchiveHandlerConfig.class.getSimpleName());
+ when(mockStatArchiveHandlerConfig.getArchiveFileName()).thenReturn(new File(""));
+ when(mockStatArchiveHandlerConfig.getArchiveFileSizeLimit()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getArchiveDiskSpaceLimit()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getSystemId()).thenReturn(0L);
+ when(mockStatArchiveHandlerConfig.getSystemStartTime()).thenReturn(startTime);
+ when(mockStatArchiveHandlerConfig.getSystemDirectoryPath()).thenReturn("");
+ when(mockStatArchiveHandlerConfig.getProductDescription()).thenReturn(getClass().getSimpleName());
+
+ final StatisticsSampler sampler = new TestStatisticsSampler(manager);
+ this.sampleCollector = new SampleCollector(sampler);
+ this.sampleCollector.initialize(mockStatArchiveHandlerConfig, NanoTimer.getTime());
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ if (this.sampleCollector != null) {
+ this.sampleCollector.close();
+ this.sampleCollector = null;
+ }
+ this.manager = null;
+ }
+
+ @Test
+ public void testAddHandlerBeforeSample() {
+ TestSampleHandler handler = new TestSampleHandler();
+ this.sampleCollector.addSampleHandler(handler);
+
+ StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createIntCounter("ST1_1_name", "ST1_1_desc", "ST1_1_units")
+ };
+ StatisticsType ST1 = manager.createType("ST1_name", "ST1_desc", statsST1);
+ Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1_text", 1);
+
+ this.sampleCollector.sample(NanoTimer.getTime());
+
+ assertEquals(3, handler.getNotificationCount());
+ List<Info> notifications = handler.getNotifications();
+
+ // validate the allocatedResourceType notification
+ assertTrue(notifications.get(0) instanceof ResourceTypeInfo);
+ ResourceTypeInfo allocatedResourceTypeInfo = (ResourceTypeInfo) notifications.get(0);
+ assertNotNull(allocatedResourceTypeInfo);
+ assertEquals("allocatedResourceType", allocatedResourceTypeInfo.getName());
+ ResourceType resourceType = allocatedResourceTypeInfo.getResourceType();
+ assertNotNull(resourceType);
+ assertEquals(0, resourceType.getId());
+ assertEquals(1, resourceType.getStatisticDescriptors().length);
+ StatisticsType statisticsType = resourceType.getStatisticsType();
+ assertNotNull(statisticsType);
+ assertTrue(statisticsType == ST1);
+ assertEquals("ST1_name", statisticsType.getName());
+ assertEquals("ST1_desc", statisticsType.getDescription());
+ assertEquals(1, statisticsType.getStatistics().length);
+
+ // validate the allocatedResourceInstance notification
+ assertTrue(notifications.get(1) instanceof ResourceInstanceInfo);
+ ResourceInstanceInfo allocatedResourceInstanceInfo = (ResourceInstanceInfo) notifications.get(1);
+ assertNotNull(allocatedResourceInstanceInfo);
+ assertEquals("allocatedResourceInstance", allocatedResourceInstanceInfo.getName());
+ ResourceInstance resourceInstance = allocatedResourceInstanceInfo.getResourceInstance();
+ assertNotNull(resourceInstance);
+ assertEquals(0, resourceInstance.getId());
+ assertEquals(1, resourceInstance.getUpdatedStats().length);
+ assertEquals(1, resourceInstance.getLatestStatValues().length); // TODO: is this correct?
+ Statistics statistics = resourceInstance.getStatistics();
+ assertNotNull(statistics);
+ assertTrue(statistics == st1_1);
+ assertEquals(1, statistics.getUniqueId());
+ assertEquals(1, statistics.getNumericId());
+ assertEquals("st1_1_text", statistics.getTextId());
+ assertEquals("ST1_name", statistics.getType().getName());
+ assertTrue(resourceType == resourceInstance.getResourceType());
+
+ // validate the sampled notification
+ assertTrue(notifications.get(2) instanceof SampledInfo);
+ SampledInfo sampledInfo = (SampledInfo) notifications.get(2);
+ assertNotNull(sampledInfo);
+ assertEquals("sampled", sampledInfo.getName());
+ assertEquals(1, sampledInfo.getResourceCount());
+ }
+
+ @Test
+ public void testAddHandlerAfterSamples() {
+ StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ manager.createIntCounter("ST1_1_name", "ST1_1_desc", "ST1_1_units")
+ };
+ StatisticsType ST1 = manager.createType("ST1_name", "ST1_desc", statsST1);
+ Statistics st1_1 = manager.createAtomicStatistics(ST1, "st1_1_text", 1);
+ Statistics st1_2 = manager.createAtomicStatistics(ST1, "st1_2_text", 1);
+
+ StatisticDescriptor[] statsST2 = new StatisticDescriptor[] {
+ manager.createIntCounter("ST2_1_name", "ST2_1_desc", "ST2_1_units")
+ };
+ StatisticsType ST2 = manager.createType("ST2_name", "ST2_desc", statsST2);
+ Statistics st2_1 = manager.createAtomicStatistics(ST2, "st2_1_text", 1);
+
+ st1_1.incInt("ST1_1_name", 1);
+ st1_2.incInt("ST1_1_name", 1);
+ st2_1.incInt("ST2_1_name", 1);
+ long sampleTime = NanoTimer.getTime();
+ this.sampleCollector.sample(sampleTime);
+
+ st1_1.incInt("ST1_1_name", 2);
+ st2_1.incInt("ST2_1_name", 1);
+ sampleTime += NanoTimer.millisToNanos(1000);
+ this.sampleCollector.sample(sampleTime);
+
+ st1_1.incInt("ST1_1_name", 1);
+ st1_1.incInt("ST1_1_name", 2);
+ sampleTime += NanoTimer.millisToNanos(1000);
+ this.sampleCollector.sample(sampleTime);
+
+ TestSampleHandler handler = new TestSampleHandler();
+ this.sampleCollector.addSampleHandler(handler);
+
+ assertEquals("TestSampleHandler = " + handler, 0, handler.getNotificationCount());
+
+ st1_2.incInt("ST1_1_name", 1);
+ st2_1.incInt("ST2_1_name", 1);
+ sampleTime += NanoTimer.millisToNanos(1000);
+ this.sampleCollector.sample(sampleTime);
+
+ assertEquals(6, handler.getNotificationCount());
+ List<Info> notifications = handler.getNotifications();
+
+ // validate the allocatedResourceType notification for ST1
+ int notificationIdx = 0;
+ assertTrue(notifications.get(notificationIdx) instanceof ResourceTypeInfo);
+ ResourceTypeInfo allocatedResourceTypeInfo = (ResourceTypeInfo) notifications.get(notificationIdx);
+ assertNotNull(allocatedResourceTypeInfo);
+ assertEquals("allocatedResourceType", allocatedResourceTypeInfo.getName());
+ ResourceType resourceType = allocatedResourceTypeInfo.getResourceType();
+ assertNotNull(resourceType);
+ assertEquals(0, resourceType.getId());
+ assertEquals(1, resourceType.getStatisticDescriptors().length);
+ StatisticsType statisticsType = resourceType.getStatisticsType();
+ assertNotNull(statisticsType);
+ assertTrue(statisticsType == ST1);
+ assertEquals("ST1_name", statisticsType.getName());
+ assertEquals("ST1_desc", statisticsType.getDescription());
+ assertEquals(1, statisticsType.getStatistics().length);
+
+ // validate the allocatedResourceInstance notification for st1_1
+ notificationIdx++;
+ assertTrue(notifications.get(notificationIdx) instanceof ResourceInstanceInfo);
+ ResourceInstanceInfo allocatedResourceInstanceInfo = (ResourceInstanceInfo) notifications.get(notificationIdx);
+ assertNotNull(allocatedResourceInstanceInfo);
+ assertEquals("allocatedResourceInstance", allocatedResourceInstanceInfo.getName());
+ ResourceInstance resourceInstance = allocatedResourceInstanceInfo.getResourceInstance();
+ assertNotNull(resourceInstance);
+ assertEquals(0, resourceInstance.getId());
+ assertEquals(0, resourceInstance.getUpdatedStats().length);
+ assertEquals(1, resourceInstance.getLatestStatValues().length); // TODO: is this correct?
+ Statistics statistics = resourceInstance.getStatistics();
+ assertNotNull(statistics);
+ assertTrue(statistics == st1_1);
+ assertEquals(1, statistics.getUniqueId());
+ assertEquals(1, statistics.getNumericId());
+ assertEquals("st1_1_text", statistics.getTextId());
+ assertEquals("ST1_name", statistics.getType().getName());
+ assertTrue(resourceType == resourceInstance.getResourceType());
+
+ // validate the allocatedResourceInstance notification for st1_2
+ notificationIdx++;
+ assertTrue(notifications.get(notificationIdx) instanceof ResourceInstanceInfo);
+ allocatedResourceInstanceInfo = (ResourceInstanceInfo) notifications.get(notificationIdx);
+ assertNotNull(allocatedResourceInstanceInfo);
+ assertEquals("allocatedResourceInstance", allocatedResourceInstanceInfo.getName());
+ resourceInstance = allocatedResourceInstanceInfo.getResourceInstance();
+ assertNotNull(resourceInstance);
+ assertEquals(1, resourceInstance.getId());
+ assertEquals(1, resourceInstance.getUpdatedStats().length);
+ assertEquals(1, resourceInstance.getLatestStatValues().length); // TODO: is this correct?
+ statistics = resourceInstance.getStatistics();
+ assertNotNull(statistics);
+ assertTrue(statistics == st1_2);
+ assertEquals(2, statistics.getUniqueId());
+ assertEquals(1, statistics.getNumericId());
+ assertEquals("st1_2_text", statistics.getTextId());
+ assertEquals("ST1_name", statistics.getType().getName());
+ assertTrue(resourceType == resourceInstance.getResourceType());
+
+ // validate the allocatedResourceType notification for ST2
+ notificationIdx++;
+ assertTrue(notifications.get(notificationIdx) instanceof ResourceTypeInfo);
+ allocatedResourceTypeInfo = (ResourceTypeInfo) notifications.get(notificationIdx);
+ assertNotNull(allocatedResourceTypeInfo);
+ assertEquals("allocatedResourceType", allocatedResourceTypeInfo.getName());
+ resourceType = allocatedResourceTypeInfo.getResourceType();
+ assertNotNull(resourceType);
+ assertEquals(1, resourceType.getId());
+ assertEquals(1, resourceType.getStatisticDescriptors().length);
+ statisticsType = resourceType.getStatisticsType();
+ assertNotNull(statisticsType);
+ assertTrue(statisticsType == ST2);
+ assertEquals("ST2_name", statisticsType.getName());
+ assertEquals("ST2_desc", statisticsType.getDescription());
+ assertEquals(1, statisticsType.getStatistics().length);
+
+ // validate the allocatedResourceInstance notification for st2_1
+ notificationIdx++;
+ assertTrue(notifications.get(notificationIdx) instanceof ResourceInstanceInfo);
+ allocatedResourceInstanceInfo = (ResourceInstanceInfo) notifications.get(notificationIdx);
+ assertNotNull(allocatedResourceInstanceInfo);
+ assertEquals("allocatedResourceInstance", allocatedResourceInstanceInfo.getName());
+ resourceInstance = allocatedResourceInstanceInfo.getResourceInstance();
+ assertNotNull(resourceInstance);
+ assertEquals(2, resourceInstance.getId());
+ assertEquals(1, resourceInstance.getUpdatedStats().length);
+ assertEquals(1, resourceInstance.getLatestStatValues().length); // TODO: is this correct?
+ statistics = resourceInstance.getStatistics();
+ assertNotNull(statistics);
+ assertTrue(statistics == st2_1);
+ assertEquals(3, statistics.getUniqueId());
+ assertEquals(1, statistics.getNumericId());
+ assertEquals("st2_1_text", statistics.getTextId());
+ assertEquals("ST2_name", statistics.getType().getName());
+ assertTrue(resourceType == resourceInstance.getResourceType());
+
+ // validate the sampled notification
+ notificationIdx++;
+ assertTrue(notifications.get(notificationIdx) instanceof SampledInfo);
+ SampledInfo sampledInfo = (SampledInfo) notifications.get(notificationIdx);
+ assertNotNull(sampledInfo);
+ assertEquals("sampled", sampledInfo.getName());
+ assertEquals(3, sampledInfo.getResourceCount());
+ }
+
+ @Test
+ public void testGetStatMonitorHandler() {
+ StatMonitorHandler handler = SampleCollector.getStatMonitorHandler();
+ assertNotNull(handler);
+ assertTrue(handler.getMonitorsSnapshot().isEmpty());
+ assertNull(handler.getStatMonitorNotifier());
+ }
+
+ @Test
+ public void testGetStatMonitorHandlerAfterClose() {
+ this.sampleCollector.close();
+ try {
+ /*StatMonitorHandler handler =*/ SampleCollector.getStatMonitorHandler();
+ fail("getStatMonitorHandler should throw IllegalStateException when SampleCollector is closed");
+ } catch (IllegalStateException expected) {
+ // passed
+ }
+ }
+
+ @Test
+ public void testGetStatMonitorHandlerBeforeAndAfterClose() {
+ StatMonitorHandler handler = SampleCollector.getStatMonitorHandler();
+ assertNotNull(handler);
+ this.sampleCollector.close();
+ try {
+ handler = SampleCollector.getStatMonitorHandler();
+ fail("getStatMonitorHandler should throw IllegalStateException when SampleCollector is closed");
+ } catch (IllegalStateException expected) {
+ // passed
+ }
+ }
+
+ @Test
+ public void testGetStatArchiveHandler() {
+ StatArchiveHandler handler = this.sampleCollector.getStatArchiveHandler();
+ assertNotNull(handler);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SimpleStatSamplerIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SimpleStatSamplerIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SimpleStatSamplerIntegrationTest.java
new file mode 100755
index 0000000..d86b968
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/SimpleStatSamplerIntegrationTest.java
@@ -0,0 +1,351 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.lang.reflect.Method;
+import java.util.List;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.CancelCriterion;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.SocketCreator;
+import com.gemstone.gemfire.internal.stats50.VMStats50;
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+
+/**
+ * Integration tests for {@link SimpleStatSampler}.
+ *
+ * @since GemFire 7.0
+ */
+@Category(IntegrationTest.class)
+public class SimpleStatSamplerIntegrationTest extends StatSamplerTestCase {
+
+ private LocalStatisticsFactory statisticsFactory;
+ private File testDir;
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUp() throws Exception {
+ this.testDir = this.temporaryFolder.getRoot();
+ assertTrue(this.testDir.exists());
+ System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY,
+ this.testDir.getAbsolutePath() + File.separator + SimpleStatSampler.DEFAULT_ARCHIVE_FILE_NAME);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ System.clearProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY);
+ System.clearProperty(SimpleStatSampler.FILE_SIZE_LIMIT_PROPERTY);
+ System.clearProperty(SimpleStatSampler.DISK_SPACE_LIMIT_PROPERTY);
+ System.clearProperty(SimpleStatSampler.SAMPLE_RATE_PROPERTY);
+ closeStatisticsFactory();
+ }
+
+ /**
+ * Tests the majority of getters and the basic functionality of the sampler.
+ */
+ @Test
+ public void testBasics() throws Exception {
+ initStatisticsFactory();
+
+ SimpleStatSampler statSampler = getSimpleStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ assertEquals(new File(System.getProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY)),
+ statSampler.getArchiveFileName());
+ assertEquals(0, statSampler.getArchiveFileSizeLimit());
+ assertEquals(0, statSampler.getArchiveDiskSpaceLimit());
+ assertEquals(SimpleStatSampler.DEFAULT_SAMPLE_RATE, statSampler.getSampleRate());
+ assertEquals(true, statSampler.isSamplingEnabled());
+
+ int statsCount = statSampler.getStatisticsManager().getStatisticsCount();
+
+ assertEquals(statsCount, statSampler.getStatisticsModCount());
+ assertEquals(statsCount, statSampler.getStatisticsManager().getStatisticsCount());
+ assertEquals(statsCount, statSampler.getStatistics().length);
+
+ assertTrue(statsCount > 0);
+
+ Assert.assertEquals(getStatisticsManager().getId(), statSampler.getSystemId());
+ assertTrue(statSampler.getSystemStartTime() <= System.currentTimeMillis());
+ Assert.assertEquals(SocketCreator.getHostName(SocketCreator.getLocalHost()),
+ statSampler.getSystemDirectoryPath());
+
+ VMStatsContract vmStats = statSampler.getVMStats();
+ assertNotNull(vmStats);
+ assertTrue(vmStats instanceof VMStats50);
+ /* NOTE: VMStats50 is not an instance of Statistics but instead its
+ * instance contains 3 instances of Statistics:
+ * 1) vmStats
+ * 2) heapMemStats
+ * 3) nonHeapMemStats
+ */
+
+ Method getProcessStats = null;
+ try {
+ getProcessStats = SimpleStatSampler.class.getMethod("getProcessStats");
+ fail("SimpleStatSampler should not have the method getProcessStats()");
+ } catch (NoSuchMethodException exected) {
+ // passed
+ }
+ assertNull(getProcessStats);
+
+ assertEquals("Unknown product", statSampler.getProductDescription());
+ }
+
+ /**
+ * Tests that the configured archive file is created and exists.
+ */
+ @Test
+ public void testArchiveFileExists() throws Exception {
+ final String dir = this.testDir.getAbsolutePath();
+ final String archiveFileName = dir + File.separator + this.testName + ".gfs";
+ final File archiveFile1 = new File(dir + File.separator + this.testName + ".gfs");
+ System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY, archiveFileName);
+ initStatisticsFactory();
+
+ SimpleStatSampler statSampler = getSimpleStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ final File archiveFile = statSampler.getArchiveFileName();
+ assertNotNull(archiveFile);
+ assertEquals(archiveFile1, archiveFile);
+
+ waitForFileToExist(archiveFile, 5000, 10);
+
+ assertTrue("File name incorrect: archiveFile.getName()=" + archiveFile.getName() +
+ " archiveFile.getAbsolutePath()=" + archiveFile.getAbsolutePath() +
+ " getCanonicalPath()" + archiveFile.getCanonicalPath(),
+ archiveFileName.contains(archiveFile.getName()));
+ }
+
+ /**
+ * Tests the statistics sample rate within an acceptable margin of error.
+ */
+ @Test
+ public void testSampleRate() throws Exception {
+ initStatisticsFactory();
+
+ SimpleStatSampler statSampler = getSimpleStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ assertEquals(SimpleStatSampler.DEFAULT_SAMPLE_RATE, statSampler.getSampleRate());
+
+ assertTrue(getStatisticsManager().getStatListModCount() > 0);
+
+ List<Statistics> statistics = getStatisticsManager().getStatsList();
+ assertNotNull(statistics);
+ assertTrue(statistics.size() > 0);
+
+ StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
+ Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
+ assertEquals(1, statsArray.length);
+
+ final Statistics statSamplerStats = statsArray[0];
+ final int initialSampleCount = statSamplerStats.getInt("sampleCount");
+ final int expectedSampleCount = initialSampleCount + 2;
+
+ waitForStatSample(statSamplerStats, expectedSampleCount, 20000, 10);
+ }
+
+ /**
+ * Tests lack of methods for supporting LocalStatListener.
+ */
+ @Test
+ public void testLocalStatListener() throws Exception {
+ initStatisticsFactory();
+
+ SimpleStatSampler statSampler = getSimpleStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ Method getLocalListeners = null;
+ try {
+ getLocalListeners = getSimpleStatSampler().getClass().getMethod("getLocalListeners");
+ fail("SimpleStatSampler should not have the method getLocalListeners()");
+ } catch (NoSuchMethodException exected) {
+ // passed
+ }
+ assertNull(getLocalListeners);
+
+ Method addLocalStatListener = null;
+ try {
+ addLocalStatListener = getSimpleStatSampler().getClass().getMethod("addLocalStatListener", LocalStatListener.class, Statistics.class, String.class);
+ fail("SimpleStatSampler should not have the method addLocalStatListener()");
+ } catch (NoSuchMethodException exected) {
+ // passed
+ }
+ assertNull(addLocalStatListener);
+
+ Method removeLocalStatListener = null;
+ try {
+ removeLocalStatListener = getSimpleStatSampler().getClass().getMethod("removeLocalStatListener", LocalStatListener.class);
+ fail("SimpleStatSampler should not have the method addLocalStatListener()");
+ } catch (NoSuchMethodException exected) {
+ // passed
+ }
+ assertNull(removeLocalStatListener);
+ }
+
+ /**
+ * Invokes stop() and then validates that the sampler did in fact stop.
+ */
+ @Test
+ public void testStop() throws Exception {
+ initStatisticsFactory();
+
+ SimpleStatSampler statSampler = getSimpleStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ // validate the stat sampler is running
+ StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
+ Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
+ assertEquals(1, statsArray.length);
+
+ final Statistics statSamplerStats = statsArray[0];
+ final int initialSampleCount = statSamplerStats.getInt("sampleCount");
+ final int expectedSampleCount = initialSampleCount + 2;
+
+ waitForStatSample(statSamplerStats, expectedSampleCount, 20000, 10);
+
+ // stop the stat sampler
+ statSampler.stop();
+
+ // validate the stat sampler has stopped
+ final int stoppedSampleCount = statSamplerStats.getInt("sampleCount");
+
+ // the following should timeout without completing
+ assertStatValueDoesNotChange(statSamplerStats, "sampleCount", stoppedSampleCount, 5000, 10);
+
+ assertEquals(stoppedSampleCount, statSamplerStats.getInt("sampleCount"));
+ }
+
+ /**
+ * Verifies that archive rolling works correctly when archive-file-size-limit
+ * is specified. This feature is broken in SimpleStatSampler.
+ */
+ @Test
+ public void testArchiveRolling() throws Exception {
+ // set the system property to use KB instead of MB for file size
+ System.setProperty(HostStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY, "true");
+
+ final String dir = this.testDir.getAbsolutePath() + File.separator + this.testName;
+ new File(dir).mkdir();
+
+ final String archiveFileName = dir + File.separator + this.testName + ".gfs";
+ System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY, archiveFileName);
+ System.setProperty(SimpleStatSampler.FILE_SIZE_LIMIT_PROPERTY, "1");
+ System.setProperty(SimpleStatSampler.DISK_SPACE_LIMIT_PROPERTY, "0");
+ System.setProperty(SimpleStatSampler.SAMPLE_RATE_PROPERTY, "1000");
+ initStatisticsFactory();
+
+ final File archiveFile1 = new File(dir + File.separator + this.testName + "-01-01.gfs");
+ final File archiveFile2 = new File(dir + File.separator + this.testName + "-01-02.gfs");
+ final File archiveFile3 = new File(dir + File.separator + this.testName + "-01-03.gfs");
+ final File archiveFile4 = new File(dir + File.separator + this.testName + "-01-04.gfs");
+
+ assertTrue(getSimpleStatSampler().waitForInitialization(5000));
+
+ assertTrue(getSimpleStatSampler().fileSizeLimitInKB());
+ assertEquals(1024, getSimpleStatSampler().getArchiveFileSizeLimit());
+
+ waitForFileToExist(archiveFile1, 4000, 10);
+ waitForFileToExist(archiveFile2, 4000, 10);
+ waitForFileToExist(archiveFile3, 4000, 10);
+ waitForFileToExist(archiveFile4, 4000, 10);
+ }
+
+ /**
+ * Verifies that archive removal works correctly when archive-disk-space-limit
+ * is specified. This feature is broken in SimpleStatSampler.
+ */
+ @Test
+ public void testArchiveRemoval() throws Exception {
+ // set the system property to use KB instead of MB for file size
+ System.setProperty(HostStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY, "true");
+
+ final String dir = this.testDir.getAbsolutePath() + File.separator + this.testName;
+ new File(dir).mkdir();
+
+ final String archiveFileName = dir + File.separator + this.testName + ".gfs";
+ final int sampleRate = 1000;
+ System.setProperty(SimpleStatSampler.ARCHIVE_FILE_NAME_PROPERTY, archiveFileName);
+ System.setProperty(SimpleStatSampler.FILE_SIZE_LIMIT_PROPERTY, "1");
+ System.setProperty(SimpleStatSampler.DISK_SPACE_LIMIT_PROPERTY, "12");
+ System.setProperty(SimpleStatSampler.SAMPLE_RATE_PROPERTY, String.valueOf(sampleRate));
+ initStatisticsFactory();
+
+ final File archiveFile1 = new File(dir + File.separator + this.testName + "-01-01.gfs");
+ final File archiveFile2 = new File(dir + File.separator + this.testName + "-01-02.gfs");
+ final File archiveFile3 = new File(dir + File.separator + this.testName + "-01-03.gfs");
+ final File archiveFile4 = new File(dir + File.separator + this.testName + "-01-04.gfs");
+ final File archiveFile5 = new File(dir + File.separator + this.testName + "-01-05.gfs");
+
+ assertTrue(getSimpleStatSampler().waitForInitialization(5000));
+
+ waitForFileToExist(archiveFile1, 4*sampleRate, 10);
+ waitForFileToExist(archiveFile2, 4*sampleRate, 10);
+ waitForFileToExist(archiveFile3, 4*sampleRate, 10);
+ waitForFileToExist(archiveFile4, 4*sampleRate, 10);
+ waitForFileToExist(archiveFile5, 4*sampleRate, 10);
+ waitForFileToDelete(archiveFile1, 10*sampleRate, 10);
+ }
+
+ @Override
+ protected StatisticsManager getStatisticsManager() {
+ return this.statisticsFactory;
+ }
+
+ private SimpleStatSampler getSimpleStatSampler() {
+ return this.statisticsFactory.getStatSampler();
+ }
+
+ private void initStatisticsFactory() {
+ CancelCriterion stopper = new CancelCriterion() {
+ public String cancelInProgress() {
+ return null;
+ }
+ public RuntimeException generateCancelledException(Throwable e) {
+ return null;
+ }
+ };
+ this.statisticsFactory = new LocalStatisticsFactory(stopper);
+ }
+
+ private void closeStatisticsFactory() {
+ if (this.statisticsFactory != null) {
+ this.statisticsFactory.close();
+ this.statisticsFactory = null;
+ }
+ }
+}
[11/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeImpl.java
new file mode 100644
index 0000000..a338dfb
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeImpl.java
@@ -0,0 +1,258 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * Gathers together a number of {@link StatisticDescriptor statistics}
+ * into one logical type.
+ *
+ * @see Statistics
+ *
+ *
+ * @since GemFire 3.0
+ */
+public class StatisticsTypeImpl implements StatisticsType {
+
+ /** The name of this statistics type */
+ private final String name;
+
+ /** The description of this statistics type */
+ private final String description;
+
+ /** The descriptions of the statistics in id order */
+ private final StatisticDescriptor[] stats;
+
+ /** Maps a stat name to its StatisticDescriptor */
+ private final HashMap statsMap;
+
+ /** Contains the number of 32-bit statistics in this type. */
+ private final int intStatCount;
+
+ /** Contains the number of long statistics in this type. */
+ private final int longStatCount;
+
+ /** Contains the number of double statistics in this type. */
+ private final int doubleStatCount;
+
+ ///////////////////// Static Methods /////////////////////
+
+ /**
+ * @see StatisticsTypeXml#read(Reader, StatisticsTypeFactory)
+ */
+ public static StatisticsType[] fromXml(Reader reader,
+ StatisticsTypeFactory factory)
+ throws IOException {
+ return (new StatisticsTypeXml()).read(reader, factory);
+ }
+
+ ////////////////////// Constructors //////////////////////
+
+ /**
+ * Creates a new <code>StatisticsType</code> with the given name,
+ * description, and statistics.
+ *
+ * @param name
+ * The name of this statistics type (for example,
+ * <code>"DatabaseStatistics"</code>)
+ * @param description
+ * A description of this statistics type (for example,
+ * "Information about the application's use of the
+ * database").
+ * @param stats
+ * Descriptions of the individual statistics grouped together
+ * in this statistics type.
+ *
+ * @throws NullPointerException
+ * If either <code>name</code> or <code>stats</code> is
+ * <code>null</code>.
+ */
+ public StatisticsTypeImpl(String name, String description,
+ StatisticDescriptor[] stats) {
+ this(name, description, stats, false);
+ }
+
+ /**
+ * Creates a new <code>StatisticsType</code> with the given name,
+ * description, and statistics.
+ *
+ * @param name
+ * The name of this statistics type (for example,
+ * <code>"DatabaseStatistics"</code>)
+ * @param description
+ * A description of this statistics type (for example,
+ * "Information about the application's use of the
+ * database").
+ * @param stats
+ * Descriptions of the individual statistics grouped together
+ * in this statistics type.
+ * @param wrapsSharedClass
+ * True if this type is a wrapper around a SharedClass??.
+ * False if its a dynamic type created at run time.
+ *
+ * @throws NullPointerException
+ * If either <code>name</code> or <code>stats</code> is
+ * <code>null</code>.
+ */
+ public StatisticsTypeImpl(String name, String description,
+ StatisticDescriptor[] stats, boolean wrapsSharedClass) {
+ if (name == null) {
+ throw new NullPointerException(LocalizedStrings.StatisticsTypeImpl_CANNOT_HAVE_A_NULL_STATISTICS_TYPE_NAME.toLocalizedString());
+ }
+
+ if (stats == null) {
+ throw new NullPointerException(LocalizedStrings.StatisticsTypeImpl_CANNOT_HAVE_A_NULL_STATISTIC_DESCRIPTORS.toLocalizedString());
+ }
+ if (stats.length > StatisticsTypeFactory.MAX_DESCRIPTORS_PER_TYPE) {
+ throw new IllegalArgumentException(LocalizedStrings.StatisticsTypeImpl_THE_REQUESTED_DESCRIPTOR_COUNT_0_EXCEEDS_THE_MAXIMUM_WHICH_IS_1.toLocalizedString(new Object[] {Integer.valueOf(stats.length), Integer.valueOf(StatisticsTypeFactory.MAX_DESCRIPTORS_PER_TYPE)}));
+ }
+
+ this.name = name;
+ this.description = description;
+ this.stats = stats;
+ this.statsMap = new HashMap(stats.length*2);
+ int intCount = 0;
+ int longCount = 0;
+ int doubleCount = 0;
+ for (int i=0; i < stats.length; i++) {
+ StatisticDescriptorImpl sd = (StatisticDescriptorImpl)stats[i];
+ if (sd.getTypeCode() == StatisticDescriptorImpl.INT) {
+ if (!wrapsSharedClass) {
+ sd.setId(intCount);
+ }
+ intCount++;
+ } else if (sd.getTypeCode() == StatisticDescriptorImpl.LONG) {
+ if (!wrapsSharedClass) {
+ sd.setId(longCount);
+ }
+ longCount++;
+ } else if (sd.getTypeCode() == StatisticDescriptorImpl.DOUBLE) {
+ if (!wrapsSharedClass) {
+ sd.setId(doubleCount);
+ }
+ doubleCount++;
+ }
+ Object previousValue = statsMap.put(stats[i].getName(), sd);
+ if (previousValue != null) {
+ throw new IllegalArgumentException(LocalizedStrings.StatisticsTypeImpl_DUPLICATE_STATISTICDESCRIPTOR_NAMED_0.toLocalizedString(stats[i].getName()));
+ }
+ }
+ this.intStatCount = intCount;
+ this.longStatCount = longCount;
+ this.doubleStatCount = doubleCount;
+ }
+
+ ////////////////////// StatisticsType Methods //////////////////////
+
+ public final String getName() {
+ return this.name;
+ }
+
+ public final String getDescription() {
+ return this.description;
+ }
+
+ public final StatisticDescriptor[] getStatistics() {
+ return this.stats;
+ }
+
+ public final int nameToId(String name) {
+ return nameToDescriptor(name).getId();
+ }
+
+ public final StatisticDescriptor nameToDescriptor(String name) {
+ StatisticDescriptorImpl stat = (StatisticDescriptorImpl)statsMap.get(name);
+ if (stat == null) {
+ throw new IllegalArgumentException(LocalizedStrings.StatisticsTypeImpl_THERE_IS_NO_STATISTIC_NAMED_0.toLocalizedString(name));
+ }
+ return stat;
+ }
+
+ ////////////////////// Instance Methods //////////////////////
+
+ /**
+ * Gets the number of statistics in this type that are ints.
+ */
+ public int getIntStatCount() {
+ return this.intStatCount;
+ }
+ /**
+ * Gets the number of statistics in this type that are longs.
+ */
+ public int getLongStatCount() {
+ return this.longStatCount;
+ }
+ /**
+ * Gets the number of statistics that are doubles.
+ */
+ public int getDoubleStatCount() {
+ return this.doubleStatCount;
+ }
+
+// @Override
+// public String toString() {
+// return "StatisticType with " + this.stats.length + " stats";
+// }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder(getClass().getName());
+ sb.append("@").append(System.identityHashCode(this)).append("{");
+ sb.append("name=").append(this.name);
+ sb.append(", description=").append(this.description);
+ sb.append(", stats.length=").append(this.stats.length);
+ sb.append("}");
+ return sb.toString();
+ }
+
+ @Override
+ public int hashCode() {
+ return getName().hashCode();
+ }
+ @Override
+ public boolean equals(Object o) {
+ if (o == null) {
+ return false;
+ }
+ if (!(o instanceof StatisticsType)) {
+ return false;
+ }
+ StatisticsType other = (StatisticsType)o;
+ if (!getName().equals(other.getName())) {
+ return false;
+ }
+ if (!getDescription().equals(other.getDescription())) {
+ return false;
+ }
+ StatisticDescriptor[] myStats = getStatistics();
+ StatisticDescriptor[] yourStats = other.getStatistics();
+ if (myStats.length != yourStats.length) {
+ return false;
+ }
+ for (int i=0; i < myStats.length; i++) {
+ if (!myStats[i].equals(yourStats[i])) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeXml.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeXml.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeXml.java
new file mode 100644
index 0000000..3fa1796
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeXml.java
@@ -0,0 +1,282 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.ClassPathLoader;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+
+import java.io.*;
+import java.util.*;
+import javax.xml.parsers.*;
+//import javax.xml.transform.*;
+//import javax.xml.transform.dom.*;
+//import javax.xml.transform.stream.*;
+import org.w3c.dom.*;
+import org.xml.sax.*;
+
+// @todo davidw Use a SAX parser instead of DOM
+/**
+ * This is an internal helper class for dealing with the
+ * SessionFactory XML configuration files.
+ */
+public class StatisticsTypeXml
+ implements EntityResolver, ErrorHandler {
+
+ /** The name of the DTD file */
+ static final String DTD = "statisticsType.dtd";
+
+ static final String systemId = "http://www.gemstone.com/dtd/" + DTD;
+ static final String publicId =
+ "-//GemStone Systems, Inc.//GemFire StatisticsType//EN";
+
+ ///////////////////// Interface methods ///////////////////////
+
+ /**
+ * Given a publicId, attempts to resolve it to a DTD. Returns an
+ * <code>InputSource</code> for the DTD.
+ */
+ public InputSource resolveEntity (String publicId, String systemId)
+ throws SAXException {
+
+ // Figure out the location for the publicId. Be tolerant of other
+ // versions of the dtd
+ if(publicId.equals(StatisticsTypeXml.publicId) ||
+ systemId.equals(StatisticsTypeXml.systemId) ||
+ systemId.endsWith(DTD)) {
+
+ // Public ID for system config DTD
+ String location = "/com/gemstone/gemfire/" + DTD;
+ InputStream stream = ClassPathLoader.getLatest().getResourceAsStream(getClass(), location);
+ if (stream != null) {
+ return new InputSource(stream);
+
+ } else {
+ throw new SAXNotRecognizedException(LocalizedStrings.StatisticsTypeXml_DTD_NOT_FOUND_0.toLocalizedString(location));
+ }
+
+ } else {
+ throw new SAXNotRecognizedException(LocalizedStrings.StatisticsTypeXml_INVALID_PUBLIC_ID_0.toLocalizedString(publicId));
+ }
+ }
+
+ public void warning(SAXParseException exception) throws SAXException
+ {
+ // We don't want to thrown an exception. We want to log it!!
+ // FIXME
+// String s = "SAX warning while working with XML";
+ }
+
+ public void error(SAXParseException exception) throws SAXException
+ {
+ throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_SAX_ERROR_WHILE_WORKING_WITH_XML.toLocalizedString(), exception);
+ }
+
+ public void fatalError(SAXParseException exception) throws SAXException
+ {
+ throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_SAX_FATAL_ERROR_WHILE_WORKING_WITH_XML.toLocalizedString(), exception);
+ }
+
+ ////////////////////// Parsing XML File ////////////////////////
+
+ /**
+ * Parses the contents of XML data and from it creates one or more
+ * <code>StatisticsType</code> instances.
+ */
+ public StatisticsType[] read( Reader reader, StatisticsTypeFactory statFactory) {
+ DocumentBuilderFactory factory =
+ DocumentBuilderFactory.newInstance();
+// factory.setValidating(validate);
+
+ DocumentBuilder parser = null;
+ try {
+ parser = factory.newDocumentBuilder();
+
+ } catch (ParserConfigurationException ex) {
+ throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_PARSING_XML.toLocalizedString(), ex);
+ }
+
+ parser.setErrorHandler(this);
+ parser.setEntityResolver(this);
+ Document doc;
+ try {
+ doc = parser.parse(new InputSource(reader));
+ } catch (SAXException se) {
+ throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_PARSING_XML.toLocalizedString(), se);
+ } catch (IOException io) {
+ throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_READING_XML_DATA.toLocalizedString(), io);
+ }
+
+ if (doc == null) {
+ throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_READING_XML_DATA_NO_DOCUMENT.toLocalizedString());
+ }
+ Element root = doc.getDocumentElement();
+ if (root == null) {
+ throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_READING_XML_DATA_NO_ROOT_ELEMENT.toLocalizedString());
+ }
+ return extractStatistics(root, statFactory);
+ }
+
+ /*
+ * <!ELEMENT statistics (type)+>
+ */
+ private StatisticsType[] extractStatistics(Element root, StatisticsTypeFactory statFactory) {
+ Assert.assertTrue(root.getTagName().equals("statistics"));
+
+ ArrayList types = new ArrayList();
+ NodeList typeNodes = root.getElementsByTagName("type");
+ for (int i = 0; i < typeNodes.getLength(); i++) {
+ Element typeNode = (Element) typeNodes.item(i);
+ types.add(extractType(typeNode, statFactory));
+ }
+ return (StatisticsType[])types.toArray(new StatisticsType[types.size()]);
+ }
+ /**
+ * <!ELEMENT type (description?, (stat)+)>
+ * <!ATTLIST type name CDATA #REQUIRED>
+ */
+ private StatisticsType extractType(Element typeNode, StatisticsTypeFactory statFactory) {
+ Assert.assertTrue(typeNode.getTagName().equals("type"));
+ Assert.assertTrue(typeNode.hasAttribute("name"));
+
+ final String typeName = typeNode.getAttribute("name");
+ ArrayList stats = new ArrayList();
+ NodeList statNodes = typeNode.getElementsByTagName("stat");
+ for (int i = 0; i < statNodes.getLength(); i++) {
+ Element statNode = (Element) statNodes.item(i);
+ stats.add(extractStat(statNode, statFactory));
+ }
+ StatisticDescriptor[] descriptors =
+ (StatisticDescriptor[])stats.toArray(new StatisticDescriptor[stats.size()]);
+ String description = "";
+ {
+ NodeList descriptionNodes = typeNode.getElementsByTagName("description");
+ if (descriptionNodes.getLength() > 0) {
+ // descriptionNodes will contain the both our description, if it exists,
+ // and any nested stat descriptions. Ours will always be first
+ Element descriptionNode = (Element) descriptionNodes.item(0);
+ // but make sure the first one belongs to our node
+ if (descriptionNode.getParentNode().getNodeName().equals(typeNode.getNodeName())) {
+ description = extractDescription(descriptionNode);
+ }
+ }
+ }
+
+ return statFactory.createType(typeName, description, descriptors);
+ }
+ private final static int INT_STORAGE = 0;
+ private final static int LONG_STORAGE = 1;
+ private final static int DOUBLE_STORAGE = 2;
+ /**
+ * <!ELEMENT stat (description?, unit?)>
+ * <!ATTLIST stat
+ * name CDATA #REQUIRED
+ * counter (true | false) #IMPLIED
+ * largerBetter (true | false) #IMPLIED
+ * storage (int | long | double) #IMPLIED
+ * >
+ */
+ private StatisticDescriptor extractStat(Element statNode, StatisticsTypeFactory statFactory) {
+ Assert.assertTrue(statNode.getTagName().equals("stat"));
+ Assert.assertTrue(statNode.hasAttribute("name"));
+
+ final String statName = statNode.getAttribute("name");
+ String description = "";
+ String unit = "";
+ boolean isCounter = true;
+ boolean largerBetter;
+ int storage = INT_STORAGE;
+
+ if ( statNode.hasAttribute("counter")) {
+ String value = statNode.getAttribute("counter");
+ Assert.assertTrue(value.equalsIgnoreCase("true") ||
+ value.equalsIgnoreCase("false"));
+ isCounter = Boolean.valueOf(value).booleanValue();
+ }
+ largerBetter = isCounter; // default
+ if ( statNode.hasAttribute("largerBetter")) {
+ String value = statNode.getAttribute("largerBetter");
+ Assert.assertTrue(value.equalsIgnoreCase("true") ||
+ value.equalsIgnoreCase("false"));
+ largerBetter = Boolean.valueOf(value).booleanValue();
+ }
+ if ( statNode.hasAttribute("storage")) {
+ String value = statNode.getAttribute("storage");
+ if (value.equalsIgnoreCase("int")) {
+ storage = INT_STORAGE;
+ } else if (value.equalsIgnoreCase("long")) {
+ storage = LONG_STORAGE;
+ } else {
+ Assert.assertTrue(value.equalsIgnoreCase("double"));
+ storage = DOUBLE_STORAGE;
+ }
+ }
+ {
+ NodeList descriptionNodes =
+ statNode.getElementsByTagName("description");
+ Assert.assertTrue(descriptionNodes.getLength() <= 1);
+ if (descriptionNodes.getLength() == 1) {
+ Element descriptionNode = (Element) descriptionNodes.item(0);
+ description = extractDescription(descriptionNode);
+ }
+ }
+
+ {
+ NodeList unitNodes =
+ statNode.getElementsByTagName("unit");
+ Assert.assertTrue(unitNodes.getLength() <= 1);
+ if (unitNodes.getLength() == 1) {
+ Element unitNode = (Element) unitNodes.item(0);
+ unit = extractUnit(unitNode);
+ }
+ }
+ if (isCounter) {
+ switch (storage) {
+ case INT_STORAGE: return statFactory.createIntCounter(statName, description, unit, largerBetter);
+ case LONG_STORAGE: return statFactory.createLongCounter(statName, description, unit, largerBetter);
+ case DOUBLE_STORAGE: return statFactory.createDoubleCounter(statName, description, unit, largerBetter);
+ default: throw new RuntimeException(LocalizedStrings.StatisticsTypeXml_UNEXPECTED_STORAGE_TYPE_0.toLocalizedString(Integer.valueOf(storage)));
+ }
+ } else {
+ switch (storage) {
+ case INT_STORAGE: return statFactory.createIntGauge(statName, description, unit, largerBetter);
+ case LONG_STORAGE: return statFactory.createLongGauge(statName, description, unit, largerBetter);
+ case DOUBLE_STORAGE: return statFactory.createDoubleGauge(statName, description, unit, largerBetter);
+ default: throw new RuntimeException(LocalizedStrings.StatisticsTypeXml_UNEXPECTED_STORAGE_TYPE_0.toLocalizedString(Integer.valueOf(storage)));
+ }
+ }
+ }
+ /**
+ * <!ELEMENT description (#PCDATA)>
+ */
+ private String extractDescription(Element descriptionNode) {
+ Assert.assertTrue(descriptionNode.getTagName().equals("description"));
+ return extractText(descriptionNode);
+ }
+ /**
+ * <!ELEMENT unit (#PCDATA)>
+ */
+ private String extractUnit(Element unitNode) {
+ Assert.assertTrue(unitNode.getTagName().equals("unit"));
+ return extractText(unitNode);
+ }
+ private String extractText(Element element) {
+ Text text = (Text) element.getFirstChild();
+ return((text == null ? "" : text.getData()));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStats.java
new file mode 100644
index 0000000..8f441f5
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStats.java
@@ -0,0 +1,87 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+
+/**
+ * Statistics related to a Java VM. Currently they all come from
+ * {@link java.lang.Runtime}.
+ */
+public class VMStats implements VMStatsContract {
+ private final static StatisticsType vmType;
+ private final static int cpusId;
+ private final static int freeMemoryId;
+ private final static int totalMemoryId;
+ private final static int maxMemoryId;
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ vmType = f.createType("VMStats",
+ "Stats available on any java virtual machine.",
+ new StatisticDescriptor[] {
+ f.createIntGauge("cpus",
+ "Number of cpus available to the java VM on its machine.",
+ "cpus", true),
+ f.createLongGauge("freeMemory",
+ "An approximation fo the total amount of memory currently available for future allocated objects, measured in bytes.",
+ "bytes", true),
+ f.createLongGauge("totalMemory",
+ "The total amount of memory currently available for current and future objects, measured in bytes.",
+ "bytes"),
+ f.createLongGauge("maxMemory",
+ "The maximum amount of memory that the VM will attempt to use, measured in bytes.",
+ "bytes", true)
+ });
+ cpusId = vmType.nameToId("cpus");
+ freeMemoryId = vmType.nameToId("freeMemory");
+ totalMemoryId = vmType.nameToId("totalMemory");
+ maxMemoryId = vmType.nameToId("maxMemory");
+ }
+
+ private final Statistics vmStats;
+
+
+ public VMStats(StatisticsFactory f, long id) {
+ this.vmStats = f.createStatistics(vmType, "vmStats", id);
+ }
+
+ public void refresh() {
+ Runtime rt = Runtime.getRuntime();
+ this.vmStats.setInt(cpusId, rt.availableProcessors());
+ this.vmStats.setLong(freeMemoryId, rt.freeMemory());
+ this.vmStats.setLong(totalMemoryId, rt.totalMemory());
+ this.vmStats.setLong(maxMemoryId, rt.maxMemory());
+
+ }
+ public void close() {
+ this.vmStats.close();
+ }
+
+ /* (non-Javadoc)
+ * @see com.gemstone.gemfire.internal.statistics.VMStatsContract#getFdsOpen()
+ */
+ public long getFdsOpen() {
+ return -1;
+ }
+
+ /* (non-Javadoc)
+ * @see com.gemstone.gemfire.internal.statistics.VMStatsContract#getFdLimit()
+ */
+ public long getFdLimit() {
+ return 0;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStatsContract.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStatsContract.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStatsContract.java
new file mode 100644
index 0000000..1870f27
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStatsContract.java
@@ -0,0 +1,36 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+/**
+ * Describes the contract a VMStats implementation must implement.
+ * <p> I named this VMStatsContract because an implementation named
+ * VMStats already exists and I didn't want to rename it because
+ * of the svn merge issues.
+ * @see VMStatsContractFactory
+ */
+public interface VMStatsContract {
+ /**
+ * Called by sampler when it wants the VMStats statistics values to be
+ * refetched from the system.
+ */
+ public void refresh();
+ /**
+ * Called by sampler when it wants the VMStats to go away.
+ */
+ public void close();
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStatsContractFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStatsContractFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStatsContractFactory.java
new file mode 100644
index 0000000..4555683
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/VMStatsContractFactory.java
@@ -0,0 +1,60 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.stats50.VMStats50;
+
+/**
+ * Factory used to produce an instance of VMStatsContract.
+ */
+public class VMStatsContractFactory {
+ /**
+ * Create and return a VMStatsContract.
+ */
+ public static VMStatsContract create(StatisticsFactory f, long id) {
+ VMStatsContract result;
+ try {
+ result = new VMStats50(f, id);
+ }
+ catch (VirtualMachineError err) {
+ SystemFailure.initiateFailure(err);
+ // If this ever returns, rethrow the error. We're poisoned
+ // now, so don't let this thread continue.
+ throw err;
+ }
+ catch (Throwable ignore) {
+ // Now that we no longer support 1.4 I'm not sure why we would get here.
+ // But just in case other vm vendors don't support mxbeans I've left
+ // this logic in that will create a simple VMStats instance.
+ // Whenever you catch Error or Throwable, you must also
+ // catch VirtualMachineError (see above). However, there is
+ // _still_ a possibility that you are dealing with a cascading
+ // error condition, so you also need to check to see if the JVM
+ // is still usable:
+ SystemFailure.checkFailure();
+ //log.warning("Could not create 5.0 VMStats", ignore);
+ // couldn't create the 1.5 version so create the old 1.4 version
+ result = new VMStats(f, id);
+ }
+ return result;
+ }
+
+ private VMStatsContractFactory() {
+ // private so no instances allowed. static methods only
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ValueMonitor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ValueMonitor.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ValueMonitor.java
index 211719f..725abb2 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ValueMonitor.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ValueMonitor.java
@@ -23,7 +23,6 @@ import java.util.Map;
import com.gemstone.gemfire.StatisticDescriptor;
import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.internal.CopyOnWriteHashSet;
-import com.gemstone.gemfire.internal.StatisticDescriptorImpl;
/**
* Adds coarser-grained monitoring of entire Statistics instances.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/package.html
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/package.html b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/package.html
index 8875df2..4cb2d4f 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/package.html
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/package.html
@@ -23,8 +23,8 @@ enhancements including the ability to monitor statistics. In addition, this
package is temporarily home for new external API classes that may eventually
be included in com.gemstone.gemfire.statistics. The original specification
is the
-<a href="https://wiki.gemstone.com/display/Tooling/Statistics+API+Specification">
-7.0 Statistics API Specification</a>.
+<a href="https://cwiki.apache.org/confluence/display/GEODE/Statistics+API">
+Statistics API</a>.
</p>
</body>
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxProcFsStatistics.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxProcFsStatistics.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxProcFsStatistics.java
new file mode 100644
index 0000000..1ce57a7
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxProcFsStatistics.java
@@ -0,0 +1,783 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import org.apache.logging.log4j.Logger;
+
+import java.io.*;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.NoSuchElementException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class LinuxProcFsStatistics {
+ private enum CPU {
+ USER, NICE, SYSTEM, IDLE, IOWAIT, IRQ, SOFTIRQ,
+ /** stands for aggregation of all columns not present in the enum list*/
+ OTHER
+ }
+
+ private static final int DEFAULT_PAGESIZE = 4 * 1024;
+ private static final int OneMeg = 1024 * 1024;
+ private static final String pageSizeProperty = DistributionConfig.GEMFIRE_PREFIX + "statistics.linux.pageSize";
+ private static CpuStat cpuStatSingleton;
+ private static int pageSize;
+ private static int sys_cpus;
+ private static boolean hasProcVmStat;
+ private static boolean hasDiskStats;
+ static SpaceTokenizer st;
+
+ /** The number of non-process files in /proc */
+ private static int nonPidFilesInProc;
+
+ /** /proc/stat tokens */
+ private static final String CPU_TOKEN = "cpu ";
+ private static final String PAGE = "page ";
+ private static final String SWAP = "swap ";
+ private static final String CTXT = "ctxt ";
+ private static final String PROCESSES = "processes ";
+
+ /** /proc/vmstat tokens */
+ private static final String PGPGIN = "pgpgin ";
+ private static final String PGPGOUT = "pgpgout ";
+ private static final String PSWPIN = "pswpin ";
+ private static final String PSWPOUT = "pswpout ";
+
+ //Do not create instances of this class
+ private LinuxProcFsStatistics() {
+ }
+
+ public static int init() { // TODO: was package-protected
+ nonPidFilesInProc = getNumberOfNonProcessProcFiles();
+ sys_cpus = Runtime.getRuntime().availableProcessors();
+ pageSize = Integer.getInteger(pageSizeProperty, DEFAULT_PAGESIZE);
+ cpuStatSingleton = new CpuStat();
+ hasProcVmStat = new File("/proc/vmstat").exists();
+ hasDiskStats = new File("/proc/diskstats").exists();
+ st = new SpaceTokenizer();
+ return 0;
+ }
+
+ public static void close() { // TODO: was package-protected
+ cpuStatSingleton = null;
+ st = null;
+ }
+
+ public static void readyRefresh() { // TODO: was package-protected
+ }
+
+ /* get the statistics for the specified process.
+ * ( pid_rssSize, pid_imageSize )
+ * vsize is assumed to be in units of kbytes
+ * System property gemfire.statistics.pagesSize can be used to configure
+ * pageSize. This is the mem_unit member of the struct returned by sysinfo()
+ *
+ */
+ public static void refreshProcess(int pid, int[] ints, long[] longs, double[] doubles) { // TODO: was package-protected
+ //Just incase a pid is not available
+ if(pid == 0) return;
+ InputStreamReader isr = null;
+ BufferedReader br = null;
+ try {
+ File file = new File( "/proc/" + pid + "/stat" );
+ isr = new InputStreamReader( new FileInputStream( file ));
+ br = new BufferedReader(isr, 2048);
+ String line = br.readLine();
+ if ( line == null ) {
+ return;
+ }
+ st.setString(line);
+ st.skipTokens(22);
+ ints[LinuxProcessStats.imageSizeINT] = (int) (st.nextTokenAsLong() / OneMeg);
+ ints[LinuxProcessStats.rssSizeINT] = (int) ((st.nextTokenAsLong()*pageSize)/OneMeg);
+ } catch ( NoSuchElementException nsee ) {
+ // It might just be a case of the process going away while we
+ // where trying to get its stats.
+ // So for now lets just ignore the failure and leave the stats
+ // as they are.
+ } catch ( IOException ioe ) {
+ // It might just be a case of the process going away while we
+ // where trying to get its stats.
+ // So for now lets just ignore the failure and leave the stats
+ // as they are.
+ } finally {
+ st.releaseResources();
+ if(br != null) try { br.close(); } catch(IOException ignore) {}
+ }
+ }
+
+ public static void refreshSystem(int[] ints, long[] longs, double[] doubles) { // TODO: was package-protected
+ ints[LinuxSystemStats.processesINT] = getProcessCount();
+ ints[LinuxSystemStats.cpusINT] = sys_cpus;
+ InputStreamReader isr = null;
+ BufferedReader br = null;
+ try {
+ isr = new InputStreamReader( new FileInputStream( "/proc/stat" ));
+ br = new BufferedReader(isr);
+ String line = null;
+ while ( ( line = br.readLine() ) != null ) {
+ try {
+ if (line.startsWith(CPU_TOKEN)) {
+ int[] cpuData = cpuStatSingleton.calculateStats(line);
+ ints[LinuxSystemStats.cpuIdleINT] = cpuData[CPU.IDLE.ordinal()];
+ ints[LinuxSystemStats.cpuNiceINT] = cpuData[CPU.NICE.ordinal()];
+ ints[LinuxSystemStats.cpuSystemINT] = cpuData[CPU.SYSTEM.ordinal()];
+ ints[LinuxSystemStats.cpuUserINT] = cpuData[CPU.USER.ordinal()];
+ ints[LinuxSystemStats.iowaitINT] = cpuData[CPU.IOWAIT.ordinal()];
+ ints[LinuxSystemStats.irqINT] = cpuData[CPU.IRQ.ordinal()];
+ ints[LinuxSystemStats.softirqINT] = cpuData[CPU.SOFTIRQ.ordinal()];
+ ints[LinuxSystemStats.cpuActiveINT] = 100 - cpuData[CPU.IDLE.ordinal()];
+ ints[LinuxSystemStats.cpuNonUserINT] = cpuData[CPU.OTHER.ordinal()]
+ + cpuData[CPU.SYSTEM.ordinal()]
+ + cpuData[CPU.IOWAIT.ordinal()]
+ + cpuData[CPU.IRQ.ordinal()]
+ + cpuData[CPU.SOFTIRQ.ordinal()];
+ } else if ( !hasProcVmStat && line.startsWith(PAGE)) {
+ int secondIndex = line.indexOf(" ", PAGE.length());
+ longs[LinuxSystemStats.pagesPagedInLONG] = SpaceTokenizer.parseAsLong(line.substring(PAGE.length(), secondIndex));
+ longs[LinuxSystemStats.pagesPagedOutLONG] = SpaceTokenizer.parseAsLong(line.substring(secondIndex+1));
+ } else if ( !hasProcVmStat && line.startsWith(SWAP)) {
+ int secondIndex = line.indexOf(" ", SWAP.length());
+ longs[LinuxSystemStats.pagesSwappedInLONG] = SpaceTokenizer.parseAsLong(line.substring(SWAP.length(), secondIndex));
+ longs[LinuxSystemStats.pagesSwappedOutLONG] = SpaceTokenizer.parseAsLong(line.substring(secondIndex+1));
+ } else if ( line.startsWith(CTXT)) {
+ longs[LinuxSystemStats.contextSwitchesLONG] = SpaceTokenizer.parseAsLong(line.substring(CTXT.length()));
+ } else if ( line.startsWith(PROCESSES)) {
+ longs[LinuxSystemStats.processCreatesLONG] = SpaceTokenizer.parseAsInt(line.substring(PROCESSES.length()));
+ }
+ } catch ( NoSuchElementException nsee ) {
+ //this is the result of reading a partially formed file
+ //just do not update what ever entry had the problem
+ }
+ }
+ } catch ( IOException ioe ) {
+ } finally {
+ if(br != null) try { br.close(); } catch(IOException ignore) {}
+ }
+ getLoadAvg(doubles);
+ getMemInfo(ints);
+ getDiskStats(longs);
+ getNetStats(longs);
+ if(hasProcVmStat) {
+ getVmStats(longs);
+ }
+ st.releaseResources();
+ }
+
+ // Example of /proc/loadavg
+ // 0.00 0.00 0.07 1/218 7907
+ private static void getLoadAvg(double[] doubles) {
+ InputStreamReader isr = null;
+ BufferedReader br = null;
+ try {
+ isr = new InputStreamReader( new FileInputStream( "/proc/loadavg" ));
+ br = new BufferedReader(isr, 512);
+ String line = br.readLine();
+ if ( line == null ) {
+ return;
+ }
+ st.setString(line);
+ doubles[LinuxSystemStats.loadAverage1DOUBLE] = st.nextTokenAsDouble();
+ doubles[LinuxSystemStats.loadAverage5DOUBLE] = st.nextTokenAsDouble();
+ doubles[LinuxSystemStats.loadAverage15DOUBLE] = st.nextTokenAsDouble();
+ } catch ( NoSuchElementException nsee ) {
+ } catch (IOException ioe) {
+ } finally {
+ st.releaseResources();
+ if(br != null) try { br.close(); } catch(IOException ignore) {}
+ }
+ }
+
+ /**
+ * Returns the available system memory (free + cached).
+ * @param logger the logger
+ * @return the available memory in bytes
+ */
+ public static long getAvailableMemory(Logger logger) {
+ try {
+ BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/meminfo")));
+ try {
+ long free = 0;
+ Pattern p = Pattern.compile("(.*)?:\\s+(\\d+)( kB)?");
+
+ String line;
+ while ((line = br.readLine()) != null) {
+ Matcher m = p.matcher(line);
+ if (m.matches() && ("MemFree".equals(m.group(1)) || "Cached".equals(m.group(1)))) {
+ free += Long.parseLong(m.group(2));
+ }
+ }
+
+ // convert to bytes
+ return 1024 * free;
+
+ } finally {
+ br.close();
+ }
+ } catch (IOException e) {
+ logger.warn("Error determining free memory", e);
+ return Long.MAX_VALUE;
+ }
+ }
+
+ // Example of /proc/meminfo
+ // total: used: free: shared: buffers: cached:
+ //Mem: 4118380544 3816050688 302329856 0 109404160 3060326400
+ //Swap: 4194881536 127942656 4066938880
+ private static void getMemInfo(int[] ints) {
+ InputStreamReader isr = null;
+ BufferedReader br = null;
+ try {
+ isr = new InputStreamReader( new FileInputStream( "/proc/meminfo" ));
+ br = new BufferedReader(isr);
+ //Assume all values read in are in kB, convert to MB
+ String line = null;
+ while ( (line = br.readLine()) != null) {
+ try {
+ if ( line.startsWith("MemTotal: ")) {
+ st.setString(line);
+ st.skipToken(); //Burn initial token
+ ints[LinuxSystemStats.physicalMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
+ } else if ( line.startsWith("MemFree: ")) {
+ st.setString(line);
+ st.skipToken(); //Burn initial token
+ ints[LinuxSystemStats.freeMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
+ } else if ( line.startsWith("SharedMem: ")) {
+ st.setString(line);
+ st.skipToken(); //Burn initial token
+ ints[LinuxSystemStats.sharedMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
+ } else if ( line.startsWith("Buffers: ")) {
+ st.setString(line);
+ st.nextToken(); //Burn initial token
+ ints[LinuxSystemStats.bufferMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
+ } else if ( line.startsWith("SwapTotal: ")) {
+ st.setString(line);
+ st.skipToken(); //Burn initial token
+ ints[LinuxSystemStats.allocatedSwapINT] = (int) (st.nextTokenAsLong() / 1024);
+ } else if ( line.startsWith("SwapFree: ")) {
+ st.setString(line);
+ st.skipToken(); //Burn initial token
+ ints[LinuxSystemStats.unallocatedSwapINT] = (int) (st.nextTokenAsLong() / 1024);
+ } else if ( line.startsWith("Cached: ")) {
+ st.setString(line);
+ st.skipToken(); //Burn initial token
+ ints[LinuxSystemStats.cachedMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
+ } else if ( line.startsWith("Dirty: ")) {
+ st.setString(line);
+ st.skipToken(); //Burn initial token
+ ints[LinuxSystemStats.dirtyMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
+ } else if ( line.startsWith("Inact_dirty: ")) { // 2.4 kernels
+ st.setString(line);
+ st.skipToken(); //Burn initial token
+ ints[LinuxSystemStats.dirtyMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
+ }
+ } catch(NoSuchElementException nsee) {
+ //ignore and let that stat not to be updated this time
+ }
+ }
+ } catch ( IOException ioe ) {
+ } finally {
+ st.releaseResources();
+ if(br != null) try { br.close(); } catch(IOException ignore) {}
+ }
+ }
+
+ /*
+Inter-| Receive | Transmit
+ face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
+ lo:1908275823 326949246 0 0 0 0 0 0 1908275823 326949246 0 0 0 0 0 0
+*/
+
+ private static void getNetStats(long[] longs) {
+ InputStreamReader isr = null;
+ BufferedReader br = null;
+ try {
+ isr = new InputStreamReader( new FileInputStream( "/proc/net/dev" ));
+ br = new BufferedReader(isr);
+ br.readLine(); // Discard header info
+ br.readLine(); // Discard header info
+ long lo_recv_packets = 0, lo_recv_bytes = 0;
+ long other_recv_packets = 0, other_recv_bytes = 0;
+ long other_recv_errs = 0, other_recv_drop = 0;
+ long other_xmit_packets = 0, other_xmit_bytes = 0;
+ long other_xmit_errs = 0, other_xmit_drop = 0, other_xmit_colls = 0;
+ String line = null;
+ while ( (line = br.readLine()) != null) {
+ int index = line.indexOf(":");
+ boolean isloopback = (line.indexOf("lo:") != -1);
+ st.setString(line.substring(index+1).trim());
+ long recv_bytes = st.nextTokenAsLong();
+ long recv_packets = st.nextTokenAsLong();
+ long recv_errs = st.nextTokenAsLong();
+ long recv_drop = st.nextTokenAsLong();
+ st.skipTokens(4); //fifo, frame, compressed, multicast
+ long xmit_bytes = st.nextTokenAsLong();
+ long xmit_packets = st.nextTokenAsLong();
+ long xmit_errs = st.nextTokenAsLong();
+ long xmit_drop = st.nextTokenAsLong();
+ st.skipToken(); //fifo
+ long xmit_colls = st.nextTokenAsLong();
+
+ if (isloopback) {
+ lo_recv_packets = recv_packets;
+ lo_recv_bytes = recv_bytes;
+ }
+ else {
+ other_recv_packets += recv_packets;
+ other_recv_bytes += recv_bytes;
+ }
+ other_recv_errs += recv_errs;
+ other_recv_drop += recv_drop;
+
+ if (isloopback) {
+ /* loopback_xmit_packets = xmit_packets; */
+ } else {
+ other_xmit_packets += xmit_packets;
+ other_xmit_bytes += xmit_bytes;
+ }
+ other_xmit_errs += xmit_errs;
+ other_xmit_drop += xmit_drop;
+ other_xmit_colls += xmit_colls;
+ }
+ // fix for bug 43860
+ longs[LinuxSystemStats.loopbackPacketsLONG] = lo_recv_packets;
+ longs[LinuxSystemStats.loopbackBytesLONG] = lo_recv_bytes;
+ longs[LinuxSystemStats.recvPacketsLONG] = other_recv_packets;
+ longs[LinuxSystemStats.recvBytesLONG] = other_recv_bytes;
+ longs[LinuxSystemStats.recvErrorsLONG] = other_recv_errs;
+ longs[LinuxSystemStats.recvDropsLONG] = other_recv_drop;
+ longs[LinuxSystemStats.xmitPacketsLONG] = other_xmit_packets;
+ longs[LinuxSystemStats.xmitBytesLONG] = other_xmit_bytes;
+ longs[LinuxSystemStats.xmitErrorsLONG] = other_xmit_errs;
+ longs[LinuxSystemStats.xmitDropsLONG] = other_xmit_drop;
+ longs[LinuxSystemStats.xmitCollisionsLONG] = other_xmit_colls;
+ } catch (NoSuchElementException nsee) {
+ } catch (IOException ioe) {
+ } finally {
+ st.releaseResources();
+ if(br != null) try { br.close(); } catch(IOException ignore) {}
+ }
+ }
+
+ // example of /proc/diskstats
+// 1 0 ram0 0 0 0 0 0 0 0 0 0 0 0
+// 1 1 ram1 0 0 0 0 0 0 0 0 0 0 0
+// 1 2 ram2 0 0 0 0 0 0 0 0 0 0 0
+// 1 3 ram3 0 0 0 0 0 0 0 0 0 0 0
+// 1 4 ram4 0 0 0 0 0 0 0 0 0 0 0
+// 1 5 ram5 0 0 0 0 0 0 0 0 0 0 0
+// 1 6 ram6 0 0 0 0 0 0 0 0 0 0 0
+// 1 7 ram7 0 0 0 0 0 0 0 0 0 0 0
+// 1 8 ram8 0 0 0 0 0 0 0 0 0 0 0
+// 1 9 ram9 0 0 0 0 0 0 0 0 0 0 0
+// 1 10 ram10 0 0 0 0 0 0 0 0 0 0 0
+// 1 11 ram11 0 0 0 0 0 0 0 0 0 0 0
+// 1 12 ram12 0 0 0 0 0 0 0 0 0 0 0
+// 1 13 ram13 0 0 0 0 0 0 0 0 0 0 0
+// 1 14 ram14 0 0 0 0 0 0 0 0 0 0 0
+// 1 15 ram15 0 0 0 0 0 0 0 0 0 0 0
+// 8 0 sda 1628761 56603 37715982 5690640 6073889 34091137 330349716 279787924 0 25235208 285650572
+// 8 1 sda1 151 638 45 360
+// 8 2 sda2 674840 11202608 8591346 68716852
+// 8 3 sda3 1010409 26512312 31733575 253868616
+// 8 16 sdb 12550386 47814 213085738 60429448 5529812 210792345 1731459040 1962038752 0 33797176 2024138028
+// 8 17 sdb1 12601113 213085114 216407197 1731257800
+// 3 0 hda 0 0 0 0 0 0 0 0 0 0 0
+ private static void getDiskStats(long[] longs) {
+ InputStreamReader isr = null;
+ BufferedReader br = null;
+ String line = null;
+ try {
+ if (hasDiskStats) {
+ // 2.6 kernel
+ isr = new InputStreamReader( new FileInputStream( "/proc/diskstats" ));
+ } else {
+ // 2.4 kernel
+ isr = new InputStreamReader( new FileInputStream( "/proc/partitions" ));
+ }
+ br = new BufferedReader(isr);
+ long readsCompleted = 0, readsMerged = 0;
+ long sectorsRead = 0, timeReading = 0;
+ long writesCompleted = 0, writesMerged = 0;
+ long sectorsWritten = 0, timeWriting = 0;
+ long iosInProgress = 0;
+ long timeIosInProgress = 0;
+ long ioTime = 0;
+ if (!hasDiskStats) {
+ br.readLine(); // Discard header info
+ br.readLine(); // Discard header info
+ }
+ while ( (line = br.readLine()) != null) {
+ st.setString(line);
+ {
+ // " 8 1 sdb" on 2.6
+ // " 8 1 452145145 sdb" on 2.4
+ String tok = st.nextToken();
+ if (tok.length() == 0 || Character.isWhitespace(tok.charAt(0))) {
+ // skip over first token since it is whitespace
+ tok = st.nextToken();
+ }
+ // skip first token it is some number
+ tok = st.nextToken();
+ // skip second token it is some number
+ tok = st.nextToken();
+ if (!hasDiskStats) {
+ // skip third token it is some number
+ tok = st.nextToken();
+ }
+ // Now tok should be the device name.
+ if (Character.isDigit(tok.charAt(tok.length()-1))) {
+ // If the last char is a digit
+ // skip this line since it is a partition of a device; not a device.
+ continue;
+ }
+ }
+ long tmp_readsCompleted = st.nextTokenAsLong();
+ long tmp_readsMerged = st.nextTokenAsLong();
+ long tmp_sectorsRead = st.nextTokenAsLong();
+ long tmp_timeReading = st.nextTokenAsLong();
+ if (st.hasMoreTokens()) {
+ // If we are on 2.6 then we might only have 4 longs; if so ignore this line
+ // Otherwise we should have 11 long tokens.
+ long tmp_writesCompleted = st.nextTokenAsLong();
+ long tmp_writesMerged = st.nextTokenAsLong();
+ long tmp_sectorsWritten = st.nextTokenAsLong();
+ long tmp_timeWriting = st.nextTokenAsLong();
+ long tmp_iosInProgress = st.nextTokenAsLong();
+ long tmp_timeIosInProgress = st.nextTokenAsLong();
+ long tmp_ioTime = st.nextTokenAsLong();
+ readsCompleted += tmp_readsCompleted;
+ readsMerged += tmp_readsMerged;
+ sectorsRead += tmp_sectorsRead;
+ timeReading += tmp_timeReading;
+ writesCompleted += tmp_writesCompleted;
+ writesMerged += tmp_writesMerged;
+ sectorsWritten += tmp_sectorsWritten;
+ timeWriting += tmp_timeWriting;
+ iosInProgress += tmp_iosInProgress;
+ timeIosInProgress += tmp_timeIosInProgress;
+ ioTime += tmp_ioTime;
+ }
+ } // while
+ final int SECTOR_SIZE = 512;
+ longs[LinuxSystemStats.readsCompletedLONG] = readsCompleted;
+ longs[LinuxSystemStats.readsMergedLONG] = readsMerged;
+ longs[LinuxSystemStats.bytesReadLONG] = sectorsRead * SECTOR_SIZE;
+ longs[LinuxSystemStats.timeReadingLONG] = timeReading;
+ longs[LinuxSystemStats.writesCompletedLONG] = writesCompleted;
+ longs[LinuxSystemStats.writesMergedLONG] = writesMerged;
+ longs[LinuxSystemStats.bytesWrittenLONG] = sectorsWritten * SECTOR_SIZE;
+ longs[LinuxSystemStats.timeWritingLONG] = timeWriting;
+ longs[LinuxSystemStats.iosInProgressLONG] = iosInProgress;
+ longs[LinuxSystemStats.timeIosInProgressLONG] = timeIosInProgress;
+ longs[LinuxSystemStats.ioTimeLONG] = ioTime;
+ } catch (NoSuchElementException nsee) {
+// com.gemstone.gemfire.distributed.internal.InternalDistributedSystem.getAnyInstance().getLoggerI18n().fine("unexpected NoSuchElementException line=" + line, nsee);
+ } catch (IOException ioe) {
+ } finally {
+ st.releaseResources();
+ if(br != null) try { br.close(); } catch(IOException ignore) {}
+ }
+ }
+
+ //Example of /proc/vmstat
+ //...
+ //pgpgin 294333738
+ //pgpgout 1057420300
+ //pswpin 19422
+ //pswpout 14495
+ private static void getVmStats(long[] longs) {
+ assert hasProcVmStat != false : "getVmStats called when hasVmStat was false";
+ InputStreamReader isr = null;
+ BufferedReader br = null;
+ try {
+ isr = new InputStreamReader( new FileInputStream( "/proc/vmstat" ));
+ br = new BufferedReader(isr);
+ String line = null;
+ while((line = br.readLine()) != null) {
+ if(line.startsWith(PGPGIN)) {
+ longs[LinuxSystemStats.pagesPagedInLONG]
+ = SpaceTokenizer.parseAsLong(line.substring(PGPGIN.length()));
+ } else if(line.startsWith(PGPGOUT)) {
+ longs[LinuxSystemStats.pagesPagedOutLONG]
+ = SpaceTokenizer.parseAsLong(line.substring(PGPGOUT.length()));
+ } else if(line.startsWith(PSWPIN)) {
+ longs[LinuxSystemStats.pagesSwappedInLONG]
+ = SpaceTokenizer.parseAsLong(line.substring(PSWPIN.length()));
+ } else if(line.startsWith(PSWPOUT)) {
+ longs[LinuxSystemStats.pagesSwappedOutLONG]
+ = SpaceTokenizer.parseAsLong(line.substring(PSWPOUT.length()));
+ }
+ }
+ } catch (NoSuchElementException nsee) {
+ } catch (IOException ioe) {
+ } finally {
+ if(br != null) try { br.close(); } catch(IOException ignore) {}
+ }
+ }
+
+ /**
+ * Count the number of files in /proc that do not represent processes.
+ * This value is cached to make counting the number of running process a
+ * cheap operation. The assumption is that the contents of /proc will not
+ * change on a running system.
+ * @return the files in /proc that do NOT match /proc/[0-9]*
+ */
+ private static int getNumberOfNonProcessProcFiles() {
+ File proc = new File("/proc");
+ String[] procFiles = proc.list();
+ int count = 0;
+ if(procFiles != null) {
+ for(String filename : procFiles) {
+ char c = filename.charAt(0);
+ if(! Character.isDigit(c)) {
+ if (c == '.') {
+ // see if the next char is a digit
+ if (filename.length() > 1) {
+ char c2 = filename.charAt(1);
+ if (Character.isDigit(c2)) {
+ // for bug 42091 do not count files that begin with a '.' followed by digits
+ continue;
+ }
+ }
+ }
+ count++;
+ }
+ }
+ }
+ return count;
+ }
+
+ /**
+ * @return the number of running processes on the system
+ */
+ private static int getProcessCount() {
+ File proc = new File("/proc");
+ String[] procFiles = proc.list();
+ if(procFiles == null) {
+ //unknown error, continue without this stat
+ return 0;
+ }
+ return procFiles.length - nonPidFilesInProc;
+ }
+
+ //The array indices must be ordered as they appear in /proc/stats
+ // (user) (nice) (system) (idle) (iowait) (irq) (softirq)
+ // cpu 42813766 10844 8889075 1450764512 49963779 808244 3084872
+ //
+ private static class CpuStat {
+ private static boolean lastCpuStatsInvalid;
+ private static List<Long> lastCpuStats;
+
+ public CpuStat() {
+ lastCpuStatsInvalid = true;
+ }
+
+ public int[] calculateStats( String newStatLine ) {
+ st.setString(newStatLine);
+ st.skipToken(); //cpu name
+ final int MAX_CPU_STATS = CPU.values().length;
+ /* newer kernels now have 8 columns for cpu in
+ * /proc/stat (up from 7). This number may increase
+ * even further, hence we now use List in place of long[].
+ * We add up entries from all columns after 7 into CPU.OTHER
+ */
+ List<Long> newStats = new ArrayList<Long>(8);
+ List<Long> diffs = new ArrayList<Long>(8);
+ long total_change = 0;
+ int actualCpuStats = 0;
+ long unaccountedCpuUtilization = 0;
+
+ while (st.hasMoreTokens()) {
+ newStats.add(st.nextTokenAsLong());
+ actualCpuStats++;
+ }
+
+ if ( lastCpuStatsInvalid ) {
+ lastCpuStats = newStats;
+ lastCpuStatsInvalid = false;
+ for (int i=0; i<MAX_CPU_STATS; i++) {
+ diffs.add(0L);
+ }
+ diffs.set(CPU.IDLE.ordinal(), 100L);
+ } else {
+ for (int i=0; i<actualCpuStats; i++) {
+ diffs.add(newStats.get(i) - lastCpuStats.get(i));
+ total_change += diffs.get(i);
+ lastCpuStats.set(i, newStats.get(i));
+ }
+ if(total_change == 0) {
+ //avoid divide by zero
+ total_change = 1;
+ }
+ for (int i = 0; i < MAX_CPU_STATS; i++) {
+ if (i < actualCpuStats) {
+ diffs.set(i, (diffs.get(i) * 100) / total_change);
+ }
+ }
+ for (int i=MAX_CPU_STATS; i<actualCpuStats; i++) {
+ unaccountedCpuUtilization += (diffs.get(i) * 100) / total_change;
+ }
+ }
+ int[] ret = new int[MAX_CPU_STATS];
+ for (int i = 0; i < MAX_CPU_STATS; i++) {
+ if (i < actualCpuStats) {
+ ret[i] = diffs.get(i).intValue();
+ }
+ }
+ ret[CPU.OTHER.ordinal()] += (int)unaccountedCpuUtilization;
+ return ret;
+ }
+ }
+
+ private static class SpaceTokenizer {
+ private String str;
+ private char[] rawChars;
+ private int beginIdx;
+ private int endIdx;
+ private int nextIdx;
+
+ protected SpaceTokenizer() {
+ endIdx = -1;
+ nextIdx = -1;
+ }
+
+ protected void releaseResources() {
+ str = null;
+ rawChars = null;
+ endIdx = -1;
+ nextIdx = -1;
+ }
+
+ private void nextIdx() {
+ int origin = nextIdx;
+ if(endIdx == rawChars.length || beginIdx == -1) {
+ endIdx = -1;
+ nextIdx = -1;
+ return;
+ }
+ endIdx = -1;
+ nextIdx = -1;
+ for(int i = origin+1; i < rawChars.length; i++) {
+ char c = rawChars[i];
+ //Add all delimiters here
+ if(c == ' ' || c == '\t' || c == '\n' || c == '\r') {
+ if(endIdx == -1) {
+ endIdx = i;
+ }
+ } else {
+ //this handles multiple consecutive delimiters
+ if(endIdx != -1) {
+ nextIdx = i;
+ return;
+ }
+ }
+ }
+ if( endIdx == -1 ) {
+ //indicates we were still reading white space at the end of the string
+ endIdx = rawChars.length;
+ }
+ }
+
+ protected boolean hasMoreTokens() {
+ return endIdx != -1;
+ }
+
+ protected void setString(String data) {
+ str = data;
+ rawChars = new char[str.length()];
+ str.getChars(0, str.length(), rawChars, 0);
+ beginIdx = 0;
+ endIdx = -1;
+ nextIdx = -1;
+ nextIdx();
+ }
+
+ protected boolean skipToken() {
+ if(hasMoreTokens()) {
+ beginIdx = nextIdx;
+ nextIdx();
+ return true;
+ }
+ return false;
+ }
+
+ protected String nextToken() {
+ if(hasMoreTokens()) {
+ final String ret = str.substring(beginIdx, endIdx);
+ beginIdx = nextIdx;
+ nextIdx();
+ return ret;
+ }
+ throw new NoSuchElementException();
+ }
+
+ protected String peekToken() {
+ if(hasMoreTokens()) {
+ return str.substring(beginIdx, endIdx);
+ }
+ throw new NoSuchElementException();
+ }
+
+ protected void skipTokens(int numberToSkip) {
+ int remaining = numberToSkip + 1;
+ while (--remaining > 0 && skipToken());
+ }
+
+ protected static long parseAsLong(String number) {
+ long l = 0L;
+ try {
+ l = Long.parseLong(number);
+ } catch(NumberFormatException nfe) {}
+ return l;
+ }
+
+ protected static int parseAsInt(String number) {
+ int i = 0;
+ try {
+ i = Integer.parseInt(number);
+ } catch(NumberFormatException nfe) {}
+ return i;
+ }
+
+ protected int nextTokenAsInt() {
+ int i = 0;
+ try {
+ i = Integer.parseInt(nextToken());
+ } catch(NumberFormatException nfe) {}
+ return i;
+ }
+
+ protected long nextTokenAsLong() {
+ long l = 0L;
+ try {
+ l = Long.parseLong(nextToken());
+ } catch(NumberFormatException nfe) {}
+ return l;
+ }
+
+ protected double nextTokenAsDouble() {
+ double d = 0;
+ try {
+ d = Double.parseDouble(nextToken());
+ } catch(NumberFormatException nfe) {}
+ return d;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxProcessStats.java
new file mode 100644
index 0000000..ab4b78d
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxProcessStats.java
@@ -0,0 +1,84 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.statistics.HostStatHelper;
+import com.gemstone.gemfire.internal.statistics.LocalStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
+
+/**
+ * <P>This class provides the interface for statistics about a
+ * Linux operating system process that is using a GemFire system.
+ */
+public class LinuxProcessStats
+{
+ final static int imageSizeINT = 0;
+ final static int rssSizeINT = 1;
+
+ private final static StatisticsType myType;
+
+ private static void checkOffset(String name, int offset) {
+ int id = myType.nameToId(name);
+ Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
+ }
+
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ myType = f.createType("LinuxProcessStats",
+ "Statistics on a Linux process.",
+ new StatisticDescriptor[] {
+ f.createIntGauge("imageSize",
+ "The size of the process's image in megabytes.",
+ "megabytes"),
+ f.createIntGauge("rssSize",
+ "The size of the process's resident set size in megabytes. (assumes PAGESIZE=4096, specify -Dgemfire.statistics.linux.pageSize=<pagesize> to adjust)",
+ "megabytes"),
+ });
+ checkOffset("imageSize", imageSizeINT);
+ checkOffset("rssSize", rssSizeINT);
+ }
+
+ private LinuxProcessStats() {
+ // no instances allowed
+ }
+ public static StatisticsType getType() {
+ return myType;
+ }
+
+ /**
+ * Returns a <code>ProcessStats</code> that wraps Linux process
+ * <code>Statistics</code>.
+ *
+ * @since GemFire 3.5
+ */
+ public static ProcessStats createProcessStats(final Statistics stats) { // TODO: was package-protected
+ if (stats instanceof LocalStatisticsImpl) {
+ HostStatHelper.refresh((LocalStatisticsImpl) stats);
+ } // otherwise its a Dummy implementation so do nothing
+ return new ProcessStats(stats) {
+ @Override
+ public long getProcessSize() {
+ return stats.getInt(rssSizeINT);
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxSystemStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxSystemStats.java
new file mode 100644
index 0000000..f50204e
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/LinuxSystemStats.java
@@ -0,0 +1,313 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+
+/**
+ * <P>This class provides the interface for statistics about the
+ * Linux machine a GemFire system is running on.
+ */
+public class LinuxSystemStats
+{
+
+ // shared fields
+ final static int allocatedSwapINT = 0;
+ final static int bufferMemoryINT = 1;
+ final static int sharedMemoryINT = 2;
+ final static int cpuActiveINT = 3;
+ final static int cpuIdleINT = 4;
+ final static int cpuNiceINT = 5;
+ final static int cpuSystemINT = 6;
+ final static int cpuUserINT = 7;
+ final static int iowaitINT = 8;
+ final static int irqINT = 9;
+ final static int softirqINT = 10;
+ final static int cpusINT = 11;
+ final static int freeMemoryINT = 12;
+ final static int physicalMemoryINT = 13;
+ final static int processesINT = 14;
+ final static int unallocatedSwapINT = 15;
+ final static int cachedMemoryINT = 16;
+ final static int dirtyMemoryINT = 17;
+ final static int cpuNonUserINT = 18;
+
+ final static int loopbackPacketsLONG = 0;
+ final static int loopbackBytesLONG = 1;
+ final static int recvPacketsLONG = 2;
+ final static int recvBytesLONG = 3;
+ final static int recvErrorsLONG = 4;
+ final static int recvDropsLONG = 5;
+ final static int xmitPacketsLONG = 6;
+ final static int xmitBytesLONG = 7;
+ final static int xmitErrorsLONG = 8;
+ final static int xmitDropsLONG = 9;
+ final static int xmitCollisionsLONG = 10;
+ final static int contextSwitchesLONG = 11;
+ final static int processCreatesLONG = 12;
+ final static int pagesPagedInLONG = 13;
+ final static int pagesPagedOutLONG = 14;
+ final static int pagesSwappedInLONG = 15;
+ final static int pagesSwappedOutLONG = 16;
+ final static int readsCompletedLONG = 17;
+ final static int readsMergedLONG = 18;
+ final static int bytesReadLONG = 19;
+ final static int timeReadingLONG = 20;
+ final static int writesCompletedLONG = 21;
+ final static int writesMergedLONG = 22;
+ final static int bytesWrittenLONG = 23;
+ final static int timeWritingLONG = 24;
+ final static int iosInProgressLONG = 25;
+ final static int timeIosInProgressLONG = 26;
+ final static int ioTimeLONG = 27;
+
+ final static int loadAverage1DOUBLE = 0;
+ final static int loadAverage15DOUBLE = 1;
+ final static int loadAverage5DOUBLE = 2;
+
+ private final static StatisticsType myType;
+
+ private static void checkOffset(String name, int offset) {
+ int id = myType.nameToId(name);
+ Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
+ }
+
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ myType = f.createType("LinuxSystemStats",
+ "Statistics on a Linux machine.",
+ new StatisticDescriptor[] {
+ f.createIntGauge("allocatedSwap",
+ "The number of megabytes of swap space have actually been written to. Swap space must be reserved before it can be allocated.",
+ "megabytes"),
+ f.createIntGauge("bufferMemory",
+ "The number of megabytes of memory allocated to buffers.",
+ "megabytes"),
+ f.createIntGauge("sharedMemory",
+ "The number of megabytes of shared memory on the machine.",
+ "megabytes", true),
+ f.createIntGauge("cpuActive",
+ "The percentage of the total available time that has been used in a non-idle state.",
+ "%"),
+ f.createIntGauge("cpuIdle",
+ "The percentage of the total available time that has been spent sleeping.",
+ "%", true),
+ f.createIntGauge("cpuNice",
+ "The percentage of the total available time that has been used to execute user code in processes with low priority.",
+ "%"),
+ f.createIntGauge("cpuSystem",
+ "The percentage of the total available time that has been used to execute system (i.e. kernel) code.",
+ "%"),
+ f.createIntGauge("cpuUser",
+ "The percentage of the total available time that has been used to execute user code.",
+ "%"),
+ f.createIntGauge("iowait",
+ "The percentage of the total available time that has been used to wait for I/O to complete.",
+ "%"),
+ f.createIntGauge("irq",
+ "The percentage of the total available time that has been used servicing interrupts.",
+ "%"),
+ f.createIntGauge("softirq",
+ "The percentage of the total available time that has been used servicing softirqs.",
+ "%"),
+ f.createIntGauge("cpus",
+ "The number of online cpus on the local machine.",
+ "items"),
+ f.createIntGauge("freeMemory",
+ "The number of megabytes of unused memory on the machine.",
+ "megabytes", true),
+ f.createIntGauge("physicalMemory",
+ "The actual amount of total physical memory on the machine.",
+ "megabytes", true),
+ f.createIntGauge("processes",
+ "The number of processes in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Each process represents the running of a program.",
+ "processes"),
+ f.createIntGauge("unallocatedSwap",
+ "The number of megabytes of swap space that have not been allocated.",
+ "megabytes", true),
+ f.createIntGauge("cachedMemory",
+ "The number of megabytes of memory used for the file system cache.",
+ "megabytes", true),
+ f.createIntGauge("dirtyMemory",
+ "The number of megabytes of memory in the file system cache that need to be written.",
+ "megabytes", true),
+ f.createIntGauge("cpuNonUser",
+ "The percentage of total available time that has been used to execute non-user code.(includes system, iowait, irq, softirq etc.)",
+ "%"),
+
+
+ f.createLongCounter("loopbackPackets",
+ "The number of network packets sent (or received) on the loopback interface",
+ "packets", false),
+ f.createLongCounter("loopbackBytes",
+ "The number of network bytes sent (or received) on the loopback interface",
+ "bytes", false),
+ f.createLongCounter("recvPackets",
+ "The total number of network packets received (excluding loopback)",
+ "packets", false),
+ f.createLongCounter("recvBytes",
+ "The total number of network bytes received (excluding loopback)",
+ "bytes", false),
+ f.createLongCounter("recvErrors",
+ "The total number of network receive errors",
+ "errors", false),
+ f.createLongCounter("recvDrops",
+ "The total number network receives dropped",
+ "packets", false),
+ f.createLongCounter("xmitPackets",
+ "The total number of network packets transmitted (excluding loopback)",
+ "packets", false),
+ f.createLongCounter("xmitBytes",
+ "The total number of network bytes transmitted (excluding loopback)",
+ "bytes", false),
+ f.createLongCounter("xmitErrors",
+ "The total number of network transmit errors",
+ "errors", false),
+ f.createLongCounter("xmitDrops",
+ "The total number of network transmits dropped",
+ "packets", false),
+ f.createLongCounter("xmitCollisions",
+ "The total number of network transmit collisions",
+ "collisions", false),
+ f.createLongCounter("contextSwitches",
+ "The total number of context switches from one thread to another on the computer. Thread switches can occur either inside of a single process or across processes. A thread switch may be caused either by one thread asking another for information, or by a thread being preempted by another, higher priority thread becoming ready to run.",
+ "operations", false),
+ f.createLongCounter("processCreates",
+ "The total number of times a process has been created.",
+ "operations", false),
+ f.createLongCounter("pagesPagedIn",
+ "The total number of pages that have been brought into memory from disk by the operating system's memory manager.",
+ "pages", false),
+ f.createLongCounter("pagesPagedOut",
+ "The total number of pages that have been flushed from memory to disk by the operating system's memory manager.",
+ "pages", false),
+ f.createLongCounter("pagesSwappedIn",
+ "The total number of swap pages that have been read in from disk by the operating system's memory manager.",
+ "pages", false),
+ f.createLongCounter("pagesSwappedOut",
+ "The total number of swap pages that have been written out to disk by the operating system's memory manager.",
+ "pages", false),
+ f.createLongCounter("diskReadsCompleted",
+ "The total number disk read operations completed successfully",
+ "ops"),
+ f.createLongCounter("diskReadsMerged",
+ "The total number disk read operations that were able to be merge with adjacent reads for efficiency",
+ "ops"),
+ f.createLongCounter("diskBytesRead",
+ "The total number bytes read from disk successfully",
+ "bytes"),
+ f.createLongCounter("diskTimeReading",
+ "The total number of milliseconds spent reading from disk",
+ "milliseconds"),
+ f.createLongCounter("diskWritesCompleted",
+ "The total number disk write operations completed successfully",
+ "ops"),
+ f.createLongCounter("diskWritesMerged",
+ "The total number disk write operations that were able to be merge with adjacent reads for efficiency",
+ "ops"),
+ f.createLongCounter("diskBytesWritten",
+ "The total number bytes written to disk successfully",
+ "bytes"),
+ f.createLongCounter("diskTimeWriting",
+ "The total number of milliseconds spent writing to disk",
+ "milliseconds"),
+ f.createLongGauge("diskOpsInProgress",
+ "The current number of disk operations in progress",
+ "ops"),
+ f.createLongCounter("diskTimeInProgress",
+ "The total number of milliseconds spent with disk ops in progress",
+ "milliseconds"),
+ f.createLongCounter("diskTime",
+ "The total number of milliseconds that measures both completed disk operations and any accumulating backlog of in progress ops.",
+ "milliseconds"),
+
+
+ f.createDoubleGauge("loadAverage1",
+ "The average number of threads in the run queue or waiting for disk I/O over the last minute.",
+ "threads"),
+ f.createDoubleGauge("loadAverage15",
+ "The average number of threads in the run queue or waiting for disk I/O over the last fifteen minutes.",
+ "threads"),
+ f.createDoubleGauge("loadAverage5",
+ "The average number of threads in the run queue or waiting for disk I/O over the last five minutes.",
+ "threads"),
+ });
+
+ checkOffset("allocatedSwap", allocatedSwapINT);
+ checkOffset("bufferMemory", bufferMemoryINT);
+ checkOffset("sharedMemory", sharedMemoryINT);
+ checkOffset("cpuActive", cpuActiveINT);
+ checkOffset("cpuIdle", cpuIdleINT);
+ checkOffset("cpuNice", cpuNiceINT);
+ checkOffset("cpuSystem", cpuSystemINT);
+ checkOffset("cpuUser", cpuUserINT);
+ checkOffset("iowait", iowaitINT);
+ checkOffset("irq", irqINT);
+ checkOffset("softirq", softirqINT);
+ checkOffset("cpus", cpusINT);
+ checkOffset("freeMemory", freeMemoryINT);
+ checkOffset("physicalMemory", physicalMemoryINT);
+ checkOffset("processes", processesINT);
+ checkOffset("unallocatedSwap", unallocatedSwapINT);
+ checkOffset("cachedMemory", cachedMemoryINT);
+ checkOffset("dirtyMemory", dirtyMemoryINT);
+ checkOffset("cpuNonUser", cpuNonUserINT);
+
+ checkOffset("loopbackPackets", loopbackPacketsLONG);
+ checkOffset("loopbackBytes", loopbackBytesLONG);
+ checkOffset("recvPackets", recvPacketsLONG);
+ checkOffset("recvBytes", recvBytesLONG);
+ checkOffset("recvErrors", recvErrorsLONG);
+ checkOffset("recvDrops", recvDropsLONG);
+ checkOffset("xmitPackets", xmitPacketsLONG);
+ checkOffset("xmitBytes", xmitBytesLONG);
+ checkOffset("xmitErrors", xmitErrorsLONG);
+ checkOffset("xmitDrops", xmitDropsLONG);
+ checkOffset("xmitCollisions", xmitCollisionsLONG);
+ checkOffset("contextSwitches", contextSwitchesLONG);
+ checkOffset("processCreates", processCreatesLONG);
+ checkOffset("pagesPagedIn", pagesPagedInLONG);
+ checkOffset("pagesPagedOut", pagesPagedOutLONG);
+ checkOffset("pagesSwappedIn", pagesSwappedInLONG);
+ checkOffset("pagesSwappedOut", pagesSwappedOutLONG);
+ checkOffset("diskReadsCompleted", readsCompletedLONG);
+ checkOffset("diskReadsMerged", readsMergedLONG);
+ checkOffset("diskBytesRead", bytesReadLONG);
+ checkOffset("diskTimeReading", timeReadingLONG);
+ checkOffset("diskWritesCompleted", writesCompletedLONG);
+ checkOffset("diskWritesMerged", writesMergedLONG);
+ checkOffset("diskBytesWritten", bytesWrittenLONG);
+ checkOffset("diskTimeWriting", timeWritingLONG);
+ checkOffset("diskOpsInProgress", iosInProgressLONG);
+ checkOffset("diskTimeInProgress", timeIosInProgressLONG);
+ checkOffset("diskTime", ioTimeLONG);
+
+ checkOffset("loadAverage1", loadAverage1DOUBLE);
+ checkOffset("loadAverage15", loadAverage15DOUBLE);
+ checkOffset("loadAverage5", loadAverage5DOUBLE);
+ }
+
+ private LinuxSystemStats() {
+ // no instances allowed
+ }
+ public static StatisticsType getType() {
+ return myType;
+ }
+}
[10/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OSXProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OSXProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OSXProcessStats.java
new file mode 100644
index 0000000..7af725f
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OSXProcessStats.java
@@ -0,0 +1,87 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.statistics.HostStatHelper;
+import com.gemstone.gemfire.internal.statistics.LocalStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+
+/**
+ * <P>This class provides the interface for statistics about a
+ * Mac OS X operating system process that is using a GemFire system.
+ */
+public class OSXProcessStats
+{
+// private final static int imageSizeINT = 0;
+// private final static int rssSizeINT = 1;
+
+ private final static StatisticsType myType;
+
+ private static void checkOffset(String name, int offset) {
+ int id = myType.nameToId(name);
+ Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
+ }
+
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ myType = f.createType("OSXProcessStats",
+ "Statistics on a OS X process.",
+ new StatisticDescriptor[] {
+ f.createIntGauge("dummyStat",
+ "Placeholder",
+ "megabytes")
+// f.createIntGauge("imageSize",
+// "The size of the process's image in megabytes.",
+// "megabytes"),
+// f.createIntGauge("rssSize",
+// "The size of the process's resident set size in megabytes.",
+// "megabytes"),
+ });
+// checkOffset("imageSize", imageSizeINT);
+// checkOffset("rssSize", rssSizeINT);
+ }
+
+ private OSXProcessStats() {
+ // no instances allowed
+ }
+ public static StatisticsType getType() {
+ return myType;
+ }
+
+ /**
+ * Returns a <code>ProcessStats</code> that wraps OS X process
+ * <code>Statistics</code>.
+ *
+ * @since GemFire 3.5
+ */
+ public static ProcessStats createProcessStats(final Statistics stats) { // TODO: was package-protected
+ if (stats instanceof LocalStatisticsImpl) {
+ HostStatHelper.refresh((LocalStatisticsImpl) stats);
+ } // otherwise its a Dummy implementation so do nothing
+ return new ProcessStats(stats) {
+ @Override
+ public long getProcessSize() {
+// return stats.getInt(rssSizeINT);
+ return 0L;
+ }
+ };
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OSXSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OSXSystemStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OSXSystemStats.java
new file mode 100644
index 0000000..3f782bc
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OSXSystemStats.java
@@ -0,0 +1,230 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+
+/**
+ * <P>This class provides the interface for statistics about the
+ * OS X machine a GemFire system is running on.
+ */
+public class OSXSystemStats
+{
+
+ // shared fields
+// private final static int allocatedSwapINT = 0;
+// private final static int bufferMemoryINT = 1;
+// private final static int contextSwitchesINT = 2;
+// private final static int cpuActiveINT = 3;
+// private final static int cpuIdleINT = 4;
+// private final static int cpuNiceINT = 5;
+// private final static int cpuSystemINT = 6;
+// private final static int cpuUserINT = 7;
+// private final static int cpusINT = 8;
+// private final static int freeMemoryINT = 9;
+// private final static int pagesPagedInINT = 10;
+// private final static int pagesPagedOutINT = 11;
+// private final static int pagesSwappedInINT = 12;
+// private final static int pagesSwappedOutINT = 13;
+// private final static int physicalMemoryINT = 14;
+// private final static int processCreatesINT = 15;
+// private final static int processesINT = 16;
+// private final static int sharedMemoryINT = 17;
+// private final static int unallocatedSwapINT = 18;
+//
+// private final static int loopbackPacketsLONG = 0;
+// private final static int loopbackBytesLONG = 1;
+// private final static int recvPacketsLONG = 2;
+// private final static int recvBytesLONG = 3;
+// private final static int recvErrorsLONG = 4;
+// private final static int recvDropsLONG = 5;
+// private final static int xmitPacketsLONG = 6;
+// private final static int xmitBytesLONG = 7;
+// private final static int xmitErrorsLONG = 8;
+// private final static int xmitDropsLONG = 9;
+// private final static int xmitCollisionsLONG = 10;
+//
+// private final static int loadAverage1DOUBLE = 0;
+// private final static int loadAverage15DOUBLE = 1;
+// private final static int loadAverage5DOUBLE = 2;
+
+ private final static StatisticsType myType;
+
+ private static void checkOffset(String name, int offset) {
+ int id = myType.nameToId(name);
+ Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
+ }
+
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ myType = f.createType("OSXSystemStats",
+ "Statistics on an OS X machine.",
+ new StatisticDescriptor[] {
+ f.createIntGauge("dummyStat",
+ "Place holder statistic until Stats are implimented for the Mac OS X Platform.",
+ "megabytes"),
+// f.createIntGauge("allocatedSwap",
+// "The number of megabytes of swap space have actually been written to. Swap space must be reserved before it can be allocated.",
+// "megabytes"),
+// f.createIntGauge("bufferMemory",
+// "The number of megabytes of memory allocated to buffers.",
+// "megabytes"),
+// f.createIntCounter("contextSwitches",
+// "The total number of context switches from one thread to another on the computer. Thread switches can occur either inside of a single process or across processes. A thread switch may be caused either by one thread asking another for information, or by a thread being preempted by another, higher priority thread becoming ready to run.",
+// "operations", false),
+// f.createIntGauge("cpuActive",
+// "The percentage of the total available time that has been used in a non-idle state.",
+// "%"),
+// f.createIntGauge("cpuIdle",
+// "The percentage of the total available time that has been spent sleeping.",
+// "%", true),
+// f.createIntGauge("cpuNice",
+// "The percentage of the total available time that has been used to execute user code in processes with low priority.",
+// "%"),
+// f.createIntGauge("cpuSystem",
+// "The percentage of the total available time that has been used to execute system (i.e. kernel) code.",
+// "%"),
+// f.createIntGauge("cpuUser",
+// "The percentage of the total available time that has been used to execute user code.",
+// "%"),
+// f.createIntGauge("cpus",
+// "The number of online cpus on the local machine.",
+// "items"),
+// f.createIntGauge("freeMemory",
+// "The number of megabytes of unused memory on the machine.",
+// "megabytes", true),
+// f.createIntCounter("pagesPagedIn",
+// "The total number of pages that have been brought into memory from disk by the operating system's memory manager.",
+// "pages", false),
+// f.createIntCounter("pagesPagedOut",
+// "The total number of pages that have been flushed from memory to disk by the operating system's memory manager.",
+// "pages", false),
+// f.createIntCounter("pagesSwappedIn",
+// "The total number of swap pages that have been read in from disk by the operating system's memory manager.",
+// "pages", false),
+// f.createIntCounter("pagesSwappedOut",
+// "The total number of swap pages that have been written out to disk by the operating system's memory manager.",
+// "pages", false),
+// f.createIntGauge("physicalMemory",
+// "The actual amount of total physical memory on the machine.",
+// "megabytes", true),
+// f.createIntCounter("processCreates",
+// "The total number of times a process has been created.",
+// "operations", false),
+// f.createIntGauge("processes",
+// "The number of processes in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Each process represents the running of a program.",
+// "processes"),
+// f.createIntGauge("sharedMemory",
+// "The number of megabytes of shared memory on the machine.",
+// "megabytes", true),
+// f.createIntGauge("unallocatedSwap",
+// "The number of megabytes of swap space that have not been allocated.",
+// "megabytes", true),
+//
+// f.createLongCounter("loopbackPackets",
+// "The number of network packets sent (or received) on the loopback interface",
+// "packets", false),
+// f.createLongCounter("loopbackBytes",
+// "The number of network bytes sent (or received) on the loopback interface",
+// "bytes", false),
+// f.createLongCounter("recvPackets",
+// "The total number of network packets received (excluding loopback)",
+// "packets", false),
+// f.createLongCounter("recvBytes",
+// "The total number of network bytes received (excluding loopback)",
+// "bytes", false),
+// f.createLongCounter("recvErrors",
+// "The total number of network receive errors",
+// "errors", false),
+// f.createLongCounter("recvDrops",
+// "The total number network receives dropped",
+// "packets", false),
+// f.createLongCounter("xmitPackets",
+// "The total number of network packets transmitted (excluding loopback)",
+// "packets", false),
+// f.createLongCounter("xmitBytes",
+// "The total number of network bytes transmitted (excluding loopback)",
+// "bytes", false),
+// f.createLongCounter("xmitErrors",
+// "The total number of network transmit errors",
+// "errors", false),
+// f.createLongCounter("xmitDrops",
+// "The total number of network transmits dropped",
+// "packets", false),
+// f.createLongCounter("xmitCollisions",
+// "The total number of network transmit collisions",
+// "collisions", false),
+//
+//
+// f.createDoubleGauge("loadAverage1",
+// "The average number of threads in the run queue or waiting for disk I/O over the last minute.",
+// "threads"),
+// f.createDoubleGauge("loadAverage15",
+// "The average number of threads in the run queue or waiting for disk I/O over the last fifteen minutes.",
+// "threads"),
+// f.createDoubleGauge("loadAverage5",
+// "The average number of threads in the run queue or waiting for disk I/O over the last five minutes.",
+// "threads"),
+ });
+
+// checkOffset("allocatedSwap", allocatedSwapINT);
+// checkOffset("bufferMemory", bufferMemoryINT);
+// checkOffset("contextSwitches", contextSwitchesINT);
+// checkOffset("cpuActive", cpuActiveINT);
+// checkOffset("cpuIdle", cpuIdleINT);
+// checkOffset("cpuNice", cpuNiceINT);
+// checkOffset("cpuSystem", cpuSystemINT);
+// checkOffset("cpuUser", cpuUserINT);
+// checkOffset("cpus", cpusINT);
+// checkOffset("freeMemory", freeMemoryINT);
+// checkOffset("pagesPagedIn", pagesPagedInINT);
+// checkOffset("pagesPagedOut", pagesPagedOutINT);
+// checkOffset("pagesSwappedIn", pagesSwappedInINT);
+// checkOffset("pagesSwappedOut", pagesSwappedOutINT);
+// checkOffset("physicalMemory", physicalMemoryINT);
+// checkOffset("processCreates", processCreatesINT);
+// checkOffset("processes", processesINT);
+// checkOffset("sharedMemory", sharedMemoryINT);
+// checkOffset("unallocatedSwap", unallocatedSwapINT);
+//
+// checkOffset("loopbackPackets", loopbackPacketsLONG);
+// checkOffset("loopbackBytes", loopbackBytesLONG);
+// checkOffset("recvPackets", recvPacketsLONG);
+// checkOffset("recvBytes", recvBytesLONG);
+// checkOffset("recvErrors", recvErrorsLONG);
+// checkOffset("recvDrops", recvDropsLONG);
+// checkOffset("xmitPackets", xmitPacketsLONG);
+// checkOffset("xmitBytes", xmitBytesLONG);
+// checkOffset("xmitErrors", xmitErrorsLONG);
+// checkOffset("xmitDrops", xmitDropsLONG);
+// checkOffset("xmitCollisions", xmitCollisionsLONG);
+//
+// checkOffset("loadAverage1", loadAverage1DOUBLE);
+// checkOffset("loadAverage15", loadAverage15DOUBLE);
+// checkOffset("loadAverage5", loadAverage5DOUBLE);
+ }
+
+ private OSXSystemStats() {
+ // no instances allowed
+ }
+ public static StatisticsType getType() {
+ return myType;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OsStatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OsStatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OsStatisticsFactory.java
new file mode 100644
index 0000000..0ec1f5a
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/OsStatisticsFactory.java
@@ -0,0 +1,41 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+
+/**
+ * Instances of this interface provide methods that create operating system
+ * instances of {@link com.gemstone.gemfire.Statistics}. Its for internal use
+ * only.
+ *
+ * {@link com.gemstone.gemfire.distributed.DistributedSystem} is an OS
+ * statistics factory.
+ * <P>
+ * @see <A href="package-summary.html#statistics">Package introduction</A>
+ *
+ *
+ * @since GemFire 3.0
+ */
+public interface OsStatisticsFactory {
+ /**
+ * Creates and returns a OS {@link Statistics} instance of the given {@link StatisticsType type}, <code>textId</code>, <code>numericId</code>, and <code>osStatFlags</code>..
+ * <p>
+ * The created instance may not be {@link Statistics#isAtomic atomic}.
+ */
+ public Statistics createOsStatistics(StatisticsType type, String textId, long numericId, int osStatFlags);
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/ProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/ProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/ProcessStats.java
new file mode 100644
index 0000000..0c4465e
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/ProcessStats.java
@@ -0,0 +1,60 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.Statistics;
+
+/**
+ * Abstracts the process statistics that are common on all platforms.
+ * This is necessary for monitoring the health of GemFire components.
+ *
+ *
+ * @since GemFire 3.5
+ * */
+public abstract class ProcessStats {
+
+ /** The underlying statistics */
+ private final Statistics stats;
+
+ /**
+ * Creates a new <code>ProcessStats</code> that wraps the given
+ * <code>Statistics</code>.
+ */
+ ProcessStats(Statistics stats) {
+ this.stats = stats;
+ }
+
+ /**
+ * Closes these process stats
+ *
+ * @see Statistics#close
+ */
+ public final void close() {
+ this.stats.close();
+ }
+
+ public final Statistics getStatistics() {
+ return this.stats;
+ }
+
+ /**
+ * Returns the size of this process (resident set on UNIX or working
+ * set on Windows) in megabytes
+ */
+ public abstract long getProcessSize();
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/SolarisProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/SolarisProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/SolarisProcessStats.java
new file mode 100644
index 0000000..c9b6746
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/SolarisProcessStats.java
@@ -0,0 +1,222 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.statistics.HostStatHelper;
+import com.gemstone.gemfire.internal.statistics.LocalStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
+
+/**
+ * <P>This class provides the interface for statistics about a
+ * Solaris operating system process that is using a GemFire system.
+ */
+public class SolarisProcessStats
+{
+ private final static int allOtherSleepTimeINT = 0;
+ private final static int characterIoINT = 1;
+ private final static int dataFaultSleepTimeINT = 2;
+ private final static int heapSizeINT = 3;
+ private final static int imageSizeINT = 4;
+ private final static int involContextSwitchesINT = 5;
+ private final static int kernelFaultSleepTimeINT = 6;
+ private final static int lockWaitSleepTimeINT = 7;
+ private final static int lwpCurCountINT = 8;
+ private final static int lwpTotalCountINT = 9;
+ private final static int majorFaultsINT = 10;
+ private final static int messagesRecvINT = 11;
+ private final static int messagesSentINT = 12;
+ private final static int minorFaultsINT = 13;
+ private final static int rssSizeINT = 14;
+ private final static int signalsReceivedINT = 15;
+ private final static int systemCallsINT = 16;
+ private final static int stackSizeINT = 17;
+ private final static int stoppedTimeINT = 18;
+ private final static int systemTimeINT = 19;
+ private final static int textFaultSleepTimeINT = 20;
+ private final static int trapTimeINT = 21;
+ private final static int userTimeINT = 22;
+ private final static int volContextSwitchesINT = 23;
+ private final static int waitCpuTimeINT = 24;
+
+ private final static int activeTimeLONG = 0;
+
+ private final static int cpuUsedDOUBLE = 0;
+ private final static int memoryUsedDOUBLE = 1;
+
+ private final static StatisticsType myType;
+
+ private static void checkOffset(String name, int offset) {
+ int id = myType.nameToId(name);
+ Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
+ }
+
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ myType = f.createType("SolarisProcessStats",
+ "Statistics on a Solaris process.",
+ new StatisticDescriptor[] {
+ f.createIntCounter("allOtherSleepTime",
+ "The number of milliseconds the process has been sleeping for some reason not tracked by any other stat. Note that all lwp's contribute to this stat's value so check lwpCurCount to understand large values.",
+ "milliseconds", false),
+ f.createIntCounter("characterIo",
+ "The number of characters read and written.",
+ "bytes"),
+ f.createIntCounter("dataFaultSleepTime",
+ "The number of milliseconds the process has been faulting in data pages.",
+ "milliseconds", false),
+ f.createIntGauge("heapSize",
+ "The size of the process's heap in megabytes.",
+ "megabytes"),
+ f.createIntGauge("imageSize",
+ "The size of the process's image in megabytes.",
+ "megabytes"),
+ f.createIntCounter("involContextSwitches",
+ "The number of times the process was forced to do a context switch.",
+ "operations", false),
+ f.createIntCounter("kernelFaultSleepTime",
+ "The number of milliseconds the process has been faulting in kernel pages.",
+ "milliseconds", false),
+ f.createIntCounter("lockWaitSleepTime",
+ "The number of milliseconds the process has been waiting for a user lock. Note that all lwp's contribute to this stat's value so check lwpCurCount to understand large values.",
+ "milliseconds", false),
+ f.createIntGauge("lwpCurCount",
+ "The current number of light weight processes that exist in the process.",
+ "threads"),
+ f.createIntCounter("lwpTotalCount",
+ "The total number of light weight processes that have ever contributed to the process's statistics.",
+ "threads", false),
+ f.createIntCounter("majorFaults",
+ "The number of times the process has had a page fault that needed disk access.",
+ "operations", false),
+ f.createIntCounter("messagesRecv",
+ "The number of messages received by the process.",
+ "messages"),
+ f.createIntCounter("messagesSent",
+ "The number of messages sent by the process.",
+ "messages"),
+ f.createIntCounter("minorFaults",
+ "The number of times the process has had a page fault that did not need disk access.",
+ "operations", false),
+ f.createIntGauge("rssSize",
+ "The size of the process's resident set size in megabytes.",
+ "megabytes"),
+ f.createIntCounter("signalsReceived",
+ "The total number of operating system signals this process has received.",
+ "signals", false),
+ f.createIntCounter("systemCalls",
+ "The total number system calls done by this process.",
+ "operations"),
+ f.createIntGauge("stackSize",
+ "The size of the process's stack in megabytes.",
+ "megabytes"),
+ f.createIntCounter("stoppedTime",
+ "The number of milliseconds the process has been stopped.",
+ "milliseconds", false),
+ f.createIntCounter("systemTime",
+ "The number of milliseconds the process has been using the CPU to execute system calls.",
+ "milliseconds", false),
+ f.createIntCounter("textFaultSleepTime",
+ "The number of milliseconds the process has been faulting in text pages.",
+ "milliseconds", false),
+ f.createIntCounter("trapTime",
+ "The number of milliseconds the process has been in system traps.",
+ "milliseconds", false),
+ f.createIntCounter("userTime",
+ "The number of milliseconds the process has been using the CPU to execute user code.",
+ "milliseconds", false),
+ f.createIntCounter("volContextSwitches",
+ "The number of voluntary context switches done by the process.",
+ "operations", false),
+ f.createIntCounter("waitCpuTime",
+ "The number of milliseconds the process has been waiting for a CPU due to latency.",
+ "milliseconds", false),
+
+
+ f.createLongCounter("activeTime",
+ "The number of milliseconds the process has been using the CPU to execute user or system code.",
+ "milliseconds", false),
+
+
+ f.createDoubleGauge("cpuUsed",
+ "The percentage of recent cpu time used by the process.",
+ "%"),
+ f.createDoubleGauge("memoryUsed",
+ "The percentage of real memory used by the process.",
+ "%")
+ });
+
+ checkOffset("allOtherSleepTime", allOtherSleepTimeINT);
+ checkOffset("characterIo", characterIoINT);
+ checkOffset("dataFaultSleepTime", dataFaultSleepTimeINT);
+ checkOffset("heapSize", heapSizeINT);
+ checkOffset("imageSize", imageSizeINT);
+ checkOffset("involContextSwitches", involContextSwitchesINT);
+ checkOffset("kernelFaultSleepTime", kernelFaultSleepTimeINT);
+ checkOffset("lockWaitSleepTime", lockWaitSleepTimeINT);
+ checkOffset("lwpCurCount", lwpCurCountINT);
+ checkOffset("lwpTotalCount", lwpTotalCountINT);
+ checkOffset("majorFaults", majorFaultsINT);
+ checkOffset("messagesRecv", messagesRecvINT);
+ checkOffset("messagesSent", messagesSentINT);
+ checkOffset("minorFaults", minorFaultsINT);
+ checkOffset("rssSize", rssSizeINT);
+ checkOffset("signalsReceived", signalsReceivedINT);
+ checkOffset("systemCalls", systemCallsINT);
+ checkOffset("stackSize", stackSizeINT);
+ checkOffset("stoppedTime", stoppedTimeINT);
+ checkOffset("systemTime", systemTimeINT);
+ checkOffset("textFaultSleepTime", textFaultSleepTimeINT);
+ checkOffset("trapTime", trapTimeINT);
+ checkOffset("userTime", userTimeINT);
+ checkOffset("volContextSwitches", volContextSwitchesINT);
+ checkOffset("waitCpuTime", waitCpuTimeINT);
+
+ checkOffset("activeTime", activeTimeLONG);
+
+ checkOffset("cpuUsed", cpuUsedDOUBLE);
+ checkOffset("memoryUsed", memoryUsedDOUBLE);
+ }
+
+ private SolarisProcessStats() {
+ // no instances allowed
+ }
+ public static StatisticsType getType() {
+ return myType;
+ }
+
+ /**
+ * Returns a <code>ProcessStats</code> that wraps Solaris process
+ * <code>Statistics</code>.
+ *
+ * @since GemFire 3.5
+ */
+ public static ProcessStats createProcessStats(final Statistics stats) { // TODO: was package-protected
+ if (stats instanceof LocalStatisticsImpl) {
+ HostStatHelper.refresh((LocalStatisticsImpl) stats);
+ } // otherwise its a Dummy implementation so do nothing
+ return new ProcessStats(stats) {
+ @Override
+ public long getProcessSize() {
+ return stats.getInt(rssSizeINT);
+ }
+ };
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/SolarisSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/SolarisSystemStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/SolarisSystemStats.java
new file mode 100644
index 0000000..3fe4495
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/SolarisSystemStats.java
@@ -0,0 +1,430 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+
+/**
+ * <P>This class provides the interface for statistics about the
+ * Solaris machine a GemFire system is running on.
+ */
+public class SolarisSystemStats
+{
+ private final static int allocatedSwapINT = 0;
+ private final static int cpuActiveINT = 1;
+ private final static int cpuIdleINT = 2;
+ private final static int cpuIoWaitINT = 3;
+ private final static int cpuSwapWaitINT = 4;
+ private final static int cpuSystemINT = 5;
+ private final static int cpuUserINT = 6;
+ private final static int cpuWaitingINT = 7;
+ private final static int cpusINT = 8;
+ private final static int freeMemoryINT = 9;
+ private final static int physicalMemoryINT = 10;
+ private final static int processesINT = 11;
+ private final static int reservedSwapINT = 12;
+ private final static int schedulerRunCountINT = 13;
+ private final static int schedulerSwapCountINT = 14;
+ private final static int schedulerWaitCountINT = 15;
+ private final static int unreservedSwapINT = 16;
+ private final static int unallocatedSwapINT = 17;
+
+ private final static int anonymousPagesFreedLONG = 0;
+ private final static int anonymousPagesPagedInLONG = 1;
+ private final static int anonymousPagesPagedOutLONG = 2;
+ private final static int contextSwitchesLONG = 3;
+ private final static int execPagesFreedLONG = 4;
+ private final static int execPagesPagedInLONG = 5;
+ private final static int execPagesPagedOutLONG = 6;
+ private final static int failedMutexEntersLONG = 7;
+ private final static int failedReaderLocksLONG = 8;
+ private final static int failedWriterLocksLONG = 9;
+ private final static int fileSystemPagesFreedLONG = 10;
+ private final static int fileSystemPagesPagedInLONG = 11;
+ private final static int fileSystemPagesPagedOutLONG = 12;
+ private final static int hatMinorFaultsLONG = 13;
+ private final static int interruptsLONG = 14;
+ private final static int involContextSwitchesLONG = 15;
+ private final static int majorPageFaultsLONG = 16;
+ private final static int messageCountLONG = 17;
+ private final static int pageDaemonCyclesLONG = 18;
+ private final static int pageInsLONG = 19;
+ private final static int pageOutsLONG = 20;
+ private final static int pagerRunsLONG = 21;
+ private final static int pagesPagedInLONG = 22;
+ private final static int pagesPagedOutLONG = 23;
+ private final static int pagesScannedLONG = 24;
+ private final static int procsInIoWaitLONG = 25;
+ private final static int protectionFaultsLONG = 26;
+ private final static int semphoreOpsLONG = 27;
+ private final static int softwareLockFaultsLONG = 28;
+ private final static int systemCallsLONG = 29;
+ private final static int systemMinorFaultsLONG = 30;
+ private final static int threadCreatesLONG = 31;
+ private final static int trapsLONG = 32;
+ private final static int userMinorFaultsLONG = 33;
+ private final static int loopbackInputPacketsLONG = 34;
+ private final static int loopbackOutputPacketsLONG = 35;
+ private final static int inputPacketsLONG = 36;
+ private final static int inputErrorsLONG = 37;
+ private final static int outputPacketsLONG = 38;
+ private final static int outputErrorsLONG = 39;
+ private final static int collisionsLONG = 40;
+ private final static int inputBytesLONG = 41;
+ private final static int outputBytesLONG = 42;
+ private final static int multicastInputPacketsLONG = 43;
+ private final static int multicastOutputPacketsLONG = 44;
+ private final static int broadcastInputPacketsLONG = 45;
+ private final static int broadcastOutputPacketsLONG = 46;
+ private final static int inputPacketsDiscardedLONG = 47;
+ private final static int outputPacketsDiscardedLONG = 48;
+
+ private final static int loadAverage1DOUBLE = 0;
+ private final static int loadAverage15DOUBLE = 1;
+ private final static int loadAverage5DOUBLE = 2;
+
+ private final static StatisticsType myType;
+
+ private static void checkOffset(String name, int offset) {
+ int id = myType.nameToId(name);
+ Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
+ }
+
+ /*
+ "\n Segments ConnectionsEstablished ConnectionsActive"
+ "\n ConnectionsPassive ConnectionFailures ConnectionsReset"
+ "\n SegmentsReceived SegmentsSent SegmentsRetransmitted"
+ "\n SentTcpBytes RetransmittedTcpBytes AcksSent DelayedAcksSent"
+ "\n ControlSegmentsSent"
+ "\n AcksReceived AckedBytes DuplicateAcks AcksForUnsentData "
+ "\n ReceivedInorderBytes ReceivedOutOfOrderBytes ReceivedDuplicateBytes ReceivedPartialDuplicateBytes "
+ "\n RetransmitTimeouts RetransmitTimeoutDrops"
+ "\n KeepAliveTimeouts KeepAliveProbes KeepAliveDrops"
+ "\n ListenQueueFull HalfOpenQueueFull HalfOpenDrops"
+ "\n) ");
+ sprintf(buff, "%d", typeCount);
+ TcpTypeCount = typeCount;
+ typeCount++;
+ strcat(res, buff);
+ }
+
+ */
+
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ myType = f.createType("SolarisSystemStats",
+ "Statistics on a Solaris machine.",
+ new StatisticDescriptor[] {
+ f.createIntGauge("allocatedSwap",
+ "The number of megabytes of swap space have actually been written to. Swap space must be reserved before it can be allocated.",
+ "megabytes"),
+ f.createIntGauge("cpuActive",
+ "The percentage of the total available time that has been used to execute user or system code.",
+ "%"),
+ f.createIntGauge("cpuIdle",
+ "The percentage of the total available time that has been spent sleeping.",
+ "%", true),
+ f.createIntGauge("cpuIoWait",
+ "The percentage of the total available time that has been spent waiting for disk io to complete.",
+ "%"),
+ f.createIntGauge("cpuSwapWait",
+ "The percentage of the total available time that has been spent waiting for paging and swapping to complete.",
+ "%"),
+ f.createIntGauge("cpuSystem",
+ "The percentage of the total available time that has been used to execute system (i.e. kernel) code.",
+ "%"),
+ f.createIntGauge("cpuUser",
+ "The percentage of the total available time that has been used to execute user code.",
+ "%"),
+ f.createIntGauge("cpuWaiting",
+ "The percentage of the total available time that has been spent waiting for io, paging, or swapping.",
+ "%"),
+ f.createIntGauge("cpus",
+ "The number of online cpus on the local machine.",
+ "items"),
+ f.createIntGauge("freeMemory",
+ "The number of megabytes of unused memory on the machine.",
+ "megabytes", true),
+ f.createIntGauge("physicalMemory",
+ "The actual amount of total physical memory on the machine.",
+ "megabytes", true),
+ f.createIntGauge("processes",
+ "The number of processes in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Each process represents the running of a program.",
+ "processes"),
+ f.createIntGauge("reservedSwap",
+ "The number of megabytes of swap space reserved for allocation by a particular process.",
+ "megabytes"),
+ f.createIntCounter("schedulerRunCount",
+ "The total number of times the system scheduler has put a thread in its run queue.",
+ "operations", false),
+ f.createIntCounter("schedulerSwapCount",
+ "The total number of times the system scheduler has swapped out an idle process.",
+ "operations", false),
+ f.createIntCounter("schedulerWaitCount",
+ "The total number of times the system scheduler has removed a thread from the run queue because it was waiting for a resource.",
+ "operations", false),
+ f.createIntGauge("unreservedSwap",
+ "The number of megabytes of swap space that are free. If this value goes to zero new processes can no longer be created.",
+ "megabytes", true),
+ f.createIntGauge("unallocatedSwap",
+ "The number of megabytes of swap space that have not been allocated.",
+ "megabytes", true),
+
+
+ f.createLongCounter("anonymousPagesFreed",
+ "The total number pages that contain heap, stack, or other changeable data that have been removed from memory and added to the free list.",
+ "pages"),
+ f.createLongCounter("anonymousPagesPagedIn",
+ "The total number pages that contain heap, stack, or other changeable data that have been allocated in memory and possibly copied from disk.",
+ "pages", false),
+ f.createLongCounter("anonymousPagesPagedOut",
+ "The total number pages that contain heap, stack, or other changeable data that have been removed from memory and copied to disk.",
+ "pages", false),
+ f.createLongCounter("contextSwitches",
+ "The total number of context switches from one thread to another on the computer. Thread switches can occur either inside of a single process or across processes. A thread switch may be caused either by one thread asking another for information, or by a thread being preempted by another, higher priority thread becoming ready to run.",
+ "operations", false),
+ f.createLongCounter("execPagesFreed",
+ "The total number readonly pages that contain code or data that have been removed from memory and returned to the free list.",
+ "pages"),
+ f.createLongCounter("execPagesPagedIn",
+ "The total number readonly pages that contain code or data that have been copied from disk to memory.",
+ "pages", false),
+ f.createLongCounter("execPagesPagedOut",
+ "The total number readonly pages that contain code or data that have been removed from memory and will need to be paged in when used again.",
+ "pages", false),
+ f.createLongCounter("failedMutexEnters",
+ "The total number of times a thread entering a mutex had to wait for the mutex to be unlocked.",
+ "operations", false),
+ f.createLongCounter("failedReaderLocks",
+ "The total number of times readers failed to obtain a readers/writer locks on their first try. When this happens the reader has to wait for the current writer to release the lock.",
+ "operations", false),
+ f.createLongCounter("failedWriterLocks",
+ "The total number of times writers failed to obtain a readers/writer locks on their first try. When this happens the writer has to wait for all the current readers or the single writer to release the lock.",
+ "operations", false),
+ f.createLongCounter("fileSystemPagesFreed",
+ "The total number of pages, that contained the contents of a file due to the file being read from a file system, that have been removed from memory and put on the free list.",
+ "pages"),
+ f.createLongCounter("fileSystemPagesPagedIn",
+ "The total number of pages that contain the contents of a file due to the file being read from a file system.",
+ "pages", false),
+ f.createLongCounter("fileSystemPagesPagedOut",
+ "The total number of pages, that contained the contents of a file due to the file being read from a file system, that have been removed from memory and copied to disk.",
+ "pages", false),
+ f.createLongCounter("hatMinorFaults",
+ "The total number of hat faults. You only get these on systems with software memory management units.",
+ "operations", false),
+ f.createLongCounter("interrupts",
+ "The total number of interrupts that have occurred on the computer.",
+ "operations", false),
+ f.createLongCounter("involContextSwitches",
+ "The total number of times a thread was forced to give up the cpu even though it was still ready to run.",
+ "operations", false),
+ f.createLongCounter("majorPageFaults",
+ "The total number of times a page fault required disk io to get the page",
+ "operations", false),
+ f.createLongCounter("messageCount",
+ "The total number of msgrcv() and msgsnd() system calls.",
+ "messages"),
+ f.createLongCounter("pageDaemonCycles",
+ "The total number of revolutions of the page daemon's scan \"clock hand\".",
+ "operations", false),
+ f.createLongCounter("pageIns",
+ "The total number of times pages have been brought into memory from disk by the operating system's memory manager.",
+ "operations", false),
+ f.createLongCounter("pageOuts",
+ "The total number of times pages have been flushed from memory to disk by the operating system's memory manager.",
+ "operations", false),
+ f.createLongCounter("pagerRuns",
+ "The total number of times the pager daemon has been scheduled to run.",
+ "operations", false),
+ f.createLongCounter("pagesPagedIn",
+ "The total number of pages that have been brought into memory from disk by the operating system's memory manager.",
+ "pages", false),
+ f.createLongCounter("pagesPagedOut",
+ "The total number of pages that have been flushed from memory to disk by the operating system's memory manager.",
+ "pages", false),
+ f.createLongCounter("pagesScanned",
+ "The total number pages examined by the pageout daemon. When the amount of free memory gets below a certain size, the daemon start to look for inactive memory pages to steal from processes. So I high scan rate is a good indication of needing more memory.",
+ "pages", false),
+ f.createLongGauge("procsInIoWait",
+ "The number of processes waiting for block I/O at this instant in time.",
+ "processes"),
+ f.createLongCounter("protectionFaults",
+ "The total number of times memory has been accessed in a way that was not allowed. This results in a segementation violation and in most cases a core dump.",
+ "operations", false),
+ f.createLongCounter("semphoreOps",
+ "The total number of semaphore operations.",
+ "operations"),
+ f.createLongCounter("softwareLockFaults",
+ "The total number of faults caused by software locks held on memory pages.",
+ "operations", false),
+ f.createLongCounter("systemCalls",
+ "The total number system calls.",
+ "operations"),
+ f.createLongCounter("systemMinorFaults",
+ "The total number of minor page faults in kernel code. Minor page faults do not require disk access.",
+ "operations", false),
+ f.createLongCounter("threadCreates",
+ "The total number of times a thread has been created.",
+ "operations", false),
+ f.createLongCounter("traps",
+ "The total number of traps that have occurred on the computer.",
+ "operations", false),
+ f.createLongCounter("userMinorFaults",
+ "The total number of minor page faults in non-kernel code. Minor page faults do not require disk access.",
+ "operatations", false),
+ f.createLongCounter("loopbackInputPackets",
+ "The total number of input packets received over the loopback network adaptor.",
+ "packets"),
+ f.createLongCounter("loopbackOutputPackets",
+ "The total number of output packets sent over the loopback network adaptor.",
+ "packets"),
+ f.createLongCounter("inputPackets",
+ "packets received (Solaris kstat 'ipackets')",
+ "packets"),
+ f.createLongCounter("inputErrors",
+ "input errors (Solaris kstat 'ierrors')",
+ "errors", false),
+ f.createLongCounter("outputPackets",
+ "Solaris kstat 'opackets'",
+ "packets"),
+ f.createLongCounter("outputErrors",
+ "output errors (Solaris kstat 'oerrors')",
+ "errors", false),
+ f.createLongCounter("collisions",
+ "Solaris kstat 'collisions'",
+ "collisions", false),
+ f.createLongCounter("inputBytes",
+ "octets received (Solaris kstat 'rbytes')",
+ "bytes"),
+ f.createLongCounter("outputBytes",
+ "octats transmitted (Solaris kstat 'obytes')",
+ "bytes"),
+ f.createLongCounter("multicastInputPackets",
+ "multicast received (Solaris kstat 'multircv')",
+ "packets"),
+ f.createLongCounter("multicastOutputPackets",
+ "multicast requested to be sent (Solaris kstat 'multixmt')",
+ "packets"),
+ f.createLongCounter("broadcastInputPackets",
+ "broadcast received (Solaris kstat 'brdcstrcv')",
+ "packets"),
+ f.createLongCounter("broadcastOutputPackets",
+ "broadcast requested to be sent (Solaris kstat 'brdcstxmt')",
+ "packets"),
+ f.createLongCounter("inputPacketsDiscarded",
+ "number receive packets discarded (Solaris kstat 'norcvbuf')",
+ "packets"),
+ f.createLongCounter("outputPacketsDiscarded",
+ "packets that could not be sent up because the queue was flow controlled (Solaris kstat 'noxmtbuf')",
+ "packets"),
+
+
+ f.createDoubleGauge("loadAverage1",
+ "The average number of threads ready to run over the last minute.",
+ "threads"),
+ f.createDoubleGauge("loadAverage15",
+ "The average number of threads ready to run over the last fifteen minutes.",
+ "threads"),
+ f.createDoubleGauge("loadAverage5",
+ "The average number of threads ready to run over the last five minutes.",
+ "threads")
+ });
+ checkOffset("allocatedSwap", allocatedSwapINT);
+ checkOffset("cpuActive", cpuActiveINT);
+ checkOffset("cpuIdle", cpuIdleINT);
+ checkOffset("cpuIoWait", cpuIoWaitINT);
+ checkOffset("cpuSwapWait", cpuSwapWaitINT);
+ checkOffset("cpuSystem", cpuSystemINT);
+ checkOffset("cpuUser", cpuUserINT);
+ checkOffset("cpuWaiting", cpuWaitingINT);
+ checkOffset("cpus", cpusINT);
+ checkOffset("freeMemory", freeMemoryINT);
+ checkOffset("physicalMemory", physicalMemoryINT);
+ checkOffset("processes", processesINT);
+ checkOffset("reservedSwap", reservedSwapINT);
+ checkOffset("schedulerRunCount", schedulerRunCountINT);
+ checkOffset("schedulerSwapCount", schedulerSwapCountINT);
+ checkOffset("schedulerWaitCount", schedulerWaitCountINT);
+ checkOffset("unreservedSwap", unreservedSwapINT);
+ checkOffset("unallocatedSwap", unallocatedSwapINT);
+
+ checkOffset("anonymousPagesFreed", anonymousPagesFreedLONG);
+ checkOffset("anonymousPagesPagedIn", anonymousPagesPagedInLONG);
+ checkOffset("anonymousPagesPagedOut", anonymousPagesPagedOutLONG);
+ checkOffset("contextSwitches", contextSwitchesLONG);
+ checkOffset("execPagesFreed", execPagesFreedLONG);
+ checkOffset("execPagesPagedIn", execPagesPagedInLONG);
+ checkOffset("execPagesPagedOut", execPagesPagedOutLONG);
+ checkOffset("failedMutexEnters", failedMutexEntersLONG);
+ checkOffset("failedReaderLocks", failedReaderLocksLONG);
+ checkOffset("failedWriterLocks", failedWriterLocksLONG);
+ checkOffset("fileSystemPagesFreed", fileSystemPagesFreedLONG);
+ checkOffset("fileSystemPagesPagedIn", fileSystemPagesPagedInLONG);
+ checkOffset("fileSystemPagesPagedOut", fileSystemPagesPagedOutLONG);
+ checkOffset("hatMinorFaults", hatMinorFaultsLONG);
+ checkOffset("interrupts", interruptsLONG);
+ checkOffset("involContextSwitches", involContextSwitchesLONG);
+ checkOffset("majorPageFaults", majorPageFaultsLONG);
+ checkOffset("messageCount", messageCountLONG);
+ checkOffset("pageDaemonCycles", pageDaemonCyclesLONG);
+ checkOffset("pageIns", pageInsLONG);
+ checkOffset("pageOuts", pageOutsLONG);
+ checkOffset("pagerRuns", pagerRunsLONG);
+ checkOffset("pagesPagedIn", pagesPagedInLONG);
+ checkOffset("pagesPagedOut", pagesPagedOutLONG);
+ checkOffset("pagesScanned", pagesScannedLONG);
+ checkOffset("procsInIoWait", procsInIoWaitLONG);
+ checkOffset("protectionFaults", protectionFaultsLONG);
+ checkOffset("semphoreOps", semphoreOpsLONG);
+ checkOffset("softwareLockFaults", softwareLockFaultsLONG);
+ checkOffset("systemCalls", systemCallsLONG);
+ checkOffset("systemMinorFaults", systemMinorFaultsLONG);
+ checkOffset("threadCreates", threadCreatesLONG);
+ checkOffset("traps", trapsLONG);
+ checkOffset("userMinorFaults", userMinorFaultsLONG);
+ checkOffset("loopbackInputPackets", loopbackInputPacketsLONG);
+ checkOffset("loopbackOutputPackets", loopbackOutputPacketsLONG);
+ checkOffset("inputPackets", inputPacketsLONG);
+ checkOffset("inputErrors", inputErrorsLONG);
+ checkOffset("outputPackets", outputPacketsLONG);
+ checkOffset("outputErrors", outputErrorsLONG);
+ checkOffset("collisions", collisionsLONG);
+ checkOffset("inputBytes", inputBytesLONG);
+ checkOffset("outputBytes", outputBytesLONG);
+ checkOffset("multicastInputPackets", multicastInputPacketsLONG);
+ checkOffset("multicastOutputPackets", multicastOutputPacketsLONG);
+ checkOffset("broadcastInputPackets", broadcastInputPacketsLONG);
+ checkOffset("broadcastOutputPackets", broadcastOutputPacketsLONG);
+ checkOffset("inputPacketsDiscarded", inputPacketsDiscardedLONG);
+ checkOffset("outputPacketsDiscarded", outputPacketsDiscardedLONG);
+
+ checkOffset("loadAverage1", loadAverage1DOUBLE);
+ checkOffset("loadAverage15", loadAverage15DOUBLE);
+ checkOffset("loadAverage5", loadAverage5DOUBLE);
+ }
+
+ private SolarisSystemStats() {
+ // no instances allowed
+ }
+ public static StatisticsType getType() {
+ return myType;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/WindowsProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/WindowsProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/WindowsProcessStats.java
new file mode 100644
index 0000000..5082316
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/WindowsProcessStats.java
@@ -0,0 +1,165 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.statistics.HostStatHelper;
+import com.gemstone.gemfire.internal.statistics.LocalStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
+
+/**
+ * <P>This class provides the interface for statistics about a
+ * windows operating system process that is using a GemFire system.
+ */
+public class WindowsProcessStats
+{
+ private final static int handlesINT = 0;
+ private final static int priorityBaseINT = 1;
+ private final static int threadsINT = 2;
+
+ private final static int activeTimeLONG = 0;
+ private final static int pageFaultsLONG = 1;
+ private final static int pageFileSizeLONG = 2;
+ private final static int pageFileSizePeakLONG = 3;
+ private final static int privateSizeLONG = 4;
+ private final static int systemTimeLONG = 5;
+ private final static int userTimeLONG = 6;
+ private final static int virtualSizeLONG = 7;
+ private final static int virtualSizePeakLONG = 8;
+ private final static int workingSetSizeLONG = 9;
+ private final static int workingSetSizePeakLONG = 10;
+
+ private final static StatisticsType myType;
+
+ private static void checkOffset(String name, int offset) {
+ int id = myType.nameToId(name);
+ Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
+ }
+
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ myType = f
+ .createType(
+ "WindowsProcessStats",
+ "Statistics on a Microsoft Window's process.",
+ new StatisticDescriptor[] {
+ f.createIntGauge(
+ "handles",
+ "The total number of handles currently open by this process. This number is the sum of the handles currently open by each thread in this process.",
+ "items"),
+ f.createIntGauge(
+ "priorityBase",
+ "The current base priority of the process. Threads within a process can raise and lower their own base priority relative to the process's base priority",
+ "priority"),
+ f.createIntGauge(
+ "threads",
+ "Number of threads currently active in this process. An instruction is the basic unit of execution in a processor, and a thread is the object that executes instructions. Every running process has at least one thread.",
+ "threads"),
+
+ f.createLongCounter(
+ "activeTime",
+ "The elapsed time in milliseconds that all of the threads of this process used the processor to execute instructions. An instruction is the basic unit of execution in a computer, a thread is the object that executes instructions, and a process is the object created when a program is run. Code executed to handle some hardware interrupts and trap conditions are included in this count.",
+ "milliseconds", false),
+
+ f.createLongCounter(
+ "pageFaults",
+ "The total number of Page Faults by the threads executing in this process. A page fault occurs when a thread refers to a virtual memory page that is not in its working set in main memory. This will not cause the page to be fetched from disk if it is on the standby list and hence already in main memory, or if it is in use by another process with whom the page is shared.",
+ "operations", false),
+ f.createLongGauge(
+ "pageFileSize",
+ "The current number of bytes this process has used in the paging file(s). Paging files are used to store pages of memory used by the process that are not contained in other files. Paging files are shared by all processes, and lack of space in paging files can prevent other processes from allocating memory.",
+ "bytes"),
+ f.createLongGauge(
+ "pageFileSizePeak",
+ "The maximum number of bytes this process has used in the paging file(s). Paging files are used to store pages of memory used by the process that are not contained in other files. Paging files are shared by all processes, and lack of space in paging files can prevent other processes from allocating memory.",
+ "bytes"),
+ f.createLongGauge(
+ "privateSize",
+ "The current number of bytes this process has allocated that cannot be shared with other processes.",
+ "bytes"),
+ f.createLongCounter(
+ "systemTime",
+ "The elapsed time in milliseconds that the threads of the process have spent executing code in privileged mode. When a Windows system service is called, the service will often run in Privileged Mode to gain access to system-private data. Such data is protected from access by threads executing in user mode. Calls to the system can be explicit or implicit, such as page faults or interrupts. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of user and privileged modes. These subsystem processes provide additional protection. Therefore, some work done by Windows on behalf of your application might appear in other subsystem processes in addition to the privileged time in your process.",
+ "milliseconds", false),
+ f.createLongCounter(
+ "userTime",
+ "The elapsed time in milliseconds that this process's threads have spent executing code in user mode. Applications, environment subsystems, and integral subsystems execute in user mode. Code executing in User Mode cannot damage the integrity of the Windows Executive, Kernel, and device drivers. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of user and privileged modes. These subsystem processes provide additional protection. Therefore, some work done by Windows on behalf of your application might appear in other subsystem processes in addition to the privileged time in your process.",
+ "milliseconds", false),
+ f.createLongGauge(
+ "virtualSize",
+ "Virtual Bytes is the current size in bytes of the virtual address space the process is using. Use of virtual address space does not necessarily imply corresponding use of either disk or main memory pages. Virtual space is finite, and by using too much, the process can limit its ability to load libraries.",
+ "bytes"),
+ f.createLongGauge(
+ "virtualSizePeak",
+ "The maximum number of bytes of virtual address space the process has used at any one time. Use of virtual address space does not necessarily imply corresponding use of either disk or main memory pages. Virtual space is however finite, and by using too much, the process might limit its ability to load libraries.",
+ "bytes"),
+ f.createLongGauge(
+ "workingSetSize",
+ "The current number of bytes in the Working Set of this process. The Working Set is the set of memory pages touched recently by the threads in the process. If free memory in the computer is above a threshold, pages are left in the Working Set of a process even if they are not in use. When free memory falls below a threshold, pages are trimmed from Working Sets. If they are needed they will then be soft-faulted back into the Working Set before they are paged out out to disk.",
+ "bytes"),
+ f.createLongGauge(
+ "workingSetSizePeak",
+ "The maximum number of bytes in the Working Set of this process at any point in time. The Working Set is the set of memory pages touched recently by the threads in the process. If free memory in the computer is above a threshold, pages are left in the Working Set of a process even if they are not in use. When free memory falls below a threshold, pages are trimmed from Working Sets. If they are needed they will then be soft-faulted back into the Working Set before they leave main memory.",
+ "bytes"),
+
+ });
+ checkOffset("handles", handlesINT);
+ checkOffset("priorityBase", priorityBaseINT);
+ checkOffset("threads", threadsINT);
+
+ checkOffset("activeTime", activeTimeLONG);
+ checkOffset("pageFaults", pageFaultsLONG);
+ checkOffset("pageFileSize", pageFileSizeLONG);
+ checkOffset("pageFileSizePeak", pageFileSizePeakLONG);
+ checkOffset("privateSize", privateSizeLONG);
+ checkOffset("systemTime", systemTimeLONG);
+ checkOffset("userTime", userTimeLONG);
+ checkOffset("virtualSize", virtualSizeLONG);
+ checkOffset("virtualSizePeak", virtualSizePeakLONG);
+ checkOffset("workingSetSize", workingSetSizeLONG);
+ checkOffset("workingSetSizePeak", workingSetSizePeakLONG);
+ }
+
+ private WindowsProcessStats() {
+ // no instances allowed
+ }
+ public static StatisticsType getType() {
+ return myType;
+ }
+
+ /**
+ * Returns a <code>ProcessStats</code> that wraps Windows process
+ * <code>Statistics</code>.
+ *
+ * @since GemFire 3.5
+ */
+ public static ProcessStats createProcessStats(final Statistics stats) { // TODO: was package-protected
+ if (stats instanceof LocalStatisticsImpl) {
+ HostStatHelper.refresh((LocalStatisticsImpl) stats);
+ } // otherwise its a Dummy implementation so do nothing
+ return new ProcessStats(stats) {
+ @Override
+ public long getProcessSize() {
+ return stats.getLong(workingSetSizeLONG) / (1024*1024);
+ }
+ };
+ }
+
+}
[12/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveWriter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveWriter.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveWriter.java
new file mode 100644
index 0000000..027bde1
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveWriter.java
@@ -0,0 +1,732 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.GemFireIOException;
+import com.gemstone.gemfire.InternalGemFireException;
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.NanoTimer;
+import com.gemstone.gemfire.internal.SocketCreator;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
+
+import org.apache.logging.log4j.Logger;
+
+import java.io.*;
+import java.net.UnknownHostException;
+import java.util.*;
+import java.util.zip.GZIPOutputStream;
+
+/**
+ * StatArchiveWriter provides APIs to write statistic snapshots to an archive
+ * file.
+ *
+ */
+public class StatArchiveWriter implements StatArchiveFormat, SampleHandler {
+
+ private static final Logger logger = LogService.getLogger();
+
+ private static volatile String traceStatisticsName = null;
+ private static volatile String traceStatisticsTypeName = null;
+ private static volatile int traceResourceInstId = -1;
+
+ private final boolean trace = Boolean.getBoolean(DistributionConfig.GEMFIRE_PREFIX + "stats.debug.traceStatArchiveWriter");
+
+ private final Set<ResourceInstance> sampleWrittenForResources =
+ new HashSet<ResourceInstance>();
+ private final Set<ResourceInstance> addedResources =
+ new HashSet<ResourceInstance>();
+ private final StatArchiveDescriptor archiveDescriptor;
+ private long initialDate;
+ private final OutputStream outStream;
+ private final MyDataOutputStream dataOut;
+ private final OutputStream traceOutStream;
+ private final PrintStream traceDataOut;
+ private long previousMillisTimeStamp;
+ private int sampleCount;
+
+ /**
+ * Opens a StatArchiveWriter that will archive to the specified file.
+ * @throws GemFireIOException if <code>archiveName</code> can not be written to
+ */
+ public StatArchiveWriter(StatArchiveDescriptor archiveDescriptor) {
+ this.archiveDescriptor = archiveDescriptor;
+
+ if (archiveDescriptor.getArchiveName().endsWith(".gz")) {
+ try {
+ this.outStream = new GZIPOutputStream(new FileOutputStream(archiveDescriptor.getArchiveName()), 32768);
+ } catch (IOException ex) {
+ throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_COULD_NOT_OPEN_0.toLocalizedString(archiveDescriptor.getArchiveName()), ex);
+ }
+ } else {
+ try {
+ this.outStream = new BufferedOutputStream(new FileOutputStream(archiveDescriptor.getArchiveName()), 32768);
+ } catch (IOException ex) {
+ throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_COULD_NOT_OPEN_0.toLocalizedString(archiveDescriptor.getArchiveName()), ex);
+ }
+ }
+
+ this.dataOut = new MyDataOutputStream(this.outStream);
+
+ if (this.trace) {
+ String traceFileName = archiveDescriptor.getArchiveName() + ".trace";
+ try {
+ this.traceOutStream = new BufferedOutputStream(new FileOutputStream(traceFileName), 32768);
+ } catch (IOException ex) {
+ throw new GemFireIOException("Could not open " + traceFileName, ex);
+ }
+ this.traceDataOut = new PrintStream(this.traceOutStream);
+ } else {
+ this.traceOutStream = null;
+ this.traceDataOut = null;
+ }
+ }
+
+ public String getArchiveName() {
+ return this.archiveDescriptor.getArchiveName();
+ }
+
+ public void initialize(long nanosTimeStamp) {
+ this.previousMillisTimeStamp = initPreviousMillisTimeStamp(nanosTimeStamp);
+ this.initialDate = initInitialDate();
+ writeHeader(this.initialDate, this.archiveDescriptor);
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder(getClass().getName());
+ sb.append("@").append(System.identityHashCode(this)).append("{");
+ sb.append("archiveName=").append(this.archiveDescriptor.getArchiveName());
+ sb.append("productDescription=").append(this.archiveDescriptor.getProductDescription());
+ sb.append("systemDirectoryPath=").append(this.archiveDescriptor.getSystemDirectoryPath());
+ sb.append("systemId=").append(this.archiveDescriptor.getSystemId());
+ sb.append("systemStartTime=").append(this.archiveDescriptor.getSystemStartTime());
+ sb.append("previousMillisTimeStamp=").append(this.previousMillisTimeStamp);
+ sb.append("initialDate=").append(this.initialDate);
+ return sb.toString();
+ }
+
+ /**
+ * Closes the statArchiver by flushing its data to disk a closing its output stream.
+ * @throws GemFireIOException if the archive file could not be closed.
+ */
+ public final void close() {
+ try {
+ this.dataOut.flush();
+ if (this.trace) {
+ this.traceDataOut.flush();
+ }
+ } catch (IOException ignore) {
+ }
+ try {
+ outStream.close();
+ if (this.trace) {
+ this.traceOutStream.close();
+ }
+ } catch (IOException ex) {
+ throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_COULD_NOT_CLOSE_STATARCHIVER_FILE.toLocalizedString(), ex);
+ }
+ if (getSampleCount() == 0) {
+ // If we are closing an empty file go ahead and delete it.
+ // This prevents the fix for 46917 from leaving a bunch of
+ // empty gfs files around.
+ deleteFileIfPossible(new File(getArchiveName()));
+ }
+ }
+
+ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification="Best effort attempt to delete a GFS file without any samples.")
+ private static void deleteFileIfPossible(File file) {
+ file.delete();
+ }
+
+ /**
+ * Returns the number of bytes written so far to this archive.
+ * This does not take compression into account.
+ */
+ public final long bytesWritten() {
+ return this.dataOut.getBytesWritten();
+ }
+
+ protected long initPreviousMillisTimeStamp(long nanosTimeStamp) {
+ return NanoTimer.nanosToMillis(nanosTimeStamp);
+ }
+
+ protected long initInitialDate() {
+ return System.currentTimeMillis();
+ }
+
+ protected TimeZone getTimeZone() {
+ return Calendar.getInstance().getTimeZone();
+ }
+
+ protected String getOSInfo() {
+ return System.getProperty("os.name") + " " + System.getProperty("os.version");
+ }
+
+ protected String getMachineInfo() {
+ String machineInfo = System.getProperty("os.arch");
+ try {
+ String hostName = SocketCreator.getHostName(SocketCreator.getLocalHost());
+ machineInfo += " " + hostName;
+ } catch (UnknownHostException ignore) {
+ }
+ return machineInfo;
+ }
+
+ private void writeHeader(long initialDate, StatArchiveDescriptor archiveDescriptor) {
+ if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeHeader initialDate={} archiveDescriptor={}", initialDate, archiveDescriptor);
+ }
+ try {
+ this.dataOut.writeByte(HEADER_TOKEN);
+ this.dataOut.writeByte(ARCHIVE_VERSION);
+ this.dataOut.writeLong(initialDate);
+ this.dataOut.writeLong(archiveDescriptor.getSystemId());
+ this.dataOut.writeLong(archiveDescriptor.getSystemStartTime());
+ TimeZone timeZone = getTimeZone();
+ this.dataOut.writeInt(timeZone.getRawOffset());
+ this.dataOut.writeUTF(timeZone.getID());
+ this.dataOut.writeUTF(archiveDescriptor.getSystemDirectoryPath());
+ this.dataOut.writeUTF(archiveDescriptor.getProductDescription());
+ this.dataOut.writeUTF(getOSInfo());
+ this.dataOut.writeUTF(getMachineInfo());
+
+ if (this.trace) {
+ this.traceDataOut.println("writeHeader traceStatisticsName: " + traceStatisticsName);
+ this.traceDataOut.println("writeHeader traceStatisticsTypeName: " + traceStatisticsTypeName);
+ this.traceDataOut.println("writeHeader#writeByte HEADER_TOKEN: " + HEADER_TOKEN);
+ this.traceDataOut.println("writeHeader#writeByte ARCHIVE_VERSION: " + ARCHIVE_VERSION);
+ this.traceDataOut.println("writeHeader#writeLong initialDate: " + initialDate);
+ this.traceDataOut.println("writeHeader#writeLong archiveDescriptor.getSystemId(): " + archiveDescriptor.getSystemId());
+ this.traceDataOut.println("writeHeader#writeLong archiveDescriptor.getSystemStartTime(): " + archiveDescriptor.getSystemStartTime());
+ this.traceDataOut.println("writeHeader#writeInt timeZone.getRawOffset(): " + timeZone.getRawOffset());
+ this.traceDataOut.println("writeHeader#writeUTF timeZone.getID(): " + timeZone.getID());
+ this.traceDataOut.println("writeHeader#writeUTF archiveDescriptor.getSystemDirectoryPath(): " + archiveDescriptor.getSystemDirectoryPath());
+ this.traceDataOut.println("writeHeader#writeUTF archiveDescriptor.getProductDescription(): " + archiveDescriptor.getProductDescription());
+ this.traceDataOut.println("writeHeader#writeUTF getOSInfo(): " + getOSInfo());
+ this.traceDataOut.println("writeHeader#writeUTF getMachineInfo(): " + getMachineInfo());
+ }
+ } catch (IOException ex) {
+ throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_HEADER_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
+ }
+ }
+
+ public void allocatedResourceType(ResourceType resourceType) {
+ if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#allocatedResourceType resourceType={}", resourceType);
+ }
+ if (resourceType.getStatisticDescriptors().length >= ILLEGAL_STAT_OFFSET) {
+ throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_COULD_NOT_ARCHIVE_TYPE_0_BECAUSE_IT_HAD_MORE_THAN_1_STATISTICS.toLocalizedString(new Object[] {resourceType.getStatisticsType().getName(), Integer.valueOf(ILLEGAL_STAT_OFFSET-1)}));
+ }
+ // write the type to the archive
+ try {
+ this.dataOut.writeByte(RESOURCE_TYPE_TOKEN);
+ this.dataOut.writeInt(resourceType.getId());
+ this.dataOut.writeUTF(resourceType.getStatisticsType().getName());
+ this.dataOut.writeUTF(resourceType.getStatisticsType().getDescription());
+ StatisticDescriptor[] stats = resourceType.getStatisticDescriptors();
+ this.dataOut.writeShort(stats.length);
+ if (this.trace && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(resourceType.getStatisticsType().getName()))) {
+ this.traceDataOut.println("allocatedResourceType#writeByte RESOURCE_TYPE_TOKEN: " + RESOURCE_TYPE_TOKEN);
+ this.traceDataOut.println("allocatedResourceType#writeInt resourceType.getId(): " + resourceType.getId());
+ this.traceDataOut.println("allocatedResourceType#writeUTF resourceType.getStatisticsType().getName(): " + resourceType.getStatisticsType().getName());
+ this.traceDataOut.println("allocatedResourceType#writeUTF resourceType.getStatisticsType().getDescription(): " + resourceType.getStatisticsType().getDescription());
+ this.traceDataOut.println("allocatedResourceType#writeShort stats.length: " + stats.length);
+ }
+ for (int i=0; i < stats.length; i++) {
+ this.dataOut.writeUTF(stats[i].getName());
+ this.dataOut.writeByte(((StatisticDescriptorImpl)stats[i]).getTypeCode());
+ this.dataOut.writeBoolean(stats[i].isCounter());
+ this.dataOut.writeBoolean(stats[i].isLargerBetter());
+ this.dataOut.writeUTF(stats[i].getUnit());
+ this.dataOut.writeUTF(stats[i].getDescription());
+ if (this.trace && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(resourceType.getStatisticsType().getName()))) {
+ this.traceDataOut.println("allocatedResourceType#writeUTF stats[i].getName(): " + stats[i].getName());
+ this.traceDataOut.println("allocatedResourceType#writeByte ((StatisticDescriptorImpl)stats[i]).getTypeCode(): " + ((StatisticDescriptorImpl)stats[i]).getTypeCode());
+ this.traceDataOut.println("allocatedResourceType#writeBoolean stats[i].isCounter(): " + stats[i].isCounter());
+ this.traceDataOut.println("allocatedResourceType#writeBoolean stats[i].isLargerBetter(): " + stats[i].isLargerBetter());
+ this.traceDataOut.println("allocatedResourceType#writeUTF stats[i].getUnit(): " + stats[i].getUnit());
+ this.traceDataOut.println("allocatedResourceType#writeUTF stats[i].getDescription(): " + stats[i].getDescription());
+ }
+ }
+ } catch (IOException ex) {
+ throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_NEW_RESOURCE_TYPE_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
+ }
+ }
+
+ @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification="This is only for debugging and there is never more than one instance being traced because there is only one stat sampler.")
+ public void allocatedResourceInstance(ResourceInstance statResource) {
+ if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#allocatedResourceInstance statResource={}", statResource);
+ }
+ if (statResource.getResourceType().getStatisticDescriptors().length >= ILLEGAL_STAT_OFFSET) {
+ throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_COULD_NOT_ARCHIVE_TYPE_0_BECAUSE_IT_HAD_MORE_THAN_1_STATISTICS.toLocalizedString(new Object[] {statResource.getResourceType().getStatisticsType().getName(), Integer.valueOf(ILLEGAL_STAT_OFFSET-1)}));
+ }
+ if (statResource.getStatistics().isClosed()) {
+ return;
+ }
+ this.addedResources.add(statResource);
+ try {
+ this.dataOut.writeByte(RESOURCE_INSTANCE_CREATE_TOKEN);
+ this.dataOut.writeInt(statResource.getId());
+ this.dataOut.writeUTF(statResource.getStatistics().getTextId());
+ this.dataOut.writeLong(statResource.getStatistics().getNumericId());
+ this.dataOut.writeInt(statResource.getResourceType().getId());
+ if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(statResource.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(statResource.getResourceType().getStatisticsType().getName()))) {
+ traceResourceInstId = statResource.getId();
+ this.traceDataOut.println("writeHeader traceResourceInstId: " + traceResourceInstId);
+ this.traceDataOut.println("allocatedResourceInstance#writeByte RESOURCE_INSTANCE_CREATE_TOKEN: " + RESOURCE_INSTANCE_CREATE_TOKEN);
+ this.traceDataOut.println("allocatedResourceInstance#writeInt statResource.getId(): " + statResource.getId());
+ this.traceDataOut.println("allocatedResourceInstance#writeUTF statResource.getStatistics().getTextId(): " + statResource.getStatistics().getTextId());
+ this.traceDataOut.println("allocatedResourceInstance#writeLong statResource.getStatistics().getNumericId(): " + statResource.getStatistics().getNumericId());
+ this.traceDataOut.println("allocatedResourceInstance#writeInt statResource.getResourceType().getId(): " + statResource.getResourceType().getId());
+ }
+ } catch (IOException ex) {
+ throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_NEW_RESOURCE_INSTANCE_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
+ }
+ }
+
+ public void destroyedResourceInstance(ResourceInstance resourceInstance) {
+ if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#destroyedResourceInstance resourceInstance={}", resourceInstance);
+ }
+ if (!this.addedResources.contains(resourceInstance)) { // Fix for bug #45377
+ return;
+ }
+
+ this.sampleWrittenForResources.remove(resourceInstance);
+ this.addedResources.remove(resourceInstance);
+
+ try {
+ this.dataOut.writeByte(RESOURCE_INSTANCE_DELETE_TOKEN);
+ this.dataOut.writeInt(resourceInstance.getId());
+ if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(resourceInstance.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(resourceInstance.getResourceType().getStatisticsType().getName()))) {
+ this.traceDataOut.println("destroyedResourceInstance#writeByte RESOURCE_INSTANCE_DELETE_TOKEN: " + RESOURCE_INSTANCE_DELETE_TOKEN);
+ this.traceDataOut.println("destroyedResourceInstance#writeInt resourceInstance.getId(): " + resourceInstance.getId());
+ }
+ } catch (IOException ex) {
+ throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_DELETE_RESOURCE_INSTANCE_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
+ }
+ }
+
+ static long calcDelta(long previousMillis, long currentMillis) {
+ long delta = currentMillis - previousMillis;
+ if (delta <= 0) {
+ throw new IllegalArgumentException("Sample timestamp must be greater than previous timestamp (millisTimeStamp is " + currentMillis + ", previousMillis is " + previousMillis + " and delta is " + delta + ").");
+ }
+ return delta;
+ }
+
+ private void writeTimeStamp(long nanosTimeStamp) throws IOException {
+ final long millisTimeStamp = NanoTimer.nanosToMillis(nanosTimeStamp);
+ final long delta = calcDelta(this.previousMillisTimeStamp, millisTimeStamp);
+ if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeTimeStamp millisTimeStamp={}, delta={}", millisTimeStamp, (int)delta);
+ }
+ if (delta > MAX_SHORT_TIMESTAMP) {
+ if (delta > Integer.MAX_VALUE) {
+ throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_TIMESTAMP_DELTA_0_WAS_GREATER_THAN_1.toLocalizedString(new Object[] {Long.valueOf(delta), Integer.valueOf(Integer.MAX_VALUE)}));
+ }
+ this.dataOut.writeShort(INT_TIMESTAMP_TOKEN);
+ this.dataOut.writeInt((int)delta);
+ if (this.trace) {
+ this.traceDataOut.println("writeTimeStamp#writeShort INT_TIMESTAMP_TOKEN: " + INT_TIMESTAMP_TOKEN);
+ this.traceDataOut.println("writeTimeStamp#writeInt (int)delta: " + (int)delta);
+ }
+ } else {
+ this.dataOut.writeShort((int)delta);
+ if (this.trace) {
+ this.traceDataOut.println("writeTimeStamp#writeShort (int)delta: " + (int)delta);
+ }
+ }
+ this.previousMillisTimeStamp = millisTimeStamp;
+ }
+
+ /**
+ * Writes the resource instance id to the <code>dataOut</code> stream.
+ */
+ private void writeResourceInst(int instId) throws IOException {
+ if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeResourceInst instId={}", instId);
+ }
+ if (instId > MAX_BYTE_RESOURCE_INST_ID) {
+ if (instId > MAX_SHORT_RESOURCE_INST_ID) {
+ this.dataOut.writeByte(INT_RESOURCE_INST_ID_TOKEN);
+ this.dataOut.writeInt(instId);
+ if (this.trace && (traceResourceInstId == -1 || traceResourceInstId == instId)) {
+ this.traceDataOut.println("writeResourceInst#writeByte INT_RESOURCE_INST_ID_TOKEN: " + INT_RESOURCE_INST_ID_TOKEN);
+ if (instId == ILLEGAL_RESOURCE_INST_ID) {
+ this.traceDataOut.println("writeResourceInst#writeInt ILLEGAL_RESOURCE_INST_ID: " + ILLEGAL_RESOURCE_INST_ID);
+ } else {
+ this.traceDataOut.println("writeResourceInst#writeInt instId: " + instId);
+ }
+ }
+ } else {
+ this.dataOut.writeByte(SHORT_RESOURCE_INST_ID_TOKEN);
+ this.dataOut.writeShort(instId);
+ if (this.trace && (traceResourceInstId == -1 || traceResourceInstId == instId)) {
+ this.traceDataOut.println("writeResourceInst#writeByte SHORT_RESOURCE_INST_ID_TOKEN: " + SHORT_RESOURCE_INST_ID_TOKEN);
+ if (instId == ILLEGAL_RESOURCE_INST_ID) {
+ this.traceDataOut.println("writeResourceInst#writeShort ILLEGAL_RESOURCE_INST_ID: " + ILLEGAL_RESOURCE_INST_ID);
+ } else {
+ this.traceDataOut.println("writeResourceInst#writeShort instId: " + instId);
+ }
+ }
+ }
+ } else {
+ this.dataOut.writeByte(instId);
+ if (this.trace && (traceResourceInstId == -1 || traceResourceInstId == instId)) {
+ if (instId == ILLEGAL_RESOURCE_INST_ID) {
+ this.traceDataOut.println("writeResourceInst#writeByte ILLEGAL_RESOURCE_INST_ID: " + ILLEGAL_RESOURCE_INST_ID);
+ } else {
+ this.traceDataOut.println("writeResourceInst#writeByte instId: " + instId);
+ }
+ }
+ }
+ }
+
+ public void sampled(long nanosTimeStamp, List<ResourceInstance> resourceInstances) {
+ if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#sampled nanosTimeStamp={}, resourceInstances={}", nanosTimeStamp, resourceInstances);
+ }
+ try {
+ this.dataOut.writeByte(SAMPLE_TOKEN);
+ if (this.trace) {
+ this.traceDataOut.println("sampled#writeByte SAMPLE_TOKEN: " + SAMPLE_TOKEN);
+ }
+ writeTimeStamp(nanosTimeStamp);
+ for (ResourceInstance ri : resourceInstances) {
+ writeSample(ri);
+ }
+ writeResourceInst(ILLEGAL_RESOURCE_INST_ID);
+ this.dataOut.flush();
+ if (this.trace) {
+ this.traceDataOut.flush();
+ }
+ } catch (IOException ex) {
+ throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_SAMPLE_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
+ }
+ this.sampleCount++; // only inc after sample done w/o an exception thrown
+ }
+
+ public int getSampleCount() {
+ return this.sampleCount;
+ }
+
+ private void writeSample(ResourceInstance ri) throws IOException {
+ final boolean isDebugEnabled_STATISTICS = logger.isTraceEnabled(LogMarker.STATISTICS);
+ if (isDebugEnabled_STATISTICS) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeSample ri={}", ri);
+ }
+ if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(ri.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(ri.getResourceType().getStatisticsType().getName()))) {
+ this.traceDataOut.println("writeSample#writeSample for ri=" + ri);
+ }
+ if (ri.getStatistics().isClosed()) {
+ return;
+ }
+ StatisticDescriptor[] stats = ri.getResourceType().getStatisticDescriptors();
+ if (stats.length > 254) {
+ throw new Error("StatisticsType " + ri.getResourceType().getStatisticsType().getName() + " has too many stats: " + stats.length);
+ }
+ boolean wroteInstId = false;
+ boolean checkForChange = true;
+
+ if (!this.sampleWrittenForResources.contains(ri)) {
+ // first time for this instance so all values need to be written
+ checkForChange = false;
+ this.sampleWrittenForResources.add(ri);
+ }
+
+ long[] previousStatValues = ri.getPreviousStatValues();
+ if (isDebugEnabled_STATISTICS) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeSample checkForChange={}, previousStatValues={}, stats.length={}",
+ checkForChange, Arrays.toString(previousStatValues), stats.length);
+ }
+ if (previousStatValues == null) {
+ previousStatValues = new long[stats.length];
+ ri.setPreviousStatValues(previousStatValues);
+ }
+
+ int statsWritten = 0;
+ try {
+ for (int i=0; i < stats.length; i++) {
+ long value = ri.getLatestStatValues()[i];
+ if (!checkForChange || value != previousStatValues[i]) {
+ long delta = checkForChange ? value - previousStatValues[i] : value;
+ if (!wroteInstId) {
+ wroteInstId = true;
+ writeResourceInst(ri.getId());
+ }
+ this.dataOut.writeByte(i);
+ if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(ri.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(ri.getResourceType().getStatisticsType().getName()))) {
+ this.traceDataOut.println("writeSample#writeByte i: " + i);
+ }
+ if (isDebugEnabled_STATISTICS) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeStatValue stats[{}]={}, delta={}", i, stats[i], delta);
+ }
+ writeStatValue(stats[i], delta, this.dataOut);
+ if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(ri.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(ri.getResourceType().getStatisticsType().getName()))) {
+ byte typeCode = ((StatisticDescriptorImpl)stats[i]).getTypeCode();
+ switch(typeCode) {
+ case BYTE_CODE:
+ this.traceDataOut.println("writeStatValue#writeByte " + typeCodeToString(typeCode) + " delta: " + delta);
+ break;
+ case SHORT_CODE:
+ this.traceDataOut.println("writeStatValue#writeShort" + typeCodeToString(typeCode) + " delta: " + delta);
+ break;
+ case INT_CODE:
+ case FLOAT_CODE:
+ case LONG_CODE:
+ case DOUBLE_CODE:
+ this.traceDataOut.println("writeStatValue#writeCompactValue " + typeCodeToString(typeCode) + " delta: " + delta);
+ break;
+ default:
+ }
+ }
+ }
+ }
+ } catch (IllegalStateException closedEx) {
+ // resource was closed causing getStatValue to throw this exception
+ }
+
+ if (wroteInstId) {
+ this.dataOut.writeByte(ILLEGAL_STAT_OFFSET);
+ if (this.trace && (traceStatisticsName == null
+ || traceStatisticsName.equals(ri.getStatistics().getTextId()))
+ && (traceStatisticsTypeName == null
+ || traceStatisticsTypeName.equals(ri.getResourceType().getStatisticsType().getName()))) {
+ this.traceDataOut.println("writeSample#writeByte ILLEGAL_STAT_OFFSET: " + ILLEGAL_STAT_OFFSET);
+ }
+ }
+ if (isDebugEnabled_STATISTICS) {
+ logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeSample statsWritten={}", statsWritten);
+ }
+ }
+
+ public static void writeCompactValue(long v, DataOutput dataOut) throws IOException {
+ if (v <= MAX_1BYTE_COMPACT_VALUE && v >= MIN_1BYTE_COMPACT_VALUE) {
+ dataOut.writeByte((int)v);
+ } else if (v <= MAX_2BYTE_COMPACT_VALUE && v >= MIN_2BYTE_COMPACT_VALUE) {
+ dataOut.writeByte(COMPACT_VALUE_2_TOKEN);
+ dataOut.writeShort((int)v);
+ } else {
+ byte[] buffer = new byte[8];
+ int idx = 0;
+ long originalValue = v;
+ if (v < 0) {
+ while (v != -1 && v != 0) {
+ buffer[idx++] = (byte)(v & 0xFF);
+ v >>= 8;
+ }
+ // On windows v goes to zero somtimes; seems like a bug
+ if (v == 0) {
+ // when this happens we end up with a bunch of -1 bytes
+ // so strip off the high order ones
+ while (buffer[idx-1] == -1) {
+ idx--;
+ }
+ // System.out.print("DEBUG: originalValue=" + originalValue);
+ // for (int dbx=0; dbx<idx; dbx++) {
+ // System.out.print(" " + buffer[dbx]);
+ // }
+ // System.out.println();
+ }
+ if ((buffer[idx-1] & 0x80) == 0) {
+ /* If the most significant byte does not have its high order bit set
+ * then add a -1 byte so we know this is a negative number
+ */
+ buffer[idx++] = -1;
+ }
+ } else {
+ while (v != 0) {
+ buffer[idx++] = (byte)(v & 0xFF);
+ v >>= 8;
+ }
+ if ((buffer[idx-1] & 0x80) != 0) {
+ /* If the most significant byte has its high order bit set
+ * then add a zero byte so we know this is a positive number
+ */
+ buffer[idx++] = 0;
+ }
+ }
+ if (idx <= 2) {
+ throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_EXPECTED_IDX_TO_BE_GREATER_THAN_2_IT_WAS_0_FOR_THE_VALUE_1.toLocalizedString(new Object[] {Integer.valueOf(idx), Long.valueOf(originalValue)}));
+ }
+ int token = COMPACT_VALUE_2_TOKEN + (idx - 2);
+ dataOut.writeByte(token);
+ for (int i=idx-1; i >= 0; i--) {
+ dataOut.writeByte(buffer[i]);
+ }
+ }
+ }
+
+ public static long readCompactValue(DataInput dataIn) throws IOException {
+ long v = dataIn.readByte();
+ boolean dump = false;
+ if (dump) {
+ System.out.print("compactValue(byte1)=" + v);
+ }
+ if (v < MIN_1BYTE_COMPACT_VALUE) {
+ if (v == COMPACT_VALUE_2_TOKEN) {
+ v = dataIn.readShort();
+ if (dump) {
+ System.out.print("compactValue(short)=" + v);
+ }
+ } else {
+ int bytesToRead = ((byte)v - COMPACT_VALUE_2_TOKEN) + 2;
+ v = dataIn.readByte(); // note the first byte will be a signed byte.
+ if (dump) {
+ System.out.print("compactValue(" + bytesToRead + ")=" + v);
+ }
+ bytesToRead--;
+ while (bytesToRead > 0) {
+ v <<= 8;
+ v |= dataIn.readUnsignedByte();
+ bytesToRead--;
+ }
+ }
+ }
+ return v;
+ }
+
+ protected static void writeStatValue(StatisticDescriptor f, long v, DataOutput dataOut) throws IOException {
+ byte typeCode = ((StatisticDescriptorImpl)f).getTypeCode();
+ writeStatValue(typeCode, v, dataOut);
+ }
+
+ public static void writeStatValue(byte typeCode, long v, DataOutput dataOut) throws IOException {
+ switch(typeCode) {
+ case BYTE_CODE:
+ dataOut.writeByte((int)v);
+ break;
+ case SHORT_CODE:
+ dataOut.writeShort((int)v);
+ break;
+ case INT_CODE:
+ case FLOAT_CODE:
+ case LONG_CODE:
+ case DOUBLE_CODE:
+ writeCompactValue(v, dataOut);
+ break;
+ default:
+ throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_UNEXPECTED_TYPE_CODE_0.toLocalizedString(Byte.valueOf(typeCode)));
+ }
+ }
+
+ protected static void setTraceFilter(String traceStatisticsName, String traceStatisticsTypeName) {
+ StatArchiveWriter.traceStatisticsName = traceStatisticsName;
+ StatArchiveWriter.traceStatisticsTypeName = traceStatisticsTypeName;
+ StatArchiveWriter.traceResourceInstId = -1;
+ }
+
+ protected static void clearTraceFilter() {
+ StatArchiveWriter.traceStatisticsName = null;
+ StatArchiveWriter.traceStatisticsTypeName = null;
+ StatArchiveWriter.traceResourceInstId = -1;
+ }
+
+ private static String typeCodeToString(byte typeCode) {
+ switch(typeCode) {
+ case BYTE_CODE:
+ return "BYTE_CODE";
+ case SHORT_CODE:
+ return "SHORT_CODE";
+ case INT_CODE:
+ return "INT_CODE";
+ case FLOAT_CODE:
+ return "FLOAT_CODE";
+ case LONG_CODE:
+ return "LONG_CODE";
+ case DOUBLE_CODE:
+ return "DOUBLE_CODE";
+ default:
+ return "unknown typeCode " + typeCode;
+ }
+ }
+
+ private static class MyDataOutputStream implements DataOutput {
+ private long bytesWritten = 0;
+ private final DataOutputStream dataOut;
+
+ public MyDataOutputStream(OutputStream out) {
+ this.dataOut = new DataOutputStream(out);
+ }
+
+ public final long getBytesWritten() {
+ return this.bytesWritten;
+ }
+ public final void flush() throws IOException {
+ this.dataOut.flush();
+ }
+ @SuppressWarnings("unused")
+ public final void close() throws IOException {
+ this.dataOut.close();
+ }
+
+ public final void write(int b) throws IOException {
+ throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
+ }
+ public final void write(byte[] b, int off, int len) throws IOException {
+ throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
+ }
+ public final void write(byte[] b) throws IOException {
+ throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
+ }
+ public final void writeBytes(String v) throws IOException {
+ throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
+ }
+ public final void writeChar(int v) throws IOException {
+ throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
+ }
+ public final void writeChars(String v) throws IOException {
+ throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
+ }
+ public final void writeDouble(double v) throws IOException {
+ throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
+ }
+ public final void writeFloat(float v) throws IOException {
+ throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
+ }
+
+ public final void writeBoolean(boolean v) throws IOException {
+ this.dataOut.writeBoolean(v);
+ this.bytesWritten += 1;
+ }
+ public final void writeByte(int v) throws IOException {
+ this.dataOut.writeByte(v);
+ this.bytesWritten += 1;
+ }
+ public final void writeShort(int v) throws IOException {
+ this.dataOut.writeShort(v);
+ this.bytesWritten += 2;
+ }
+ public final void writeInt(int v) throws IOException {
+ this.dataOut.writeInt(v);
+ this.bytesWritten += 4;
+ }
+ public final void writeLong(long v) throws IOException {
+ this.dataOut.writeLong(v);
+ this.bytesWritten += 8;
+ }
+ public final void writeUTF(String v) throws IOException {
+ this.dataOut.writeUTF(v);
+ this.bytesWritten += v.length() + 2; // this is the minimum. The max is v.size()*3 +2
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatSamplerStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatSamplerStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatSamplerStats.java
new file mode 100644
index 0000000..e83d46c
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatSamplerStats.java
@@ -0,0 +1,153 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+
+/**
+ * Statistics related to the statistic sampler.
+ */
+public class StatSamplerStats {
+ public final static String SAMPLE_COUNT = "sampleCount"; // int
+ public final static String SAMPLE_TIME = "sampleTime"; // long
+ public final static String DELAY_DURATION = "delayDuration"; // int
+ public final static String STAT_RESOURCES = "statResources"; // int
+ public final static String JVM_PAUSES = "jvmPauses"; // int
+ public final static String SAMPLE_CALLBACKS = "sampleCallbacks"; // int
+ public final static String SAMPLE_CALLBACK_ERRORS = "sampleCallbackErrors"; // int
+ public final static String SAMPLE_CALLBACK_DURATION = "sampleCallbackDuration"; // long
+
+ private final static StatisticsType samplerType;
+ private final static int sampleCountId;
+ private final static int sampleTimeId;
+ private final static int delayDurationId;
+ private final static int statResourcesId;
+ private final static int jvmPausesId;
+ private final static int sampleCallbacksId;
+ private final static int sampleCallbackErrorsId;
+ private final static int sampleCallbackDurationId;
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ samplerType = f.createType("StatSampler",
+ "Stats on the statistic sampler.",
+ new StatisticDescriptor[] {
+ f.createIntCounter(SAMPLE_COUNT,
+ "Total number of samples taken by this sampler.",
+ "samples", false),
+ f.createLongCounter(SAMPLE_TIME,
+ "Total amount of time spent taking samples.",
+ "milliseconds", false),
+ f.createIntGauge(DELAY_DURATION,
+ "Actual duration of sampling delay taken before taking this sample.",
+ "milliseconds", false),
+ f.createIntGauge(STAT_RESOURCES,
+ "Current number of statistic resources being sampled by this sampler.",
+ "resources", false),
+ f.createIntCounter(JVM_PAUSES,
+ "Total number of JVM pauses (which may or may not be full GC pauses) detected by this sampler. A JVM pause is defined as a system event which kept the statistics sampler thread from sampling for 3000 or more milliseconds. This threshold can be customized by setting the system property gemfire.statSamplerDelayThreshold (units are milliseconds).",
+ "jvmPauses", false),
+ f.createIntGauge(SAMPLE_CALLBACKS,
+ "Current number of statistics that are sampled using callbacks.",
+ "resources", false),
+ f.createIntCounter(SAMPLE_CALLBACK_ERRORS,
+ "Total number of exceptions thrown by callbacks when performing sampling",
+ "errors", false),
+ f.createLongCounter(SAMPLE_CALLBACK_DURATION,
+ "Total amount of time invoking sampling callbacks",
+ "milliseconds", false),
+ });
+ sampleCountId = samplerType.nameToId(SAMPLE_COUNT);
+ sampleTimeId = samplerType.nameToId(SAMPLE_TIME);
+ delayDurationId = samplerType.nameToId(DELAY_DURATION);
+ statResourcesId = samplerType.nameToId(STAT_RESOURCES);
+ jvmPausesId = samplerType.nameToId(JVM_PAUSES);
+ sampleCallbacksId = samplerType.nameToId(SAMPLE_CALLBACKS);
+ sampleCallbackErrorsId = samplerType.nameToId(SAMPLE_CALLBACK_ERRORS);
+ sampleCallbackDurationId = samplerType.nameToId(SAMPLE_CALLBACK_DURATION);
+ }
+
+ private final Statistics samplerStats;
+
+ public StatSamplerStats(StatisticsFactory f, long id) {
+ this.samplerStats = f.createStatistics(samplerType, "statSampler", id);
+ }
+
+ public void tookSample(long nanosSpentWorking, int statResources, long nanosSpentSleeping) {
+ this.samplerStats.incInt(sampleCountId, 1);
+ this.samplerStats.incLong(sampleTimeId, nanosSpentWorking / 1000000);
+ this.samplerStats.setInt(delayDurationId, (int)(nanosSpentSleeping / 1000000));
+ this.samplerStats.setInt(statResourcesId, statResources);
+ }
+
+ public void incJvmPauses() {
+ this.samplerStats.incInt(jvmPausesId, 1);
+ }
+
+ public void incSampleCallbackErrors(int delta) {
+ this.samplerStats.incInt(sampleCallbackErrorsId, delta);
+ }
+
+ public void setSampleCallbacks(int count) {
+ this.samplerStats.setInt(sampleCallbacksId, count);
+ }
+
+ public void incSampleCallbackDuration(long delta) {
+ this.samplerStats.incLong(sampleCallbackDurationId, delta);
+ }
+
+ public int getSampleCount() {
+ return this.samplerStats.getInt(SAMPLE_COUNT);
+ }
+
+ public long getSampleTime() {
+ return this.samplerStats.getLong(SAMPLE_TIME);
+ }
+
+ public int getDelayDuration() {
+ return this.samplerStats.getInt(DELAY_DURATION);
+ }
+
+ public int getStatResources() {
+ return this.samplerStats.getInt(STAT_RESOURCES);
+ }
+
+ public int getJvmPauses() {
+ return this.samplerStats.getInt(JVM_PAUSES);
+ }
+
+ public void close() {
+ this.samplerStats.close();
+ }
+
+ public Statistics getStats(){
+ return this.samplerStats;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder(getClass().getName());
+ sb.append("@").append(System.identityHashCode(this)).append("{");
+ sb.append("isClosed=").append(this.samplerStats.isClosed());
+ sb.append(", ").append(SAMPLE_COUNT + "=").append(this.samplerStats.getInt(SAMPLE_COUNT));
+ sb.append(", ").append(SAMPLE_TIME + "=").append(this.samplerStats.getLong(SAMPLE_TIME));
+ sb.append(", ").append(DELAY_DURATION + "=").append(this.samplerStats.getInt(DELAY_DURATION));
+ sb.append(", ").append(STAT_RESOURCES + "=").append(this.samplerStats.getInt(STAT_RESOURCES));
+ sb.append(", ").append(JVM_PAUSES + "=").append(this.samplerStats.getInt(JVM_PAUSES));
+ sb.append("}");
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticDescriptorImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticDescriptorImpl.java
new file mode 100644
index 0000000..682f77e
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticDescriptorImpl.java
@@ -0,0 +1,383 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+
+/**
+ * Describes an individual statistic whose value is updated by an
+ * application and may be archived by GemFire. These descriptions are
+ * gathered together in a {@link StatisticsType}.
+ *
+ * @see Statistics
+ *
+ *
+ * @since GemFire 3.0
+ */
+public final class StatisticDescriptorImpl implements StatisticDescriptor {
+
+ /** A constant for an <code>byte</code> type */
+ static final byte BYTE = (byte) 3;
+
+ /** A constant for an <code>short</code> type */
+ static final byte SHORT = (byte) 4;
+
+ /** A constant for an <code>int</code> type */
+ static final byte INT = (byte) 5;
+
+ /** A constant for an <code>long</code> type */
+ static final byte LONG = (byte) 6;
+
+ /** A constant for an <code>float</code> type */
+ static final byte FLOAT = (byte) 7;
+
+ /** A constant for an <code>double</code> type */
+ static final byte DOUBLE = (byte) 8;
+
+ //////////////////// Instance Fields ////////////////////
+
+ /** An unitialized offset */
+ private int INVALID_OFFSET = -1;
+
+ /** The name of the statistic */
+ private final String name;
+
+ /** The type code of this statistic */
+ private final byte typeCode;
+
+ /** A description of the statistic */
+ private final String description;
+
+ /** The unit of the statistic */
+ private final String unit;
+
+ /** Is the statistic a counter? */
+ private final boolean isCounter;
+
+ /** Do larger values of the statistic indicate better performance? */
+ private final boolean isLargerBetter;
+
+ /** The physical offset used to access the data that stores the
+ * value for this statistic in an instance of {@link Statistics}
+ */
+ private int id = INVALID_OFFSET;
+
+ ////////////////////// Static Methods //////////////////////
+
+ /**
+ * Returns the name of the given type code
+ *
+ * @throws IllegalArgumentException
+ * <code>code</code> is an unknown type
+ */
+ public final static String getTypeCodeName(int code) {
+ switch (code) {
+ case BYTE:
+ return "byte";
+ case SHORT:
+ return "short";
+ case FLOAT:
+ return "float";
+ case INT:
+ return "int";
+ case LONG:
+ return "long";
+ case DOUBLE:
+ return "double";
+ default:
+ throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_UNKNOWN_TYPE_CODE_0.toLocalizedString(Integer.valueOf(code)));
+ }
+ }
+
+ /**
+ * Returns the number of bits needed to represent a value of the given type
+ *
+ * @throws IllegalArgumentException
+ * <code>code</code> is an unknown type
+ */
+ public final static int getTypeCodeBits(int code) {
+ switch (code) {
+ case BYTE:
+ return 8;
+ case SHORT:
+ return 16;
+ case FLOAT:
+ return 32;
+ case INT:
+ return 32;
+ case LONG:
+ return 64;
+ case DOUBLE:
+ return 64;
+ default:
+ throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_UNKNOWN_TYPE_CODE_0.toLocalizedString(Integer.valueOf(code)));
+ }
+ }
+
+ /**
+ * Returns the class of the given type code
+ *
+ * @throws IllegalArgumentException
+ * <code>code</code> is an unknown type
+ */
+ public final static Class<?> getTypeCodeClass(byte code) {
+ switch (code) {
+ case BYTE:
+ return byte.class;
+ case SHORT:
+ return short.class;
+ case FLOAT:
+ return float.class;
+ case INT:
+ return int.class;
+ case LONG:
+ return long.class;
+ case DOUBLE:
+ return double.class;
+ default:
+ throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_UNKNOWN_TYPE_CODE_0.toLocalizedString(Integer.valueOf(code)));
+ }
+ }
+
+ public static StatisticDescriptor createIntCounter(String name, String description,
+ String units, boolean isLargerBetter) {
+ return new StatisticDescriptorImpl(name, INT, description, units, true, isLargerBetter);
+ }
+ public static StatisticDescriptor createLongCounter(String name, String description,
+ String units, boolean isLargerBetter) {
+ return new StatisticDescriptorImpl(name, LONG, description, units, true, isLargerBetter);
+ }
+ public static StatisticDescriptor createDoubleCounter(String name, String description,
+ String units, boolean isLargerBetter) {
+ return new StatisticDescriptorImpl(name, DOUBLE, description, units, true, isLargerBetter);
+ }
+ public static StatisticDescriptor createIntGauge(String name, String description,
+ String units, boolean isLargerBetter) {
+ return new StatisticDescriptorImpl(name, INT, description, units, false, isLargerBetter);
+ }
+ public static StatisticDescriptor createLongGauge(String name, String description,
+ String units, boolean isLargerBetter) {
+ return new StatisticDescriptorImpl(name, LONG, description, units, false, isLargerBetter);
+ }
+ public static StatisticDescriptor createDoubleGauge(String name, String description,
+ String units, boolean isLargerBetter) {
+ return new StatisticDescriptorImpl(name, DOUBLE, description, units, false, isLargerBetter);
+ }
+
+ /////////////////////// Constructors ///////////////////////
+
+ /**
+ * Creates a new description of a statistic.
+ *
+ * @param name
+ * The name of the statistic (for example,
+ * <code>"numDatabaseLookups"</code>)
+ * @param typeCode
+ * The type of the statistic. This must be either
+ * <code>int.class</code>, <code>long.class</code>, or
+ * <code>double.class</code>.
+ * @param description
+ * A description of the statistic (for example, <code>"The
+ * number of database lookups"</code>
+ * @param unit
+ * The units that this statistic is measure in (for example,
+ * <code>"milliseconds"</code>)
+ * @param isCounter
+ * Is this statistic a counter? That is, does its value
+ * change monotonically (always increases or always
+ * decreases)?
+ * @param isLargerBetter
+ * True if larger values indicate better performance.
+ *
+ * @throws IllegalArgumentException
+ * <code>type</code> is not one of <code>int.class</code>,
+ * <code>long.class</code>, or <code>double.class</code>.
+ */
+ private StatisticDescriptorImpl(String name, byte typeCode,
+ String description, String unit,
+ boolean isCounter,
+ boolean isLargerBetter) {
+ this.name = name;
+ this.typeCode = typeCode;
+ if (description == null) {
+ this.description = "";
+
+ } else {
+ this.description = description;
+ }
+
+ if (unit == null) {
+ this.unit = "";
+
+ } else {
+ this.unit = unit;
+ }
+ this.isCounter = isCounter;
+ this.isLargerBetter = isLargerBetter;
+ }
+
+ //////////////////// StatisticDescriptor Methods ////////////////////
+
+ public final String getName() {
+ return this.name;
+ }
+
+ public final String getDescription() {
+ return this.description;
+ }
+
+ public final Class<?> getType() {
+ return getTypeCodeClass(this.typeCode);
+ }
+
+ public final int getStorageBits() {
+ return getTypeCodeBits(this.typeCode);
+ }
+
+ public final boolean isCounter() {
+ return this.isCounter;
+ }
+
+ public final boolean isLargerBetter() {
+ return this.isLargerBetter;
+ }
+
+ public final String getUnit() {
+ return this.unit;
+ }
+
+ public final int getId() {
+// if (this.id == INVALID_OFFSET) {
+// String s = "The id has not been initialized yet.";
+// throw new IllegalStateException(s);
+// }
+
+ //Assert.assertTrue(this.id >= 0);
+ return this.id;
+ }
+
+ public final Number getNumberForRawBits(long bits) {
+ switch (this.typeCode) {
+ case StatisticDescriptorImpl.INT:
+ return (int)bits;
+ case StatisticDescriptorImpl.LONG:
+ return bits;
+ case StatisticDescriptorImpl.DOUBLE:
+ return Double.longBitsToDouble(bits);
+ default:
+ throw new RuntimeException(LocalizedStrings.StatisticsImpl_UNEXPECTED_STAT_DESCRIPTOR_TYPE_CODE_0.toLocalizedString(Byte.valueOf(this.typeCode)));
+ }
+ }
+
+ //////////////////// Instance Methods ////////////////////
+
+ /**
+ * Returns the type code of this statistic
+ */
+ public final byte getTypeCode() {
+ return this.typeCode;
+ }
+
+ /**
+ * Sets the id of this descriptor
+ */
+ final void setId(int id) {
+ //Assert.assertTrue(id >= 0);
+ this.id = id;
+ }
+
+ //////////////////// Comparable Methods ////////////////////
+ /**
+ * <code>StatisticDescriptor</code>s are naturally ordered by their
+ * name.
+ *
+ * @throws IllegalArgumentException
+ * <code>o</code> is not a <code>StatisticDescriptor</code>
+ *
+ * @see #getName
+ */
+ public int compareTo(StatisticDescriptor o) {
+ return this.getName().compareTo(o.getName());
+ }
+
+ public final int checkInt() {
+ if (this.typeCode != INT) {
+ throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_THE_STATISTIC_0_WITH_ID_1_IS_OF_TYPE_2_AND_IT_WAS_EXPECTED_TO_BE_AN_INT.toLocalizedString(new Object[] {getName(), Integer.valueOf(getId()), StatisticDescriptorImpl.getTypeCodeName(getTypeCode())}));
+ }
+ return this.id;
+ }
+
+ public final int checkLong() {
+ if (this.typeCode != LONG) {
+ StringBuffer sb = new StringBuffer();
+ sb.append("The statistic " + getName() + " with id ");
+ sb.append(getId());
+ sb.append(" is of type ");
+ sb.append(StatisticDescriptorImpl.getTypeCodeName(getTypeCode()));
+
+ sb.append(" and it was expected to be a long");
+ throw new IllegalArgumentException(sb.toString());
+ }
+ return this.id;
+ }
+
+ public final int checkDouble() {
+ if (this.typeCode != DOUBLE) {
+ throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_THE_STATISTIC_0_WITH_ID_1_IS_OF_TYPE_2_AND_IT_WAS_EXPECTED_TO_BE_A_DOUBLE.toLocalizedString(new Object[] {getName(), Integer.valueOf(getId()), StatisticDescriptorImpl.getTypeCodeName(getTypeCode())}));
+ }
+ return this.id;
+ }
+
+
+ @Override // GemStoneAddition
+ public int hashCode() {
+ return getName().hashCode();
+ }
+ @Override
+ public boolean equals(Object o) {
+ if (o == null) {
+ return false;
+ }
+ if (!(o instanceof StatisticDescriptorImpl)) {
+ return false;
+ }
+ StatisticDescriptorImpl other = (StatisticDescriptorImpl)o;
+ if (getId() != other.getId()) {
+ return false;
+ }
+ if (!getName().equals(other.getName())) {
+ return false;
+ }
+ if (isCounter() != other.isCounter()) {
+ return false;
+ }
+ if (isLargerBetter() != other.isLargerBetter()) {
+ return false;
+ }
+ if (!getType().equals(other.getType())) {
+ return false;
+ }
+ if (!getUnit().equals(other.getUnit())) {
+ return false;
+ }
+ if (!getDescription().equals(other.getDescription())) {
+ return false;
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsImpl.java
new file mode 100644
index 0000000..ea3b953
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsImpl.java
@@ -0,0 +1,588 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+//import com.gemstone.gemfire.distributed.DistributedSystem;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.DoubleSupplier;
+import java.util.function.IntSupplier;
+import java.util.function.LongSupplier;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.concurrent.Atomics;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.util.concurrent.CopyOnWriteHashMap;
+
+import org.apache.logging.log4j.Logger;
+
+// @todo darrel Add statistics instances to archive when they are created.
+/**
+ * An object that maintains the values of various application-defined
+ * statistics. The statistics themselves are described by an instance
+ * of {@link StatisticsType}.
+ *
+ * <P>
+ *
+ * For optimal statistic access, each statistic may be referred to by
+ * its {@link #nameToId id} in the statistics object.
+ *
+ * <P>
+ *
+ * @see <A href="package-summary.html#statistics">Package introduction</A>
+ *
+ *
+ * @since GemFire 3.0
+ */
+public abstract class StatisticsImpl implements Statistics {
+ /** logger - not private for tests */
+ static Logger logger = LogService.getLogger();
+
+ /** The type of this statistics instance */
+ private final StatisticsTypeImpl type;
+
+ /** The display name of this statistics instance */
+ private final String textId;
+
+ /** Numeric information display with these statistics */
+ private final long numericId;
+
+ /** Non-zero if stats values come from operating system system calls */
+ private final int osStatFlags;
+
+ /** Are these statistics closed? */
+ private boolean closed;
+
+ /** Uniquely identifies this instance */
+ private long uniqueId;
+
+ /**
+ * Suppliers of int sample values to be sampled every sample-interval
+ */
+ private final CopyOnWriteHashMap<Integer, IntSupplier> intSuppliers = new CopyOnWriteHashMap<>();
+ /**
+ * Suppliers of long sample values to be sampled every sample-interval
+ */
+ private final CopyOnWriteHashMap<Integer, LongSupplier> longSuppliers = new CopyOnWriteHashMap<>();
+ /**
+ * Suppliers of double sample values to be sampled every sample-interval
+ */
+ private final CopyOnWriteHashMap<Integer, DoubleSupplier> doubleSuppliers = new CopyOnWriteHashMap<>();
+
+ /**
+ * Suppliers that have previously failed. Tracked to avoid logging many messages about
+ * a failing supplier
+ */
+ private final Set<Object> flakySuppliers = new HashSet<Object>();
+
+ /////////////////////// Constructors ///////////////////////
+
+ /** factory method to create a class that implements Statistics
+ */
+ public static Statistics createAtomicNoOS(StatisticsType type, String textId,
+ long numericId, long uniqueId,
+ StatisticsManager mgr) {
+ return Atomics.createAtomicStatistics(type, textId, numericId, uniqueId, mgr);
+ }
+ /**
+ * Creates a new statistics instance of the given type and unique id
+ *
+ * @param type
+ * A description of the statistics
+ * @param textId
+ * Text that helps identifies this instance
+ * @param numericId
+ * A number that helps identify this instance
+ * @param uniqueId
+ * A number that uniquely identifies this instance
+ * @param osStatFlags
+ * Non-zero if stats require system calls to collect them; for internal use only
+ */
+ public StatisticsImpl(StatisticsType type, String textId,
+ long numericId, long uniqueId, int osStatFlags) {
+ this.type = (StatisticsTypeImpl)type;
+ this.textId = textId;
+ this.numericId = numericId;
+ this.uniqueId = uniqueId;
+ this.osStatFlags = osStatFlags;
+ closed = false;
+ }
+
+ ////////////////////// Instance Methods //////////////////////
+
+ public final boolean usesSystemCalls() {
+ return this.osStatFlags != 0;
+ }
+
+ public final int getOsStatFlags() {
+ return this.osStatFlags;
+ }
+
+ public final int nameToId(String name) {
+ return this.type.nameToId(name);
+ }
+
+ public final StatisticDescriptor nameToDescriptor(String name) {
+ return this.type.nameToDescriptor(name);
+ }
+
+ public void close() {
+ this.closed = true;
+ }
+
+ public final boolean isClosed() {
+ return this.closed;
+ }
+
+ public abstract boolean isAtomic();
+
+ private final boolean isOpen() { // fix for bug 29973
+ return !this.closed;
+ }
+
+ //////////////////////// attribute Methods ///////////////////////
+
+ public final StatisticsType getType() {
+ return this.type;
+ }
+ public final String getTextId() {
+ return this.textId;
+ }
+ public final long getNumericId() {
+ return this.numericId;
+ }
+
+ /**
+ * Gets the unique id for this resource
+ */
+ public long getUniqueId() {
+ return this.uniqueId;
+ }
+ /**
+ * Sets a unique id for this resource.
+ */
+ public void setUniqueId(long uid) {
+ this.uniqueId = uid;
+ }
+
+ //////////////////////// set() Methods ///////////////////////
+
+ public final void setInt(String name, int value) {
+ setInt(nameToDescriptor(name), value);
+ }
+
+ public final void setInt(StatisticDescriptor descriptor, int value) {
+ setInt(getIntId(descriptor), value);
+ }
+
+ public final void setInt(int id, int value) {
+ if (isOpen()) {
+ _setInt(id, value);
+ }
+ }
+
+ /**
+ * Sets the value of a statistic of type <code>int</code> at the
+ * given offset, but performs no type checking.
+ */
+ protected abstract void _setInt(int offset, int value);
+
+ public final void setLong(String name, long value) {
+ setLong(nameToDescriptor(name), value);
+ }
+
+ public final void setLong(StatisticDescriptor descriptor, long value) {
+ setLong(getLongId(descriptor), value);
+ }
+
+ public final void setLong(int id, long value) {
+ if (isOpen()) {
+ _setLong(id, value);
+ }
+ }
+
+ /**
+ * Sets the value of a statistic of type <code>long</code> at the
+ * given offset, but performs no type checking.
+ */
+ protected abstract void _setLong(int offset, long value);
+
+ public final void setDouble(String name, double value) {
+ setDouble(nameToDescriptor(name), value);
+ }
+
+ public final void setDouble(StatisticDescriptor descriptor, double value) {
+ setDouble(getDoubleId(descriptor), value);
+ }
+
+ public final void setDouble(int id, double value) {
+ if (isOpen()) {
+ _setDouble(id, value);
+ }
+ }
+
+ /**
+ * Sets the value of a statistic of type <code>double</code> at the
+ * given offset, but performs no type checking.
+ */
+ protected abstract void _setDouble(int offset, double value);
+
+ /////////////////////// get() Methods ///////////////////////
+
+ public final int getInt(String name) {
+ return getInt(nameToDescriptor(name));
+ }
+
+ public final int getInt(StatisticDescriptor descriptor) {
+ return getInt(getIntId(descriptor));
+ }
+
+ public final int getInt(int id) {
+ if (isOpen()) {
+ return _getInt(id);
+ } else {
+ return 0;
+ }
+ }
+
+ /**
+ * Returns the value of the statistic of type <code>int</code> at
+ * the given offset, but performs no type checking.
+ */
+ protected abstract int _getInt(int offset);
+
+
+ public final long getLong(String name) {
+ return getLong(nameToDescriptor(name));
+ }
+
+ public final long getLong(StatisticDescriptor descriptor) {
+ return getLong(getLongId(descriptor));
+ }
+
+ public final long getLong(int id) {
+ if (isOpen()) {
+ return _getLong(id);
+ } else {
+ return 0;
+ }
+ }
+
+
+ /**
+ * Returns the value of the statistic of type <code>long</code> at
+ * the given offset, but performs no type checking.
+ */
+ protected abstract long _getLong(int offset);
+
+ public final double getDouble(String name) {
+ return getDouble(nameToDescriptor(name));
+ }
+
+ public final double getDouble(StatisticDescriptor descriptor) {
+ return getDouble(getDoubleId(descriptor));
+ }
+
+ public final double getDouble(int id) {
+ if (isOpen()) {
+ return _getDouble(id);
+ } else {
+ return 0.0;
+ }
+ }
+
+ /**
+ * Returns the value of the statistic of type <code>double</code> at
+ * the given offset, but performs no type checking.
+ */
+ protected abstract double _getDouble(int offset);
+
+ public final Number get(StatisticDescriptor descriptor) {
+ if (isOpen()) {
+ return _get((StatisticDescriptorImpl)descriptor);
+ } else {
+ return Integer.valueOf(0);
+ }
+ }
+
+ public final Number get(String name) {
+ return get(nameToDescriptor(name));
+ }
+
+ public long getRawBits(StatisticDescriptor descriptor) {
+ if (isOpen()) {
+ return _getRawBits((StatisticDescriptorImpl)descriptor);
+ } else {
+ return 0;
+ }
+ }
+
+ public long getRawBits(String name) {
+ return getRawBits(nameToDescriptor(name));
+ }
+
+ //////////////////////// inc() Methods ////////////////////////
+
+ public final void incInt(String name, int delta) {
+ incInt(nameToDescriptor(name), delta);
+ }
+
+ public final void incInt(StatisticDescriptor descriptor, int delta) {
+ incInt(getIntId(descriptor), delta);
+ }
+
+ public final void incInt(int id, int delta) {
+ if (isOpen()) {
+ _incInt(id, delta);
+ }
+ }
+
+ /**
+ * Increments the value of the statistic of type <code>int</code> at
+ * the given offset by a given amount, but performs no type checking.
+ */
+ protected abstract void _incInt(int offset, int delta);
+
+ public final void incLong(String name, long delta) {
+ incLong(nameToDescriptor(name), delta);
+ }
+ public final void incLong(StatisticDescriptor descriptor, long delta) {
+ incLong(getLongId(descriptor), delta);
+ }
+ public final void incLong(int id, long delta) {
+ if (isOpen()) {
+ _incLong(id, delta);
+ }
+ }
+
+ /**
+ * Increments the value of the statistic of type <code>long</code> at
+ * the given offset by a given amount, but performs no type checking.
+ */
+ protected abstract void _incLong(int offset, long delta);
+
+ public final void incDouble(String name, double delta) {
+ incDouble(nameToDescriptor(name), delta);
+ }
+
+ public final void incDouble(StatisticDescriptor descriptor, double delta) {
+ incDouble(getDoubleId(descriptor), delta);
+ }
+
+ public final void incDouble(int id, double delta) {
+ if (isOpen()) {
+ _incDouble(id, delta);
+ }
+ }
+
+ /**
+ * Increments the value of the statistic of type <code>double</code> at
+ * the given offset by a given amount, but performs no type checking.
+ */
+ protected abstract void _incDouble(int offset, double delta);
+
+ /**
+ * For internal use only.
+ * Tells the implementation to prepare the data in this instance
+ * for sampling.
+ * @since GemFire 5.1
+ */
+ public void prepareForSample() {
+ // nothing needed in this impl.
+ }
+
+ /**
+ * Invoke sample suppliers to retrieve the current value for
+ * the suppler controlled sets and update the stats to reflect
+ * the supplied values.
+ * @return the number of callback errors that occurred while
+ * sampling stats
+ */
+ public int invokeSuppliers() {
+ int errors = 0;
+ for(Map.Entry<Integer, IntSupplier> entry: intSuppliers.entrySet()) {
+ try {
+ _setInt(entry.getKey(), entry.getValue().getAsInt());
+ } catch(Throwable t) {
+ logSupplierError(t, entry.getKey(), entry.getValue());
+ errors++;
+ }
+ }
+ for(Map.Entry<Integer, LongSupplier> entry: longSuppliers.entrySet()) {
+ try {
+ _setLong(entry.getKey(), entry.getValue().getAsLong());
+ } catch(Throwable t) {
+ logSupplierError(t, entry.getKey(), entry.getValue());
+ errors++;
+ }
+ }
+ for(Map.Entry<Integer, DoubleSupplier> entry: doubleSuppliers.entrySet()) {
+ try {
+ _setDouble(entry.getKey(), entry.getValue().getAsDouble());
+ } catch(Throwable t) {
+ logSupplierError(t, entry.getKey(), entry.getValue());
+ errors++;
+ }
+ }
+
+ return errors;
+ }
+
+ private void logSupplierError(final Throwable t, int statId, Object supplier) {
+ if(flakySuppliers.add(supplier)) {
+ logger.warn("Error invoking supplier for stat {}, id {}", this.getTextId(), statId, t);
+ }
+ }
+
+ /**
+ * @return the number of statistics that are measured using supplier callbacks
+ */
+ public int getSupplierCount() {
+ return intSuppliers.size() + doubleSuppliers.size() + longSuppliers.size();
+ }
+
+ @Override
+ public IntSupplier setIntSupplier(final int id, final IntSupplier supplier) {
+ if(id >= type.getIntStatCount()) {
+ throw new IllegalArgumentException("Id " + id + " is not in range for stat" + type);
+ }
+ return intSuppliers.put(id, supplier);
+ }
+
+ @Override
+ public IntSupplier setIntSupplier(final String name, final IntSupplier supplier) {
+ return setIntSupplier(nameToId(name), supplier);
+ }
+
+ @Override
+ public IntSupplier setIntSupplier(final StatisticDescriptor descriptor, final IntSupplier supplier) {
+ return setIntSupplier(getIntId(descriptor), supplier);
+ }
+
+ @Override
+ public LongSupplier setLongSupplier(final int id, final LongSupplier supplier) {
+ if(id >= type.getLongStatCount()) {
+ throw new IllegalArgumentException("Id " + id + " is not in range for stat" + type);
+ }
+ return longSuppliers.put(id, supplier);
+ }
+
+ @Override
+ public LongSupplier setLongSupplier(final String name, final LongSupplier supplier) {
+ return setLongSupplier(nameToId(name), supplier);
+ }
+
+ @Override
+ public LongSupplier setLongSupplier(final StatisticDescriptor descriptor, final LongSupplier supplier) {
+ return setLongSupplier(getLongId(descriptor), supplier);
+ }
+
+ @Override
+ public DoubleSupplier setDoubleSupplier(final int id, final DoubleSupplier supplier) {
+ if(id >= type.getDoubleStatCount()) {
+ throw new IllegalArgumentException("Id " + id + " is not in range for stat" + type);
+ }
+ return doubleSuppliers.put(id, supplier);
+ }
+
+ @Override
+ public DoubleSupplier setDoubleSupplier(final String name, final DoubleSupplier supplier) {
+ return setDoubleSupplier(nameToId(name), supplier);
+ }
+
+ @Override
+ public DoubleSupplier setDoubleSupplier(final StatisticDescriptor descriptor, final DoubleSupplier supplier) {
+ return setDoubleSupplier(getDoubleId(descriptor), supplier);
+ }
+
+ @Override
+ public int hashCode() {
+ return (int)this.uniqueId;
+ }
+ @Override
+ public boolean equals(Object o) {
+ if (o == null) {
+ return false;
+ }
+ if (!(o instanceof StatisticsImpl)) {
+ return false;
+ }
+ StatisticsImpl other = (StatisticsImpl)o;
+ return this.uniqueId == other.getUniqueId();
+ }
+
+ private final static int getIntId(StatisticDescriptor descriptor) {
+ return ((StatisticDescriptorImpl)descriptor).checkInt();
+ }
+
+ private final static int getLongId(StatisticDescriptor descriptor) {
+ return ((StatisticDescriptorImpl)descriptor).checkLong();
+ }
+
+ private final static int getDoubleId(StatisticDescriptor descriptor) {
+ return ((StatisticDescriptorImpl)descriptor).checkDouble();
+ }
+
+ /**
+ * Returns the value of the specified statistic descriptor.
+ */
+ private final Number _get(StatisticDescriptorImpl stat) {
+ switch (stat.getTypeCode()) {
+ case StatisticDescriptorImpl.INT:
+ return Integer.valueOf(_getInt(stat.getId()));
+ case StatisticDescriptorImpl.LONG:
+ return Long.valueOf(_getLong(stat.getId()));
+ case StatisticDescriptorImpl.DOUBLE:
+ return Double.valueOf(_getDouble(stat.getId()));
+ default:
+ throw new RuntimeException(LocalizedStrings.StatisticsImpl_UNEXPECTED_STAT_DESCRIPTOR_TYPE_CODE_0.toLocalizedString(Byte.valueOf(stat.getTypeCode())));
+ }
+ }
+ /**
+ * Returns the bits that represent the raw value of the
+ * specified statistic descriptor.
+ */
+ private final long _getRawBits(StatisticDescriptorImpl stat) {
+ switch (stat.getTypeCode()) {
+ case StatisticDescriptorImpl.INT:
+ return _getInt(stat.getId());
+ case StatisticDescriptorImpl.LONG:
+ return _getLong(stat.getId());
+ case StatisticDescriptorImpl.DOUBLE:
+ return Double.doubleToRawLongBits(_getDouble(stat.getId()));
+ default:
+ throw new RuntimeException(LocalizedStrings.StatisticsImpl_UNEXPECTED_STAT_DESCRIPTOR_TYPE_CODE_0.toLocalizedString(Byte.valueOf(stat.getTypeCode())));
+ }
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder(getClass().getName());
+ sb.append("@").append(System.identityHashCode(this)).append("{");
+ sb.append("uniqueId=").append(this.uniqueId);
+ sb.append(", numericId=").append(this.numericId);
+ sb.append(", textId=").append(this.textId);
+ sb.append(", type=").append(this.type.getName());
+ sb.append(", closed=").append(this.closed);
+ sb.append("}");
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsManager.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsManager.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsManager.java
new file mode 100644
index 0000000..9257271
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsManager.java
@@ -0,0 +1,78 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import java.util.List;
+
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsFactory;
+
+/**
+ * Defines the contract that a statistics factory must implement
+ * for its Statistics instances. This is an internal implementation
+ * specific interface.
+ *
+ *
+ */
+public interface StatisticsManager extends StatisticsFactory {
+ /**
+ * Called when the Statistics instance <code>s</code> is closed.
+ */
+ public void destroyStatistics(Statistics s);
+ /**
+ * Returns a name that can be used to identify the manager
+ */
+ public String getName();
+ /**
+ * Returns a numeric id that can be used to identify the manager
+ */
+ public long getId();
+ /**
+ * Returns the start time of this manager.
+ */
+ public long getStartTime();
+ /**
+ * Returns a value that changes any time a Statistics instance is added
+ * or removed from this manager.
+ */
+ public int getStatListModCount();
+ /**
+ * Returns a list of all the Statistics this manager is currently managing.
+ */
+ public List<Statistics> getStatsList();
+
+ /**
+ * Returns the current number of statistics instances.
+ */
+ public int getStatisticsCount();
+
+ /**
+ * Returns the statistics resource instance given its id.
+ */
+ public Statistics findStatistics(long id);
+
+ /**
+ * Returns true if the specified statistic resource still exists.
+ */
+ public boolean statisticsExists(long id);
+
+ /**
+ * Returns an array of all the current statistic resource instances.
+ */
+ public Statistics[] getStatistics();
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeFactoryImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeFactoryImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeFactoryImpl.java
new file mode 100644
index 0000000..8450dd3
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatisticsTypeFactoryImpl.java
@@ -0,0 +1,140 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+
+import java.io.*;
+import java.util.*;
+
+/**
+ * The implementation of {@link StatisticsTypeFactory}.
+ * Each VM can any have a single instance of this class which can
+ * be accessed by calling {@link #singleton()}.
+ *
+ * @see <A href="package-summary.html#statistics">Package introduction</A>
+ *
+ *
+ * @since GemFire 3.0
+ *
+ */
+public class StatisticsTypeFactoryImpl implements StatisticsTypeFactory {
+ // static fields
+ private final static StatisticsTypeFactoryImpl singleton = new StatisticsTypeFactoryImpl();
+
+ // static methods
+ /**
+ * Returns the single instance of this class.
+ */
+ public final static StatisticsTypeFactory singleton() {
+ return singleton;
+ }
+
+ protected final static void clear() {
+ singleton.statTypes.clear();
+ }
+
+ // constructors
+ private StatisticsTypeFactoryImpl() {
+ }
+
+ // instance fields
+ private final HashMap statTypes = new HashMap();
+
+ // instance methods
+ /**
+ * Adds an already created type. If the type has already been
+ * added and is equal to the new one then the new one is dropped and the existing one returned.
+ * @throws IllegalArgumentException if the type already exists and is not equal to the new type
+ */
+ public StatisticsType addType(StatisticsType t) {
+ StatisticsType result = t;
+ synchronized (this.statTypes) {
+ StatisticsType currentValue = findType(result.getName());
+ if (currentValue == null) {
+ this.statTypes.put(result.getName(), result);
+ } else if (result.equals(currentValue)) {
+ result = currentValue;
+ } else {
+ throw new IllegalArgumentException(LocalizedStrings.StatisticsTypeFactoryImpl_STATISTICS_TYPE_NAMED_0_ALREADY_EXISTS.toLocalizedString(result.getName()));
+ }
+ }
+ return result;
+ }
+ public StatisticsType createType(String name, String description,
+ StatisticDescriptor[] stats) {
+ return addType(new StatisticsTypeImpl(name, description, stats));
+ }
+ public StatisticsType findType(String name) {
+ return (StatisticsType)this.statTypes.get(name);
+ }
+ public StatisticsType[] createTypesFromXml(Reader reader)
+ throws IOException {
+ return StatisticsTypeImpl.fromXml(reader, this);
+ }
+
+ public StatisticDescriptor createIntCounter(String name, String description,
+ String units) {
+ return StatisticDescriptorImpl.createIntCounter(name, description, units, true);
+ }
+ public StatisticDescriptor createLongCounter(String name, String description,
+ String units) {
+ return StatisticDescriptorImpl.createLongCounter(name, description, units, true);
+ }
+ public StatisticDescriptor createDoubleCounter(String name, String description,
+ String units) {
+ return StatisticDescriptorImpl.createDoubleCounter(name, description, units, true);
+ }
+ public StatisticDescriptor createIntGauge(String name, String description,
+ String units) {
+ return StatisticDescriptorImpl.createIntGauge(name, description, units, false);
+ }
+ public StatisticDescriptor createLongGauge(String name, String description,
+ String units) {
+ return StatisticDescriptorImpl.createLongGauge(name, description, units, false);
+ }
+ public StatisticDescriptor createDoubleGauge(String name, String description,
+ String units) {
+ return StatisticDescriptorImpl.createDoubleGauge(name, description, units, false);
+ }
+
+ public StatisticDescriptor createIntCounter(String name, String description,
+ String units, boolean largerBetter) {
+ return StatisticDescriptorImpl.createIntCounter(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createLongCounter(String name, String description,
+ String units, boolean largerBetter) {
+ return StatisticDescriptorImpl.createLongCounter(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createDoubleCounter(String name, String description,
+ String units, boolean largerBetter) {
+ return StatisticDescriptorImpl.createDoubleCounter(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createIntGauge(String name, String description,
+ String units, boolean largerBetter) {
+ return StatisticDescriptorImpl.createIntGauge(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createLongGauge(String name, String description,
+ String units, boolean largerBetter) {
+ return StatisticDescriptorImpl.createLongGauge(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createDoubleGauge(String name, String description,
+ String units, boolean largerBetter) {
+ return StatisticDescriptorImpl.createDoubleGauge(name, description, units, largerBetter);
+ }
+}
[22/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
GEODE-1781: refactor internal statistics classes
* move internal statistics classes into com.gemstone.gemfire.internal.
statistics
* move statistics tests into com.gemstone.gemfire.internal.statistics
* modify tests to include integration and distributed in names
* modify tests to use TemporaryFolder and TestName rules
Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/11507012
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/11507012
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/11507012
Branch: refs/heads/feature/GEODE-1781-02
Commit: 115070123ec15638ca1189a7349938c35e0d51e0
Parents: a5daa92
Author: Kirk Lund <kl...@Kirks-MacBook-Pro.local>
Authored: Mon Aug 15 18:26:16 2016 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Wed Aug 17 15:44:51 2016 -0700
----------------------------------------------------------------------
.../internal/DeltaSessionStatistics.java | 2 +-
.../gemfire/modules/util/ModuleStatistics.java | 2 +-
.../com/gemstone/gemfire/StatisticsFactory.java | 2 +-
.../gemstone/gemfire/StatisticsTypeFactory.java | 2 +-
.../admin/internal/MemberHealthEvaluator.java | 2 +
.../internal/AsyncEventQueueStats.java | 2 +-
.../cache/client/internal/ConnectionStats.java | 2 +-
.../client/internal/EndpointManagerImpl.java | 2 +-
.../gemfire/cache/client/internal/PoolImpl.java | 2 +-
.../cache/query/internal/CqQueryVsdStats.java | 2 +-
.../cache/query/internal/index/IndexStats.java | 2 +-
.../distributed/internal/DistributionStats.java | 2 +-
.../internal/InternalDistributedSystem.java | 8 +
.../distributed/internal/LocatorStats.java | 2 +-
.../distributed/internal/locks/DLockStats.java | 2 +-
.../internal/AbstractStatisticsFactory.java | 327 --
.../gemfire/internal/ArchiveSplitter.java | 522 ---
.../internal/DummyStatisticsFactory.java | 134 -
.../gemfire/internal/DummyStatisticsImpl.java | 242 --
.../gemfire/internal/GemFireStatSampler.java | 502 ---
.../gemfire/internal/HostStatHelper.java | 289 --
.../gemfire/internal/HostStatSampler.java | 550 ---
.../gemfire/internal/LinuxProcFsStatistics.java | 783 ----
.../gemfire/internal/LinuxProcessStats.java | 79 -
.../gemfire/internal/LinuxSystemStats.java | 311 --
.../gemfire/internal/LocalStatListener.java | 40 -
.../internal/LocalStatisticsFactory.java | 99 -
.../gemfire/internal/LocalStatisticsImpl.java | 268 --
.../gemfire/internal/OSXProcessStats.java | 83 -
.../gemfire/internal/OSXSystemStats.java | 228 --
.../gemfire/internal/OsStatisticsFactory.java | 41 -
.../gemstone/gemfire/internal/ProcessStats.java | 60 -
.../gemfire/internal/SimpleStatSampler.java | 112 -
.../gemfire/internal/SolarisProcessStats.java | 217 --
.../gemfire/internal/SolarisSystemStats.java | 428 ---
.../gemfire/internal/StatArchiveFormat.java | 197 --
.../gemfire/internal/StatArchiveReader.java | 3338 -----------------
.../gemfire/internal/StatArchiveWriter.java | 733 ----
.../gemfire/internal/StatSamplerStats.java | 153 -
.../internal/StatisticDescriptorImpl.java | 383 --
.../gemfire/internal/StatisticsImpl.java | 589 ---
.../gemfire/internal/StatisticsManager.java | 78 -
.../internal/StatisticsTypeFactoryImpl.java | 140 -
.../gemfire/internal/StatisticsTypeImpl.java | 258 --
.../gemfire/internal/StatisticsTypeXml.java | 280 --
.../gemstone/gemfire/internal/SystemAdmin.java | 7 +-
.../com/gemstone/gemfire/internal/VMStats.java | 87 -
.../gemfire/internal/VMStatsContract.java | 36 -
.../internal/VMStatsContractFactory.java | 60 -
.../gemfire/internal/WindowsProcessStats.java | 160 -
.../gemfire/internal/WindowsSystemStats.java | 267 --
.../admin/remote/AddStatListenerResponse.java | 2 +-
.../remote/AdminConsoleDisconnectMessage.java | 2 +-
.../remote/CancelStatListenerResponse.java | 2 +-
.../internal/admin/remote/RemoteStat.java | 2 +-
.../gemfire/internal/admin/remote/package.html | 2 +-
.../gemfire/internal/cache/CachePerfStats.java | 1 +
.../internal/cache/DiskDirectoryStats.java | 2 +-
.../gemfire/internal/cache/DiskRegionStats.java | 2 +-
.../gemfire/internal/cache/DiskStoreStats.java | 2 +-
.../internal/cache/PartitionedRegionStats.java | 2 +-
.../gemfire/internal/cache/PoolStats.java | 2 +-
.../cache/control/HeapMemoryMonitor.java | 8 +-
.../cache/control/ResourceManagerStats.java | 2 +-
.../cache/execute/FunctionServiceStats.java | 4 +-
.../internal/cache/execute/FunctionStats.java | 5 +-
.../internal/cache/ha/HARegionQueueStats.java | 2 +-
.../cache/lru/HeapLRUCapacityController.java | 2 +-
.../cache/lru/LRUCapacityController.java | 2 +-
.../cache/lru/MemLRUCapacityController.java | 2 +-
.../cache/tier/sockets/CacheClientNotifier.java | 2 +-
.../tier/sockets/CacheClientNotifierStats.java | 3 +-
.../tier/sockets/CacheClientProxyStats.java | 2 +-
.../cache/tier/sockets/CacheClientUpdater.java | 1 +
.../cache/tier/sockets/CacheServerStats.java | 11 +-
.../internal/cache/wan/GatewaySenderStats.java | 2 +-
.../gemfire/internal/concurrent/Atomics.java | 6 +-
.../internal/offheap/OffHeapStorage.java | 2 +-
.../statistics/AbstractStatisticsFactory.java | 327 ++
.../internal/statistics/ArchiveSplitter.java | 522 +++
.../internal/statistics/CallbackSampler.java | 3 -
.../statistics/DummyStatisticsFactory.java | 135 +
.../statistics/DummyStatisticsImpl.java | 242 ++
.../internal/statistics/GemFireStatSampler.java | 507 +++
.../internal/statistics/HostStatHelper.java | 303 ++
.../internal/statistics/HostStatSampler.java | 549 +++
.../statistics/IgnoreResourceException.java | 2 +-
.../internal/statistics/LocalStatListener.java | 40 +
.../statistics/LocalStatisticsFactory.java | 103 +
.../statistics/LocalStatisticsImpl.java | 272 ++
.../internal/statistics/ResourceInstance.java | 2 +-
.../internal/statistics/ResourceType.java | 2 +-
.../internal/statistics/SimpleStatSampler.java | 112 +
.../statistics/StatArchiveDescriptor.java | 4 +-
.../internal/statistics/StatArchiveFormat.java | 197 ++
.../internal/statistics/StatArchiveHandler.java | 9 +-
.../statistics/StatArchiveHandlerConfig.java | 2 +-
.../internal/statistics/StatArchiveReader.java | 3339 ++++++++++++++++++
.../internal/statistics/StatArchiveWriter.java | 732 ++++
.../internal/statistics/StatSamplerStats.java | 153 +
.../statistics/StatisticDescriptorImpl.java | 383 ++
.../internal/statistics/StatisticsImpl.java | 588 +++
.../internal/statistics/StatisticsManager.java | 78 +
.../statistics/StatisticsTypeFactoryImpl.java | 140 +
.../internal/statistics/StatisticsTypeImpl.java | 258 ++
.../internal/statistics/StatisticsTypeXml.java | 282 ++
.../gemfire/internal/statistics/VMStats.java | 87 +
.../internal/statistics/VMStatsContract.java | 36 +
.../statistics/VMStatsContractFactory.java | 60 +
.../internal/statistics/ValueMonitor.java | 1 -
.../gemfire/internal/statistics/package.html | 4 +-
.../platform/LinuxProcFsStatistics.java | 783 ++++
.../statistics/platform/LinuxProcessStats.java | 84 +
.../statistics/platform/LinuxSystemStats.java | 313 ++
.../statistics/platform/OSXProcessStats.java | 87 +
.../statistics/platform/OSXSystemStats.java | 230 ++
.../platform/OsStatisticsFactory.java | 41 +
.../statistics/platform/ProcessStats.java | 60 +
.../platform/SolarisProcessStats.java | 222 ++
.../statistics/platform/SolarisSystemStats.java | 430 +++
.../platform/WindowsProcessStats.java | 165 +
.../statistics/platform/WindowsSystemStats.java | 269 ++
.../stats50/Atomic50StatisticsImpl.java | 4 +
.../gemfire/internal/stats50/VMStats50.java | 4 +-
.../internal/beans/MemberMBeanBridge.java | 8 +
.../com/gemstone/gemfire/GemFireTestCase.java | 91 -
.../java/com/gemstone/gemfire/Invariant.java | 31 -
.../com/gemstone/gemfire/InvariantResult.java | 27 -
.../gemfire/LocalStatisticsJUnitTest.java | 50 -
.../gemstone/gemfire/StatisticsTestCase.java | 388 --
.../gemfire/StatisticsTypeJUnitTest.java | 76 -
.../MemberHealthEvaluatorJUnitTest.java | 4 +-
.../management/MemoryThresholdsDUnitTest.java | 6 +-
.../codeAnalysis/decode/CompiledClass.java | 2 +-
.../internal/DataSerializableJUnitTest.java | 1 +
.../internal/GemFireStatSamplerJUnitTest.java | 612 ----
.../internal/LocalStatisticsImplJUnitTest.java | 139 -
.../internal/SimpleStatSamplerJUnitTest.java | 357 --
.../StatArchiveWriterReaderJUnitTest.java | 1728 ---------
.../gemfire/internal/StatSamplerJUnitTest.java | 367 --
.../gemfire/internal/StatSamplerTestCase.java | 184 -
.../internal/cache/lru/LRUClockJUnitTest.java | 2 +-
.../offheap/OffHeapStorageJUnitTest.java | 2 +-
.../statistics/CallbackSamplerJUnitTest.java | 98 -
.../statistics/CallbackSamplerTest.java | 98 +
...tributedSystemStatisticsIntegrationTest.java | 271 ++
...utedSystemStatisticsTypeIntegrationTest.java | 90 +
.../GemFireStatSamplerIntegrationTest.java | 612 ++++
.../statistics/SampleCollectorJUnitTest.java | 322 --
.../statistics/SampleCollectorTest.java | 322 ++
.../SimpleStatSamplerIntegrationTest.java | 351 ++
.../StatArchiveWriterReaderIntegrationTest.java | 1634 +++++++++
.../statistics/StatMonitorHandlerJUnitTest.java | 236 --
.../statistics/StatMonitorHandlerTest.java | 235 ++
.../statistics/StatSamplerIntegrationTest.java | 363 ++
.../statistics/StatSamplerTestCase.java | 185 +
.../statistics/StatisticsDUnitTest.java | 947 -----
.../statistics/StatisticsDistributedTest.java | 851 +++++
.../internal/statistics/StatisticsImplTest.java | 136 +
.../statistics/StatisticsMonitorJUnitTest.java | 198 --
.../statistics/StatisticsMonitorTest.java | 198 ++
.../statistics/TestStatArchiveWriter.java | 6 +-
.../statistics/TestStatisticsManager.java | 13 +-
.../statistics/TestStatisticsSampler.java | 13 +-
.../statistics/ValueMonitorIntegrationTest.java | 367 ++
.../statistics/ValueMonitorJUnitTest.java | 370 --
.../internal/stats50/AtomicStatsJUnitTest.java | 2 +-
.../bean/stats/MemberLevelStatsJUnitTest.java | 2 +-
...st_testWriteAfterSamplingBegins_expected.gfs | Bin 1970 -> 0 bytes
...est_testWriteWhenSamplingBegins_expected.gfs | Bin 1933 -> 0 bytes
...st_testWriteAfterSamplingBegins_expected.gfs | Bin 0 -> 1976 bytes
...est_testWriteWhenSamplingBegins_expected.gfs | Bin 0 -> 1939 bytes
.../query/internal/cq/CqServiceVsdStats.java | 4 +-
.../cache/lucene/internal/LuceneIndexStats.java | 2 +-
.../internal/filesystem/FileSystemStats.java | 2 +-
.../util/AutoBalancerIntegrationJUnitTest.java | 2 +-
176 files changed, 17957 insertions(+), 18408 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/session/catalina/internal/DeltaSessionStatistics.java
----------------------------------------------------------------------
diff --git a/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/session/catalina/internal/DeltaSessionStatistics.java b/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/session/catalina/internal/DeltaSessionStatistics.java
index 2d59103..99a3a83 100644
--- a/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/session/catalina/internal/DeltaSessionStatistics.java
+++ b/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/session/catalina/internal/DeltaSessionStatistics.java
@@ -21,7 +21,7 @@ import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
public class DeltaSessionStatistics {
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/util/ModuleStatistics.java
----------------------------------------------------------------------
diff --git a/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/util/ModuleStatistics.java b/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/util/ModuleStatistics.java
index 82e882c..48020a3 100644
--- a/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/util/ModuleStatistics.java
+++ b/extensions/geode-modules/src/main/java/com/gemstone/gemfire/modules/util/ModuleStatistics.java
@@ -22,7 +22,7 @@ import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.distributed.DistributedSystem;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* Statistics for modules.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/StatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/StatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/StatisticsFactory.java
index 3ef5ba5..3ba1665 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/StatisticsFactory.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/StatisticsFactory.java
@@ -17,7 +17,7 @@
package com.gemstone.gemfire;
//import com.gemstone.gemfire.distributed.DistributedSystem;
-//import com.gemstone.gemfire.internal.StatArchiveFormat;
+//import com.gemstone.gemfire.internal.statistics.StatArchiveFormat;
//import java.io.IOException;
//import java.io.Reader;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/StatisticsTypeFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/StatisticsTypeFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/StatisticsTypeFactory.java
index 9b6c546..4569b7e 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/StatisticsTypeFactory.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/StatisticsTypeFactory.java
@@ -17,7 +17,7 @@
package com.gemstone.gemfire;
//import com.gemstone.gemfire.distributed.DistributedSystem;
-import com.gemstone.gemfire.internal.StatArchiveFormat;
+import com.gemstone.gemfire.internal.statistics.StatArchiveFormat;
import java.io.IOException;
import java.io.Reader;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluator.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluator.java b/geode-core/src/main/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluator.java
index d0710ca..5344724 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluator.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluator.java
@@ -24,6 +24,8 @@ import com.gemstone.gemfire.internal.*;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.internal.cache.CachePerfStats;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
import java.util.*;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/cache/asyncqueue/internal/AsyncEventQueueStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/cache/asyncqueue/internal/AsyncEventQueueStats.java b/geode-core/src/main/java/com/gemstone/gemfire/cache/asyncqueue/internal/AsyncEventQueueStats.java
index 8d541a3..e9e1e0b 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/cache/asyncqueue/internal/AsyncEventQueueStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/cache/asyncqueue/internal/AsyncEventQueueStats.java
@@ -20,7 +20,7 @@ import com.gemstone.gemfire.StatisticDescriptor;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.wan.GatewaySenderStats;
public class AsyncEventQueueStats extends GatewaySenderStats {
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/ConnectionStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/ConnectionStats.java b/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/ConnectionStats.java
index 4bd4439..6aaae2d 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/ConnectionStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/ConnectionStats.java
@@ -22,7 +22,7 @@ import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.PoolStats;
import com.gemstone.gemfire.internal.cache.tier.sockets.MessageStats;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/EndpointManagerImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/EndpointManagerImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/EndpointManagerImpl.java
index d155602..111cec6 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/EndpointManagerImpl.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/EndpointManagerImpl.java
@@ -32,7 +32,7 @@ import com.gemstone.gemfire.cache.client.PoolManager;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.DistributedSystem;
import com.gemstone.gemfire.distributed.internal.ServerLocation;
-import com.gemstone.gemfire.internal.DummyStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.DummyStatisticsFactory;
import com.gemstone.gemfire.internal.cache.PoolStats;
import com.gemstone.gemfire.internal.cache.tier.InternalClientMembership;
import com.gemstone.gemfire.internal.logging.LogService;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/PoolImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/PoolImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/PoolImpl.java
index b26d76b..371098d 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/PoolImpl.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/cache/client/internal/PoolImpl.java
@@ -33,7 +33,7 @@ import com.gemstone.gemfire.distributed.PoolCancelledException;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.ServerLocation;
-import com.gemstone.gemfire.internal.DummyStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.DummyStatisticsFactory;
import com.gemstone.gemfire.internal.ScheduledThreadPoolExecutorWithKeepAlive;
import com.gemstone.gemfire.internal.admin.ClientStatsManager;
import com.gemstone.gemfire.internal.cache.*;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/CqQueryVsdStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/CqQueryVsdStats.java b/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/CqQueryVsdStats.java
index e9d30d5..e65af17 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/CqQueryVsdStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/CqQueryVsdStats.java
@@ -22,7 +22,7 @@ import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.cache.query.CqEvent;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.tier.MessageType;
/**
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/index/IndexStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/index/IndexStats.java b/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/index/IndexStats.java
index 77941b6..84d9b61 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/index/IndexStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/cache/query/internal/index/IndexStats.java
@@ -19,7 +19,7 @@ package com.gemstone.gemfire.cache.query.internal.index;
import com.gemstone.gemfire.*;
//import com.gemstone.gemfire.cache.query.*;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.CachePerfStats;
/**
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionStats.java b/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionStats.java
index c4803ab..dcd4aba 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/DistributionStats.java
@@ -24,7 +24,7 @@ import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.logging.LogService;
//import java.io.*;
import com.gemstone.gemfire.internal.tcp.Buffers;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/InternalDistributedSystem.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/InternalDistributedSystem.java b/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/InternalDistributedSystem.java
index 1ea5611..49a4c97 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/InternalDistributedSystem.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/InternalDistributedSystem.java
@@ -55,6 +55,14 @@ import com.gemstone.gemfire.internal.logging.log4j.LogWriterAppender;
import com.gemstone.gemfire.internal.logging.log4j.LogWriterAppenders;
import com.gemstone.gemfire.internal.offheap.MemoryAllocator;
import com.gemstone.gemfire.internal.offheap.OffHeapStorage;
+import com.gemstone.gemfire.internal.statistics.DummyStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
+import com.gemstone.gemfire.internal.statistics.platform.LinuxProcFsStatistics;
+import com.gemstone.gemfire.internal.statistics.LocalStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.platform.OsStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.StatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsManager;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.tcp.ConnectionTable;
import com.gemstone.gemfire.internal.util.concurrent.StoppableCondition;
import com.gemstone.gemfire.internal.util.concurrent.StoppableReentrantLock;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/LocatorStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/LocatorStats.java b/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/LocatorStats.java
index f59ed84..897b8c3 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/LocatorStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/LocatorStats.java
@@ -17,7 +17,7 @@
package com.gemstone.gemfire.distributed.internal;
import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/locks/DLockStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/locks/DLockStats.java b/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/locks/DLockStats.java
index 9a61c10..ac83d14 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/locks/DLockStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/distributed/internal/locks/DLockStats.java
@@ -18,8 +18,8 @@
package com.gemstone.gemfire.distributed.internal.locks;
import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.*;
import com.gemstone.gemfire.distributed.internal.*;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* This class maintains statistics in GemFire about the distributed lock
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/AbstractStatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/AbstractStatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/AbstractStatisticsFactory.java
deleted file mode 100755
index 972e670e..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/AbstractStatisticsFactory.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.StatisticDescriptor;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsFactory;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-/**
- * An abstract standalone implementation of {@link StatisticsFactory}.
- * It can be used in contexts that do not have the GemFire product
- * or in vm's that do not have a distributed system nor a gemfire connection.
- *
- * @since GemFire 7.0
- */
-public abstract class AbstractStatisticsFactory
- implements StatisticsFactory, StatisticsManager {
-
- private final long id;
- private final String name;
- private final CopyOnWriteArrayList<Statistics> statsList;
- private int statsListModCount = 0;
- private long statsListUniqueId = 1;
- private final Object statsListUniqueIdLock;
- private final StatisticsTypeFactory tf;
- private final long startTime;
-
- public AbstractStatisticsFactory(long id, String name, long startTime) {
- this.id = id;
- this.name = name;
- this.startTime = startTime;
-
- this.statsList = new CopyOnWriteArrayList<Statistics>();
- this.statsListUniqueIdLock = new Object();
- this.tf = StatisticsTypeFactoryImpl.singleton();
- }
-
- public void close() {
- }
-
- @Override
- public final String getName() {
- return this.name;
- }
-
- @Override
- public final long getId() {
- return this.id;
- }
-
- @Override
- public final long getStartTime() {
- return this.startTime;
- }
-
- @Override
- public final int getStatListModCount() {
- return this.statsListModCount;
- }
-
- @Override
- public final List<Statistics> getStatsList() {
- return this.statsList;
- }
-
- @Override
- public final int getStatisticsCount() {
- int result = 0;
- List<Statistics> statsList = this.statsList;
- if (statsList != null) {
- result = statsList.size();
- }
- return result;
- }
-
- @Override
- public final Statistics findStatistics(long id) {
- List<Statistics> statsList = this.statsList;
- synchronized (statsList) {
- for (Statistics s : statsList) {
- if (s.getUniqueId() == id) {
- return s;
- }
- }
- }
- throw new RuntimeException(LocalizedStrings.PureStatSampler_COULD_NOT_FIND_STATISTICS_INSTANCE.toLocalizedString());
- }
-
- @Override
- public final boolean statisticsExists(long id) {
- List<Statistics> statsList = this.statsList;
- for (Statistics s : statsList) {
- if (s.getUniqueId() == id) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public final Statistics[] getStatistics() {
- List<Statistics> statsList = this.statsList;
- return (Statistics[])statsList.toArray(new Statistics[statsList.size()]);
- }
-
- // StatisticsFactory methods
-
- @Override
- public final Statistics createStatistics(StatisticsType type) {
- return createOsStatistics(type, null, 0, 0);
- }
-
- @Override
- public final Statistics createStatistics(StatisticsType type, String textId) {
- return createOsStatistics(type, textId, 0, 0);
- }
-
- @Override
- public final Statistics createStatistics(StatisticsType type, String textId, long numericId) {
- return createOsStatistics(type, textId, 0, 0);
- }
-
- protected Statistics createOsStatistics(StatisticsType type, String textId, long numericId, int osStatFlags) {
- long myUniqueId;
- synchronized (statsListUniqueIdLock) {
- myUniqueId = statsListUniqueId++; // fix for bug 30597
- }
- Statistics result = new LocalStatisticsImpl(type, textId, numericId, myUniqueId, false, osStatFlags, this);
- synchronized (statsList) {
- statsList.add(result);
- statsListModCount++;
- }
- return result;
- }
-
- @Override
- public final Statistics[] findStatisticsByType(StatisticsType type) {
- List<Statistics> hits = new ArrayList<Statistics>();
- Iterator<Statistics> it = statsList.iterator();
- while (it.hasNext()) {
- Statistics s = (Statistics)it.next();
- if (type == s.getType()) {
- hits.add(s);
- }
- }
- Statistics[] result = new Statistics[hits.size()];
- return (Statistics[])hits.toArray(result);
- }
-
- @Override
- public final Statistics[] findStatisticsByTextId(String textId) {
- List<Statistics> hits = new ArrayList<Statistics>();
- Iterator<Statistics> it = statsList.iterator();
- while (it.hasNext()) {
- Statistics s = (Statistics)it.next();
- if (s.getTextId().equals(textId)) {
- hits.add(s);
- }
- }
- Statistics[] result = new Statistics[hits.size()];
- return (Statistics[])hits.toArray(result);
- }
-
- @Override
- public final Statistics[] findStatisticsByNumericId(long numericId) {
- List<Statistics> hits = new ArrayList<Statistics>();
- Iterator<Statistics> it = statsList.iterator();
- while (it.hasNext()) {
- Statistics s = (Statistics)it.next();
- if (numericId == s.getNumericId()) {
- hits.add(s);
- }
- }
- Statistics[] result = new Statistics[hits.size()];
- return (Statistics[])hits.toArray(result);
- }
-
- public final Statistics findStatisticsByUniqueId(long uniqueId) {
- Iterator<Statistics> it = statsList.iterator();
- while (it.hasNext()) {
- Statistics s = (Statistics)it.next();
- if (uniqueId == s.getUniqueId()) {
- return s;
- }
- }
- return null;
- }
-
- /** for internal use only. Its called by {@link LocalStatisticsImpl#close}. */
- @Override
- public final void destroyStatistics(Statistics stats) {
- synchronized (statsList) {
- if (statsList.remove(stats)) {
- statsListModCount++;
- }
- }
- }
-
- @Override
- public final Statistics createAtomicStatistics(StatisticsType type) {
- return createAtomicStatistics(type, null, 0);
- }
-
- @Override
- public final Statistics createAtomicStatistics(StatisticsType type, String textId) {
- return createAtomicStatistics(type, textId, 0);
- }
-
- @Override
- public Statistics createAtomicStatistics(StatisticsType type, String textId, long numericId) {
- long myUniqueId;
- synchronized (statsListUniqueIdLock) {
- myUniqueId = statsListUniqueId++; // fix for bug 30597
- }
- Statistics result = StatisticsImpl.createAtomicNoOS(type, textId, numericId, myUniqueId, this);
- synchronized (statsList) {
- statsList.add(result);
- statsListModCount++;
- }
- return result;
- }
-
- // StatisticsTypeFactory methods
-
- /**
- * Creates or finds a StatisticType for the given shared class.
- */
- @Override
- public final StatisticsType createType(String name, String description, StatisticDescriptor[] stats) {
- return tf.createType(name, description, stats);
- }
-
- @Override
- public final StatisticsType findType(String name) {
- return tf.findType(name);
- }
-
- @Override
- public final StatisticsType[] createTypesFromXml(Reader reader)
- throws IOException {
- return tf.createTypesFromXml(reader);
- }
-
- @Override
- public final StatisticDescriptor createIntCounter(String name, String description, String units) {
- return tf.createIntCounter(name, description, units);
- }
-
- @Override
- public final StatisticDescriptor createLongCounter(String name, String description, String units) {
- return tf.createLongCounter(name, description, units);
- }
-
- @Override
- public final StatisticDescriptor createDoubleCounter(String name, String description, String units) {
- return tf.createDoubleCounter(name, description, units);
- }
-
- @Override
- public final StatisticDescriptor createIntGauge(String name, String description, String units) {
- return tf.createIntGauge(name, description, units);
- }
-
- @Override
- public final StatisticDescriptor createLongGauge(String name, String description, String units) {
- return tf.createLongGauge(name, description, units);
- }
-
- @Override
- public final StatisticDescriptor createDoubleGauge(String name, String description, String units) {
- return tf.createDoubleGauge(name, description, units);
- }
-
- @Override
- public final StatisticDescriptor createIntCounter(String name, String description, String units, boolean largerBetter) {
- return tf.createIntCounter(name, description, units, largerBetter);
- }
-
- @Override
- public final StatisticDescriptor createLongCounter(String name, String description, String units, boolean largerBetter) {
- return tf.createLongCounter(name, description, units, largerBetter);
- }
-
- @Override
- public final StatisticDescriptor createDoubleCounter(String name, String description, String units, boolean largerBetter) {
- return tf.createDoubleCounter(name, description, units, largerBetter);
- }
-
- @Override
- public final StatisticDescriptor createIntGauge(String name, String description, String units, boolean largerBetter) {
- return tf.createIntGauge(name, description, units, largerBetter);
- }
-
- @Override
- public final StatisticDescriptor createLongGauge(String name, String description, String units, boolean largerBetter) {
- return tf.createLongGauge(name, description, units, largerBetter);
- }
-
- @Override
- public final StatisticDescriptor createDoubleGauge(String name, String description, String units, boolean largerBetter) {
- return tf.createDoubleGauge(name, description, units, largerBetter);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/ArchiveSplitter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/ArchiveSplitter.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/ArchiveSplitter.java
deleted file mode 100644
index 28b9dd7..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/ArchiveSplitter.java
+++ /dev/null
@@ -1,522 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-
-import java.io.*;
-//import java.text.*;
-//import java.util.*;
-import java.util.zip.*;
-
-/**
- * ArchiveSplitter provides APIs to read statistic snapshots from an archive
- * file.
- */
-public class ArchiveSplitter implements StatArchiveFormat {
- private final File archiveName;
- private InputStream is;
- private MyFilterInputStream myIs;
- private DataInputStream dataIn;
- private DataOutputStream dataOut;
- private OutputStream output;
- private final static int BUFFER_SIZE = 1024*1024;
- private long splitDuration; // in millis
- private byte[][] resourceTypes = new byte[256][];
- private byte[][] resourceInstanceTypeCodes = new byte[256][];
- private byte[][] resourceInstanceTokens = new byte[256][];
- private long[][] resourceInstanceBits = new long[256][];
- private static final long DEFAULT_SPLIT_DURATION = 24*60*60*1000; // one day
- private long currentDuration = 0; // in millis
- private int splitCount = 0;
- private byte[][] globalTokens = new byte[256][];
- private int globalTokenCount = 0;
-
- // header info
- private byte archiveVersion;
- private long startTimeStamp;
- private long systemId;
- private long systemStartTimeStamp;
- private int timeZoneOffset;
- private String timeZoneName;
- private String systemDirectory;
- private String productVersion;
- private String os;
- private String machine;
-
-
- public ArchiveSplitter(File archiveName) throws IOException {
- this(archiveName, DEFAULT_SPLIT_DURATION);
- }
- public ArchiveSplitter(File archiveName, long splitDuration) throws IOException {
- this.archiveName = archiveName;
- this.splitDuration = splitDuration;
- this.is = new FileInputStream(archiveName);
- boolean compressed = archiveName.getPath().endsWith(".gz");
- if (compressed) {
- this.myIs = new MyFilterInputStream(new BufferedInputStream(new GZIPInputStream(this.is, BUFFER_SIZE), BUFFER_SIZE));
- } else {
- this.myIs = new MyFilterInputStream(new BufferedInputStream(this.is, BUFFER_SIZE));
- }
- this.dataIn = new DataInputStream(this.myIs);
- }
- private void readHeaderToken() throws IOException {
- byte archiveVersion = dataIn.readByte();
- if (archiveVersion <= 1) {
- throw new GemFireIOException(LocalizedStrings.ArchiveSplitter_ARCHIVE_VERSION_0_IS_NO_LONGER_SUPPORTED.toLocalizedString(new Byte(archiveVersion)), null);
- }
- if (archiveVersion > ARCHIVE_VERSION) {
- throw new GemFireIOException(LocalizedStrings.ArchiveSplitter_UNSUPPORTED_ARCHIVE_VERSION_0_THE_SUPPORTED_VERSION_IS_1.toLocalizedString(new Object[] {new Byte(archiveVersion), new Byte(ARCHIVE_VERSION)}), null);
- }
-
- this.archiveVersion = archiveVersion;
- this.startTimeStamp = dataIn.readLong();
- this.systemId = dataIn.readLong();
- this.systemStartTimeStamp = dataIn.readLong();
- this.timeZoneOffset = dataIn.readInt();
- this.timeZoneName = dataIn.readUTF();
- this.systemDirectory = dataIn.readUTF();
- this.productVersion = dataIn.readUTF();
- this.os = dataIn.readUTF();
- this.machine = dataIn.readUTF();
- }
- private void skipBytes(int count) throws IOException {
- int skipped = dataIn.skipBytes(count);
- while (skipped != count) {
- count -= skipped;
- skipped = dataIn.skipBytes(count);
- }
- }
- private void skipBoolean() throws IOException {
- //dataIn.readBoolean();
- skipBytes(1);
- }
-// private void skipByte() throws IOException {
-// //dataIn.readByte();
-// skipBytes(1);
-// }
-// private void skipUByte() throws IOException {
-// //dataIn.readUnsignedByte();
-// skipBytes(1);
-// }
-// private void skipShort() throws IOException {
-// //dataIn.readShort();
-// skipBytes(2);
-// }
-// private void skipUShort() throws IOException {
-// //dataIn.readUnsignedShort();
-// skipBytes(2);
-// }
-// private void skipInt() throws IOException {
-// //dataIn.readInt();
-// skipBytes(4);
-// }
- private void skipLong() throws IOException {
- //dataIn.readLong();
- skipBytes(8);
- }
- private void skipUTF() throws IOException {
- //dataIn.readUTF();
- skipBytes(dataIn.readUnsignedShort());
- }
- private void addGlobalToken(byte[] token) {
- if (globalTokenCount >= globalTokens.length) {
- byte[][] tmp = new byte[globalTokenCount+128][];
- System.arraycopy(globalTokens, 0, tmp, 0, globalTokens.length);
- globalTokens = tmp;
- }
- globalTokens[globalTokenCount] = token;
- globalTokenCount += 1;
- }
- private void readResourceTypeToken() throws IOException {
- int resourceTypeId = dataIn.readInt();
- skipUTF(); //String resourceTypeName = dataIn.readUTF();
- skipUTF(); //String resourceTypeDesc = dataIn.readUTF();
- int statCount = dataIn.readUnsignedShort();
- byte[] typeCodes = new byte[statCount];
-
- for (int i=0; i < statCount; i++) {
- skipUTF(); //String statName = dataIn.readUTF();
- typeCodes[i] = dataIn.readByte();
- skipBoolean(); //boolean isCounter = dataIn.readBoolean();
- if (this.archiveVersion >= 4) {
- skipBoolean(); //boolean largerBetter = dataIn.readBoolean();
- }
- skipUTF(); //String units = dataIn.readUTF();
- skipUTF(); //String desc = dataIn.readUTF();
- }
- if (resourceTypeId >= resourceTypes.length) {
- byte[][] tmp = new byte[resourceTypeId+128][];
- System.arraycopy(resourceTypes, 0, tmp, 0, resourceTypes.length);
- resourceTypes = tmp;
- }
- resourceTypes[resourceTypeId] = typeCodes;
-
- addGlobalToken(this.myIs.getBytes());
- }
- private void readResourceInstanceCreateToken(boolean initialize) throws IOException {
- int resourceInstId = dataIn.readInt();
- skipUTF(); //String name = dataIn.readUTF();
- skipLong(); //long id = dataIn.readLong();
- int resourceTypeId = dataIn.readInt();
-
- if (resourceInstId >= resourceInstanceBits.length) {
- long[][] tmpBits = new long[resourceInstId+128][];
- System.arraycopy(resourceInstanceBits, 0,
- tmpBits, 0, resourceInstanceBits.length);
- resourceInstanceBits = tmpBits;
-
- byte[][] tmpTypeCodes = new byte[resourceInstId+128][];
- System.arraycopy(resourceInstanceTypeCodes, 0,
- tmpTypeCodes, 0, resourceInstanceTypeCodes.length);
- resourceInstanceTypeCodes = tmpTypeCodes;
-
- byte[][] tmpTokens = new byte[resourceInstId+128][];
- System.arraycopy(resourceInstanceTokens, 0,
- tmpTokens, 0, resourceInstanceTokens.length);
- resourceInstanceTokens = tmpTokens;
- }
- byte[] instTypeCodes = resourceTypes[resourceTypeId];
- resourceInstanceTypeCodes[resourceInstId] = instTypeCodes;
- resourceInstanceTokens[resourceInstId] = this.myIs.getBytes();
- resourceInstanceTokens[resourceInstId][0] = RESOURCE_INSTANCE_INITIALIZE_TOKEN;
- long[] instBits = new long[instTypeCodes.length];
- resourceInstanceBits[resourceInstId] = instBits;
- if (initialize) {
- for (int i=0; i < instBits.length; i++) {
- switch (instTypeCodes[i]) {
- case BOOLEAN_CODE:
- case BYTE_CODE:
- case CHAR_CODE:
- instBits[i] = dataIn.readByte();
- break;
- case WCHAR_CODE:
- instBits[i] = dataIn.readUnsignedShort();
- break;
- case SHORT_CODE:
- instBits[i] = dataIn.readShort();
- break;
- case INT_CODE:
- case FLOAT_CODE:
- case LONG_CODE:
- case DOUBLE_CODE:
- instBits[i] = readCompactValue();
- break;
- default:
- throw new IOException(LocalizedStrings.ArchiveSplitter_UNEXPECTED_TYPECODE_VALUE_0.toLocalizedString(new Byte(instTypeCodes[i])));
- }
- }
- }
- }
- private void readResourceInstanceDeleteToken() throws IOException {
- int id = dataIn.readInt();
- resourceInstanceTypeCodes[id] = null;
- resourceInstanceBits[id] = null;
- resourceInstanceTokens[id] = null;
- }
- private int readResourceInstId() throws IOException {
- int token = dataIn.readUnsignedByte();
- if (token <= MAX_BYTE_RESOURCE_INST_ID) {
- return token;
- } else if (token == ILLEGAL_RESOURCE_INST_ID_TOKEN) {
- return ILLEGAL_RESOURCE_INST_ID;
- } else if (token == SHORT_RESOURCE_INST_ID_TOKEN) {
- return dataIn.readUnsignedShort();
- } else { /* token == INT_RESOURCE_INST_ID_TOKEN */
- return dataIn.readInt();
- }
- }
- private void readTimeDelta() throws IOException {
- int millisSinceLastSample = dataIn.readUnsignedShort();
- if (millisSinceLastSample == INT_TIMESTAMP_TOKEN) {
- millisSinceLastSample = dataIn.readInt();
- }
- this.currentDuration += millisSinceLastSample;
- this.startTimeStamp += millisSinceLastSample;
- }
- private long readCompactValue() throws IOException {
- long v = dataIn.readByte();
- if (v < MIN_1BYTE_COMPACT_VALUE) {
- if (v == COMPACT_VALUE_2_TOKEN) {
- v = dataIn.readShort();
- } else {
- int bytesToRead = ((byte)v - COMPACT_VALUE_2_TOKEN) + 2;
- v = dataIn.readByte(); // note the first byte will be a signed byte.
- bytesToRead--;
- while (bytesToRead > 0) {
- v <<= 8;
- v |= dataIn.readUnsignedByte();
- bytesToRead--;
- }
- }
- }
- return v;
- }
- private void readSampleToken() throws IOException {
- readTimeDelta();
- int resourceInstId = readResourceInstId();
- while (resourceInstId != ILLEGAL_RESOURCE_INST_ID) {
- byte[] typeCodes = resourceInstanceTypeCodes[resourceInstId];
- long[] bits = resourceInstanceBits[resourceInstId];
- int statOffset = dataIn.readUnsignedByte();
- while (statOffset != ILLEGAL_STAT_OFFSET) {
- long statDeltaBits;
- switch (typeCodes[statOffset]) {
- case BOOLEAN_CODE:
- case BYTE_CODE:
- case CHAR_CODE:
- statDeltaBits = dataIn.readByte();
- break;
- case WCHAR_CODE:
- statDeltaBits = dataIn.readUnsignedShort();
- break;
- case SHORT_CODE:
- statDeltaBits = dataIn.readShort();
- break;
- case INT_CODE:
- case FLOAT_CODE:
- case LONG_CODE:
- case DOUBLE_CODE:
- statDeltaBits = readCompactValue();
- break;
- default:
- throw new IOException(LocalizedStrings.ArchiveSplitter_UNEXPECTED_TYPECODE_VALUE_0.toLocalizedString(new Byte(typeCodes[statOffset])));
- }
- bits[statOffset] += statDeltaBits;
- statOffset = dataIn.readUnsignedByte();
- }
- resourceInstId = readResourceInstId();
- }
- }
- /**
- * Returns true if token read, false if eof.
- */
- private boolean readToken() throws IOException {
- byte token;
- try {
- token = this.dataIn.readByte();
- switch (token) {
- case HEADER_TOKEN:
- readHeaderToken();
- this.myIs.putBytes(this.dataOut);
- break;
- case RESOURCE_TYPE_TOKEN:
- readResourceTypeToken();
- this.myIs.putBytes(this.dataOut);
- break;
- case RESOURCE_INSTANCE_CREATE_TOKEN:
- case RESOURCE_INSTANCE_INITIALIZE_TOKEN:
- readResourceInstanceCreateToken(token == RESOURCE_INSTANCE_INITIALIZE_TOKEN);
- this.myIs.putBytes(this.dataOut);
- break;
- case RESOURCE_INSTANCE_DELETE_TOKEN:
- readResourceInstanceDeleteToken();
- this.myIs.putBytes(this.dataOut);
- break;
- case SAMPLE_TOKEN:
- readSampleToken();
- this.myIs.putBytes(this.dataOut);
- break;
- default:
- throw new IOException(LocalizedStrings.ArchiveSplitter_UNEXPECTED_TOKEN_BYTE_VALUE_0.toLocalizedString(new Byte(token)));
- }
- return true;
- } catch (EOFException ignore) {
- return false;
- }
- }
-
- private File getOutputName() {
- String inName = archiveName.getPath();
- StringBuffer buf = new StringBuffer(inName.length()+4);
- int idx = inName.lastIndexOf('.');
- if (idx == -1) {
- buf.append(inName);
- } else {
- buf.append(inName.substring(0, idx));
- }
- buf.append('-')
- .append(this.splitCount);
- if (idx != -1) {
- buf.append(inName.substring(idx));
- }
- return new File(buf.toString());
- }
-
- private void startSplit() throws IOException {
- this.currentDuration = 0;
- this.splitCount++;
- if (archiveName.getPath().endsWith(".gz")) {
- this.output = new GZIPOutputStream(new FileOutputStream(getOutputName()), BUFFER_SIZE);
- } else {
- this.output = new BufferedOutputStream(new FileOutputStream(getOutputName()), BUFFER_SIZE);
- }
- this.dataOut = new DataOutputStream(this.output);
-
-
- if (this.splitCount > 1) {
- this.dataOut.writeByte(HEADER_TOKEN);
- this.dataOut.writeByte(ARCHIVE_VERSION);
- this.dataOut.writeLong(this.startTimeStamp);
- this.dataOut.writeLong(this.systemId);
- this.dataOut.writeLong(this.systemStartTimeStamp);
- this.dataOut.writeInt(this.timeZoneOffset);
- this.dataOut.writeUTF(this.timeZoneName);
- this.dataOut.writeUTF(this.systemDirectory);
- this.dataOut.writeUTF(this.productVersion);
- this.dataOut.writeUTF(this.os);
- this.dataOut.writeUTF(this.machine);
- }
-
- for (int i=0; i < globalTokenCount; i++) {
- this.dataOut.write(globalTokens[i]);
- }
- for (int i=0; i < resourceInstanceTokens.length; i++) {
- if (resourceInstanceTokens[i] != null) {
- this.dataOut.write(resourceInstanceTokens[i]);
- byte[] instTypeCodes = resourceInstanceTypeCodes[i];
- long[] instBits = resourceInstanceBits[i];
- for (int j=0; j < instBits.length; j++) {
- StatArchiveWriter.writeStatValue(instTypeCodes[j], instBits[j], this.dataOut);
- }
- }
- }
- }
-
- private void endSplit() {
- try {
- this.dataOut.flush();
- } catch (IOException ex) {
- }
- try {
- this.output.close();
- } catch (IOException ex) {
- System.err.println("[warning] could not close " + getOutputName());
- }
- }
-
- public void split() throws IOException {
- boolean done = false;
- do {
- done = true;
- startSplit();
- while (readToken()) {
- if (this.currentDuration >= this.splitDuration) {
- done = false;
- break;
- }
- }
- endSplit();
- } while (!done);
- }
-
- private static class MyFilterInputStream extends FilterInputStream {
- private byte[] readBytes = new byte[32000];
- private int idx = 0;
- public MyFilterInputStream(InputStream in) {
- super(in);
- }
-
- /**
- * Returns all the bytes, read or skipped, since the last reset.
- */
- public byte[] getBytes() {
- byte[] result = new byte[idx];
- System.arraycopy(readBytes, 0, result, 0, result.length);
- return result;
- }
-
- /**
- * Writes all the bytes, read or skipped, since the last reset
- * to the specified output stream.
- * Does a mark and reset after the write.
- */
- public void putBytes(DataOutputStream dataOut) throws IOException {
- dataOut.write(readBytes, 0, idx);
- idx = 0;
- }
-
- @Override
- public void close() throws IOException {
- readBytes = null;
- super.close();
- }
-
- @Override
- public void reset() throws IOException {
- idx = 0;
- super.reset();
- }
-
- @Override
- public long skip(long n) throws IOException {
- makeRoom((int)n);
- int result = super.read(readBytes, idx, (int)n);
- if (result == -1) {
- return 0;
- } else {
- idx += result;
- return result;
- }
- }
-
- private void makeRoom(int n) {
- if (idx+n > readBytes.length) {
- byte[] tmp = new byte[readBytes.length + n + 1024];
- System.arraycopy(readBytes, 0, tmp, 0, readBytes.length);
- readBytes = tmp;
- }
- }
-
- @Override
- public int read() throws IOException {
- int result = super.read();
- if (result != -1) {
- makeRoom(1);
- readBytes[idx] = (byte)result;
- idx += 1;
- }
- return result;
- }
-
- @Override
- public int read(byte[] b) throws IOException {
- return read(b, 0, b.length);
- }
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- int result = super.read(b, off, len);
- if (result != -1) {
- makeRoom(result);
- System.arraycopy(b, off, readBytes, idx, result);
- idx += result;
- }
- return result;
- }
- }
-
- public static void main(String args[]) throws IOException {
- if (args.length != 1) {
- System.err.println(LocalizedStrings.ArchiveSplitter_USAGE.toLocalizedString() + ": com.gemstone.gemfire.internal.ArchiveSplitter <archive.gfs>");
- System.exit(1);
- }
- ArchiveSplitter as = new ArchiveSplitter(new File(args[0]));
- as.split();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/DummyStatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/DummyStatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/DummyStatisticsFactory.java
deleted file mode 100644
index 9d280eb..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/DummyStatisticsFactory.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-import java.io.*;
-
-/**
- * A StatisticsFactory that creates disconnected statistics
- */
-public class DummyStatisticsFactory implements StatisticsFactory {
-
- private final static StatisticsTypeFactoryImpl tf = (StatisticsTypeFactoryImpl)StatisticsTypeFactoryImpl.singleton();
-
- /** Creates a new instance of DummyStatisticsFactory */
- public DummyStatisticsFactory() {
- }
-
- // StatisticsFactory methods
- public Statistics createStatistics(StatisticsType type) {
- return createStatistics(type, null, 1);
- }
- public Statistics createStatistics(StatisticsType type, String textId) {
- return createStatistics(type, textId, 1);
- }
- public Statistics createStatistics(StatisticsType type, String textId, long numericId) {
- Statistics result = new LocalStatisticsImpl(type, textId, numericId, 1, false, 0, null);
- return result;
- }
-
-// /** for internal use only. Its called by {@link LocalStatisticsImpl#close}. */
-// public void destroyStatistics(Statistics stats) {
-// if (statsList.remove(stats)) {
-// statsListModCount++;
-// }
-// }
-//
- public Statistics createAtomicStatistics(StatisticsType type) {
- return createAtomicStatistics(type, null, 1);
- }
- public Statistics createAtomicStatistics(StatisticsType type, String textId) {
- return createAtomicStatistics(type, textId, 1);
- }
- public Statistics createAtomicStatistics(StatisticsType type, String textId, long numericId) {
- Statistics result = new LocalStatisticsImpl(type, textId, numericId, 1, true, 0, null);
- return result;
- }
- public Statistics[] findStatisticsByType(StatisticsType type) {
- return new Statistics[0];
- }
- public Statistics[] findStatisticsByTextId(String textId) {
- return new Statistics[0];
- }
- public Statistics[] findStatisticsByNumericId(long numericId) {
- return new Statistics[0];
- }
-
- public StatisticsType createType(String name, String description,
- StatisticDescriptor[] stats) {
- return tf.createType(name, description, stats);
- }
- public StatisticsType findType(String name) {
- return tf.findType(name);
- }
- public StatisticsType[] createTypesFromXml(Reader reader)
- throws IOException {
- return tf.createTypesFromXml(reader);
- }
-
- public StatisticDescriptor createIntCounter(String name, String description,
- String units) {
- return tf.createIntCounter(name, description, units);
- }
- public StatisticDescriptor createLongCounter(String name, String description,
- String units) {
- return tf.createLongCounter(name, description, units);
- }
- public StatisticDescriptor createDoubleCounter(String name, String description,
- String units) {
- return tf.createDoubleCounter(name, description, units);
- }
- public StatisticDescriptor createIntGauge(String name, String description,
- String units) {
- return tf.createIntGauge(name, description, units);
- }
- public StatisticDescriptor createLongGauge(String name, String description,
- String units) {
- return tf.createLongGauge(name, description, units);
- }
- public StatisticDescriptor createDoubleGauge(String name, String description,
- String units) {
- return tf.createDoubleGauge(name, description, units);
- }
- public StatisticDescriptor createIntCounter(String name, String description,
- String units, boolean largerBetter) {
- return tf.createIntCounter(name, description, units, largerBetter);
- }
- public StatisticDescriptor createLongCounter(String name, String description,
- String units, boolean largerBetter) {
- return tf.createLongCounter(name, description, units, largerBetter);
- }
- public StatisticDescriptor createDoubleCounter(String name, String description,
- String units, boolean largerBetter) {
- return tf.createDoubleCounter(name, description, units, largerBetter);
- }
- public StatisticDescriptor createIntGauge(String name, String description,
- String units, boolean largerBetter) {
- return tf.createIntGauge(name, description, units, largerBetter);
- }
- public StatisticDescriptor createLongGauge(String name, String description,
- String units, boolean largerBetter) {
- return tf.createLongGauge(name, description, units, largerBetter);
- }
- public StatisticDescriptor createDoubleGauge(String name, String description,
- String units, boolean largerBetter) {
- return tf.createDoubleGauge(name, description, units, largerBetter);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/DummyStatisticsImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/DummyStatisticsImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/DummyStatisticsImpl.java
deleted file mode 100644
index aa8da50..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/DummyStatisticsImpl.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import java.util.function.DoubleSupplier;
-import java.util.function.IntSupplier;
-import java.util.function.LongSupplier;
-
-import com.gemstone.gemfire.*;
-
-/**
- * An implementation of {@link Statistics} that does nothing.
- * Setting the "gemfire.statsDisabled" to true causes it to be used.
- *
- * @see <A href="package-summary.html#statistics">Package introduction</A>
- *
- *
- * @since GemFire 3.0
- *
- */
-public class DummyStatisticsImpl implements Statistics {
-
- private final StatisticsType type;
- private final String textId;
- private final long numericId;
-
- /////////////////////// Constructors ///////////////////////
-
- /**
- * Creates a new statistics instance of the given type
- *
- * @param type
- * A description of the statistics
- */
- public DummyStatisticsImpl(StatisticsType type, String textId, long numericId) {
- this.type = type;
- this.textId = textId;
- this.numericId = numericId;
- }
-
- public final void close() {
- }
-
- //////////////////////// accessor Methods ///////////////////////
-
- public final int nameToId(String name) {
- return this.type.nameToId(name);
- }
-
- public final StatisticDescriptor nameToDescriptor(String name) {
- return this.type.nameToDescriptor(name);
- }
-
- public final long getUniqueId() {
- return 0;
- }
-
- public final StatisticsType getType() {
- return this.type;
- }
-
- public final String getTextId() {
- return this.textId;
- }
- public final long getNumericId() {
- return this.numericId;
- }
- public final boolean isAtomic() {
- return true;
- }
- public final boolean isClosed() {
- return false;
- }
-
- //////////////////////// set() Methods ///////////////////////
-
- public final void setInt(int id, int value) {
- }
-
- public final void setInt(StatisticDescriptor descriptor, int value) {
- }
-
- public final void setInt(String name, int value) {
- }
-
- public final void setLong(int id, long value) {
- }
-
- public final void setLong(StatisticDescriptor descriptor, long value) {
- }
-
- public final void setLong(String name, long value) {
- }
-
- public final void setDouble(int id, double value) {
- }
-
- public final void setDouble(StatisticDescriptor descriptor, double value) {
- }
-
- public final void setDouble(String name, double value) {
- }
-
- /////////////////////// get() Methods ///////////////////////
-
- public final int getInt(int id) {
- return 0;
- }
-
- public final int getInt(StatisticDescriptor descriptor) {
- return 0;
- }
-
- public final int getInt(String name) {
- return 0;
- }
-
- public final long getLong(int id) {
- return 0;
- }
-
- public final long getLong(StatisticDescriptor descriptor) {
- return 0;
- }
-
- public final long getLong(String name) {
- return 0;
- }
-
- public final double getDouble(int id) {
- return 0.0;
- }
-
- public final double getDouble(StatisticDescriptor descriptor) {
- return 0.0;
- }
-
- public final double getDouble(String name) {
- return 0.0;
- }
-
- private static final Number dummyNumber = Integer.valueOf(0);
-
- public final Number get(StatisticDescriptor descriptor) {
- return dummyNumber;
- }
-
- public final Number get(String name) {
- return dummyNumber;
- }
-
- public final long getRawBits(StatisticDescriptor descriptor) {
- return 0;
- }
-
- public final long getRawBits(String name) {
- return 0;
- }
-
- //////////////////////// inc() Methods ////////////////////////
-
- public final void incInt(int id, int delta) {
- }
-
- public final void incInt(StatisticDescriptor descriptor, int delta) {
- }
-
- public final void incInt(String name, int delta) {
- }
-
- public final void incLong(int id, long delta) {
- }
-
- public final void incLong(StatisticDescriptor descriptor, long delta) {
- }
-
- public final void incLong(String name, long delta) {
- }
-
- public final void incDouble(int id, double delta) {
- }
-
- public final void incDouble(StatisticDescriptor descriptor, double delta) {
- }
-
- public final void incDouble(String name, double delta) {
- }
-
- @Override
- public IntSupplier setIntSupplier(final int id, final IntSupplier supplier) {
- return null;
- }
-
- @Override
- public IntSupplier setIntSupplier(final String name, final IntSupplier supplier) {
- return null;
- }
-
- @Override
- public IntSupplier setIntSupplier(final StatisticDescriptor descriptor, final IntSupplier supplier) {
- return null;
- }
-
- @Override public LongSupplier setLongSupplier(final int id, final LongSupplier supplier) {
- return null;
- }
-
- @Override public LongSupplier setLongSupplier(final String name, final LongSupplier supplier) {
- return null;
- }
-
- @Override public LongSupplier setLongSupplier(final StatisticDescriptor descriptor, final LongSupplier supplier) {
- return null;
- }
-
- @Override public DoubleSupplier setDoubleSupplier(final int id, final DoubleSupplier supplier) {
- return null;
- }
-
- @Override public DoubleSupplier setDoubleSupplier(final String name, final DoubleSupplier supplier) {
- return null;
- }
-
- @Override
- public DoubleSupplier setDoubleSupplier(final StatisticDescriptor descriptor, final DoubleSupplier supplier) {
- return null;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/GemFireStatSampler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/GemFireStatSampler.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/GemFireStatSampler.java
deleted file mode 100644
index 1eb35d0..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/GemFireStatSampler.java
+++ /dev/null
@@ -1,502 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
-import com.gemstone.gemfire.internal.admin.ListenerIdMap;
-import com.gemstone.gemfire.internal.admin.remote.StatListenerMessage;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
-import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.apache.logging.log4j.Logger;
-
-/**
- * GemFireStatSampler adds listeners and rolling archives to HostStatSampler.
- * <p>
- * The StatisticsManager is implemented by DistributedSystem.
- *
- */
-public final class GemFireStatSampler extends HostStatSampler {
-
- private static final Logger logger = LogService.getLogger();
-
- private final ListenerIdMap listeners = new ListenerIdMap();
-
- // TODO: change the listener maps to be copy-on-write
-
- private final Map<LocalStatListenerImpl, Boolean> localListeners =
- new ConcurrentHashMap<LocalStatListenerImpl, Boolean>();
-
- private final Map<InternalDistributedMember, List<RemoteStatListenerImpl>> recipientToListeners =
- new HashMap<InternalDistributedMember, List<RemoteStatListenerImpl>>();
-
- private final InternalDistributedSystem con;
-
- private int nextListenerId = 1;
- private ProcessStats processStats = null;
-
- ////////////////////// Constructors //////////////////////
-
- public GemFireStatSampler(InternalDistributedSystem con) {
- super(con.getCancelCriterion(), new StatSamplerStats(con, con.getId()));
- this.con = con;
- }
-
- /**
- * Returns the <code>ProcessStats</code> for this Java VM. Note
- * that <code>null</code> will be returned if operating statistics
- * are disabled.
- *
- * @since GemFire 3.5
- */
- public final ProcessStats getProcessStats() {
- return this.processStats;
- }
-
- @Override
- public String getProductDescription() {
- return "GemFire " + GemFireVersion.getGemFireVersion()
- + " #" + GemFireVersion.getBuildId()
- + " as of " + GemFireVersion.getSourceDate();
- }
-
- public int addListener(InternalDistributedMember recipient, long resourceId, String statName) {
- int result = getNextListenerId();
- synchronized (listeners) {
- while (listeners.get(result) != null) {
- // previous one was still being used
- result = getNextListenerId();
- }
- RemoteStatListenerImpl sl = RemoteStatListenerImpl.create(result, recipient,
- resourceId, statName, this);
- listeners.put(result, sl);
- List<RemoteStatListenerImpl> l = recipientToListeners.get(recipient);
- if (l == null) {
- l = new ArrayList<RemoteStatListenerImpl>();
- recipientToListeners.put(recipient, l);
- }
- l.add(sl);
- }
- return result;
- }
-
- public boolean removeListener(int listenerId) {
- synchronized (listeners) {
- RemoteStatListenerImpl sl = (RemoteStatListenerImpl)listeners.remove(listenerId);
- if (sl != null) {
- List<RemoteStatListenerImpl> l = recipientToListeners.get(sl.getRecipient());
- l.remove(sl);
- }
- return sl != null;
- }
- }
-
- public void removeListenersByRecipient(InternalDistributedMember recipient) {
- synchronized (listeners) {
- List<RemoteStatListenerImpl> l = recipientToListeners.get(recipient);
- if (l != null && l.size() != 0) {
- for (RemoteStatListenerImpl sl : l) {
- listeners.remove(sl.getListenerId());
- }
- recipientToListeners.remove(recipient);
- }
- }
- }
-
- public void addLocalStatListener(LocalStatListener l, Statistics stats, String statName) {
- LocalStatListenerImpl sl = null;
- synchronized (LocalStatListenerImpl.class) {
- sl = LocalStatListenerImpl.create(l, stats, statName);
- }
- this.localListeners.put(sl, Boolean.TRUE);
- }
-
- public boolean removeLocalStatListener(LocalStatListener listener) {
- Iterator<Map.Entry<LocalStatListenerImpl, Boolean>> it =
- this.localListeners.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<LocalStatListenerImpl, Boolean> entry = it.next();
- if (listener.equals(entry.getKey().getListener())) {
- it.remove();
- return true;
- }
- }
- return false;
- }
-
- public Set<LocalStatListenerImpl> getLocalListeners() {
- return this.localListeners.keySet();
- }
-
- @Override
- public final File getArchiveFileName() {
- return this.con.getConfig().getStatisticArchiveFile();
- }
-
- @Override
- public final long getArchiveFileSizeLimit() {
- if (fileSizeLimitInKB()) {
- // use KB instead of MB to speed up rolling for testing
- return ((long)this.con.getConfig().getArchiveFileSizeLimit()) * (1024);
- } else {
- return ((long)this.con.getConfig().getArchiveFileSizeLimit()) * (1024*1024);
- }
- }
-
- @Override
- public final long getArchiveDiskSpaceLimit() {
- if (fileSizeLimitInKB()) {
- // use KB instead of MB to speed up removal for testing
- return ((long)this.con.getConfig().getArchiveDiskSpaceLimit()) * (1024);
- } else {
- return ((long)this.con.getConfig().getArchiveDiskSpaceLimit()) * (1024*1024);
- }
- }
-
- @Override
- protected void checkListeners() {
- checkLocalListeners();
- synchronized (listeners) {
- if (listeners.size() == 0) {
- return;
- }
- long timeStamp = System.currentTimeMillis();
- Iterator<Map.Entry<InternalDistributedMember, List<RemoteStatListenerImpl>>> it1 =
- recipientToListeners.entrySet().iterator();
- while (it1.hasNext()) {
- if (stopRequested()) return;
- Map.Entry<InternalDistributedMember, List<RemoteStatListenerImpl>> me =
- it1.next();
- List<RemoteStatListenerImpl> l = me.getValue();
- if (l.size() > 0) {
- InternalDistributedMember recipient = (InternalDistributedMember)me.getKey();
- StatListenerMessage msg =
- StatListenerMessage.create(timeStamp, l.size());
- msg.setRecipient(recipient);
- for (RemoteStatListenerImpl statListener : l) {
- if (getStatisticsManager().statisticsExists(statListener.getStatId())) {
- statListener.checkForChange(msg);
- } else {
- // its stale; indicate this with a negative listener id
- // fix for bug 29405
- msg.addChange(-statListener.getListenerId(), 0);
- }
- }
- this.con.getDistributionManager().putOutgoing(msg);
- }
- }
- }
- }
-
- @Override
- protected final int getSampleRate() {
- return this.con.getConfig().getStatisticSampleRate();
- }
-
- @Override
- public final boolean isSamplingEnabled() {
- return this.con.getConfig().getStatisticSamplingEnabled();
- }
-
- @Override
- protected final StatisticsManager getStatisticsManager() {
- return this.con;
- }
-
- @Override
- protected final OsStatisticsFactory getOsStatisticsFactory() {
- return this.con;
- }
-
- @Override
- protected final long getSpecialStatsId() {
- long statId = OSProcess.getId();
- if (statId == 0 || statId == -1) {
- statId = getStatisticsManager().getId();
- }
- return statId;
- }
-
- @Override
- protected final void initProcessStats(long id) {
- if (PureJavaMode.osStatsAreAvailable()) {
- if (osStatsDisabled()) {
- logger.info(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.GemFireStatSampler_OS_STATISTIC_COLLECTION_DISABLED_BY_OSSTATSDISABLED_SYSTEM_PROPERTY));
- } else {
- int retVal = HostStatHelper.initOSStats();
- if ( retVal != 0 ) {
- logger.error(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.GemFireStatSampler_OS_STATISTICS_FAILED_TO_INITIALIZE_PROPERLY_SOME_STATS_MAY_BE_MISSING_SEE_BUGNOTE_37160));
- }
- HostStatHelper.newSystem(getOsStatisticsFactory());
- String statName = getStatisticsManager().getName();
- if (statName == null || statName.length() == 0) {
- statName = "javaApp" + getStatisticsManager().getId();
- }
- Statistics stats = HostStatHelper.newProcess(getOsStatisticsFactory(), id, statName + "-proc");
- this.processStats = HostStatHelper.newProcessStats(stats);
- }
- }
- }
-
- @Override
- protected final void sampleProcessStats(boolean prepareOnly) {
- if (prepareOnly || osStatsDisabled() || !PureJavaMode.osStatsAreAvailable()) {
- return;
- }
- List<Statistics> l = getStatisticsManager().getStatsList();
- if (l == null) {
- return;
- }
- if (stopRequested()) return;
- HostStatHelper.readyRefreshOSStats();
- Iterator<Statistics> it = l.iterator();
- while (it.hasNext()) {
- if (stopRequested()) return;
- StatisticsImpl s = (StatisticsImpl)it.next();
- if (s.usesSystemCalls()) {
- HostStatHelper.refresh((LocalStatisticsImpl)s);
- }
- }
- }
-
- @Override
- protected final void closeProcessStats() {
- if (PureJavaMode.osStatsAreAvailable()) {
- if (!osStatsDisabled()) {
- if (this.processStats != null) {
- this.processStats.close();
- }
- HostStatHelper.closeOSStats();
- }
- }
- }
-
- private void checkLocalListeners() {
- for (LocalStatListenerImpl st : this.localListeners.keySet()) {
- if (getStatisticsManager().statisticsExists(st.getStatId())) {
- st.checkForChange();
- }
- }
- }
-
- private int getNextListenerId() {
- int result = nextListenerId++;
- if (nextListenerId < 0) {
- nextListenerId = 1;
- }
- return result;
- }
-
- protected static abstract class StatListenerImpl {
- protected Statistics stats;
- protected StatisticDescriptorImpl stat;
- protected boolean oldValueInitialized = false;
- protected long oldValue;
-
- public long getStatId() {
- if (this.stats.isClosed()) {
- return -1;
- } else {
- return this.stats.getUniqueId();
- }
- }
-
- protected abstract double getBitsAsDouble(long bits);
- }
-
- protected static abstract class LocalStatListenerImpl extends StatListenerImpl {
- private LocalStatListener listener;
-
- public LocalStatListener getListener() {
- return this.listener;
- }
-
- static LocalStatListenerImpl create(LocalStatListener l, Statistics stats, String statName) {
- LocalStatListenerImpl result = null;
- StatisticDescriptorImpl stat = (StatisticDescriptorImpl)stats.nameToDescriptor(statName);
- switch (stat.getTypeCode()) {
- case StatisticDescriptorImpl.BYTE:
- case StatisticDescriptorImpl.SHORT:
- case StatisticDescriptorImpl.INT:
- case StatisticDescriptorImpl.LONG:
- result = new LocalLongStatListenerImpl();
- break;
- case StatisticDescriptorImpl.FLOAT:
- result = new LocalFloatStatListenerImpl();
- break;
- case StatisticDescriptorImpl.DOUBLE:
- result = new LocalDoubleStatListenerImpl();
- break;
- default:
- throw new RuntimeException("Illegal field type " + stats.getType() + " for statistic");
- }
- result.stats = stats;
- result.stat = stat;
- result.listener = l;
- return result;
- }
-
- /**
- * Checks to see if the value of the stat has changed. If it has then
- * the local listener is fired
- */
- public void checkForChange() {
- long currentValue = stats.getRawBits(stat);
- if (oldValueInitialized) {
- if (currentValue == oldValue) {
- return;
- }
- } else {
- oldValueInitialized = true;
- }
- oldValue = currentValue;
- listener.statValueChanged(getBitsAsDouble(currentValue));
- }
- }
-
- protected static class LocalLongStatListenerImpl extends LocalStatListenerImpl {
- @Override
- protected double getBitsAsDouble(long bits) {
- return bits;
- }
- }
-
- protected static class LocalFloatStatListenerImpl extends LocalStatListenerImpl {
- @Override
- protected double getBitsAsDouble(long bits) {
- return Float.intBitsToFloat((int)bits);
- }
- }
-
- protected static class LocalDoubleStatListenerImpl extends LocalStatListenerImpl {
- @Override
- protected double getBitsAsDouble(long bits) {
- return Double.longBitsToDouble(bits);
- }
- }
-
- /**
- * Used to register a StatListener.
- */
- protected static abstract class RemoteStatListenerImpl extends StatListenerImpl{
- private int listenerId;
- private InternalDistributedMember recipient;
-
- @Override
- public final int hashCode() {
- return listenerId;
- }
-
- @Override
- public final boolean equals(Object o) {
- if (o == null) {
- return false;
- }
- if (o instanceof RemoteStatListenerImpl) {
- return listenerId == ((RemoteStatListenerImpl)o).listenerId;
- } else {
- return false;
- }
- }
-
- public int getListenerId() {
- return this.listenerId;
- }
-
- public InternalDistributedMember getRecipient() {
- return this.recipient;
- }
-
- static RemoteStatListenerImpl create(int listenerId, InternalDistributedMember recipient, long resourceId, String statName, HostStatSampler sampler) {
- RemoteStatListenerImpl result = null;
- Statistics stats = sampler.getStatisticsManager().findStatistics(resourceId);
- StatisticDescriptorImpl stat = (StatisticDescriptorImpl)stats.nameToDescriptor(statName);
- switch (stat.getTypeCode()) {
- case StatisticDescriptorImpl.BYTE:
- case StatisticDescriptorImpl.SHORT:
- case StatisticDescriptorImpl.INT:
- case StatisticDescriptorImpl.LONG:
- result = new LongStatListenerImpl();
- break;
- case StatisticDescriptorImpl.FLOAT:
- result = new FloatStatListenerImpl();
- break;
- case StatisticDescriptorImpl.DOUBLE:
- result = new DoubleStatListenerImpl();
- break;
- default:
- throw new RuntimeException(LocalizedStrings.GemFireStatSampler_ILLEGAL_FIELD_TYPE_0_FOR_STATISTIC.toLocalizedString(stats.getType()));
- }
- result.stats = stats;
- result.stat = stat;
- result.listenerId = listenerId;
- result.recipient = recipient;
- return result;
- }
-
- /**
- * Checks to see if the value of the stat has changed. If it has then it
- * adds that change to the specified message.
- */
- public void checkForChange(StatListenerMessage msg) {
- long currentValue = stats.getRawBits(stat);
- if (oldValueInitialized) {
- if (currentValue == oldValue) {
- return;
- }
- } else {
- oldValueInitialized = true;
- }
- oldValue = currentValue;
- msg.addChange(listenerId, getBitsAsDouble(currentValue));
- }
- }
-
- protected static class LongStatListenerImpl extends RemoteStatListenerImpl {
- @Override
- protected double getBitsAsDouble(long bits) {
- return bits;
- }
- }
-
- protected static class FloatStatListenerImpl extends RemoteStatListenerImpl {
- @Override
- protected double getBitsAsDouble(long bits) {
- return Float.intBitsToFloat((int)bits);
- }
- }
-
- protected static class DoubleStatListenerImpl extends RemoteStatListenerImpl {
- @Override
- protected double getBitsAsDouble(long bits) {
- return Double.longBitsToDouble(bits);
- }
- }
-}
[14/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/HostStatSampler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/HostStatSampler.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/HostStatSampler.java
new file mode 100644
index 0000000..d414d2c
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/HostStatSampler.java
@@ -0,0 +1,549 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.CancelCriterion;
+import com.gemstone.gemfire.CancelException;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.SystemFailure;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.NanoTimer;
+import com.gemstone.gemfire.internal.SocketCreator;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.logging.LoggingThreadGroup;
+import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
+import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
+import com.gemstone.gemfire.internal.statistics.platform.OsStatisticsFactory;
+import com.gemstone.gemfire.internal.util.concurrent.StoppableCountDownLatch;
+import org.apache.logging.log4j.Logger;
+
+import java.io.File;
+import java.net.UnknownHostException;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * HostStatSampler implements a thread which will monitor, sample, and archive
+ * statistics. It only has the common functionality that any sampler needs.
+
+ */
+public abstract class HostStatSampler
+ implements Runnable, StatisticsSampler, StatArchiveHandlerConfig {
+
+ private static final Logger logger = LogService.getLogger();
+
+ public static final String TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY = DistributionConfig.GEMFIRE_PREFIX + "stats.test.fileSizeLimitInKB";
+ public static final String OS_STATS_DISABLED_PROPERTY = "osStatsDisabled";
+
+ protected static final String INITIALIZATION_TIMEOUT_PROPERTY = DistributionConfig.GEMFIRE_PREFIX + "statSamplerInitializationTimeout";
+ protected static final int INITIALIZATION_TIMEOUT_DEFAULT = 30000;
+ protected static final long INITIALIZATION_TIMEOUT_MILLIS =
+ Long.getLong(INITIALIZATION_TIMEOUT_PROPERTY, INITIALIZATION_TIMEOUT_DEFAULT);
+
+ /**
+ * Used to check if the sampler thread wake-up is delayed, and log a warning if it is delayed by longer than
+ * the amount of milliseconds specified by this property. The value of 0 disables the check.
+ */
+ private static final long STAT_SAMPLER_DELAY_THRESHOLD = Long.getLong(DistributionConfig.GEMFIRE_PREFIX + "statSamplerDelayThreshold", 3000);
+ private static final long STAT_SAMPLER_DELAY_THRESHOLD_NANOS = NanoTimer.millisToNanos(STAT_SAMPLER_DELAY_THRESHOLD);
+
+ private static final int MIN_MS_SLEEP = 1;
+
+ private static final int WAIT_FOR_SLEEP_INTERVAL = 10;
+
+ private static Thread statThread = null;
+
+ private volatile boolean stopRequested = false;
+
+ private final boolean osStatsDisabled = Boolean.getBoolean(OS_STATS_DISABLED_PROPERTY);
+ private final boolean fileSizeLimitInKB;
+ private final StatSamplerStats samplerStats;
+
+ private VMStatsContract vmStats;
+ private SampleCollector sampleCollector;
+
+ /**
+ * Used to signal thread that are waiting for the stat sampler to be initialized.
+ */
+ private final StoppableCountDownLatch statSamplerInitializedLatch;
+
+ private final CancelCriterion stopper;
+
+ private final CallbackSampler callbackSampler;
+
+ protected HostStatSampler(CancelCriterion stopper,
+ StatSamplerStats samplerStats) {
+ this.stopper = stopper;
+ this.statSamplerInitializedLatch = new StoppableCountDownLatch(this.stopper, 1);
+ this.samplerStats = samplerStats;
+ this.fileSizeLimitInKB = Boolean.getBoolean(TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY);
+ this.callbackSampler = new CallbackSampler(stopper, samplerStats);
+ }
+
+ public final StatSamplerStats getStatSamplerStats() {
+ return this.samplerStats;
+ }
+
+ /**
+ * Returns the number of times a statistics resource has been add or deleted.
+ */
+ @Override
+ public final int getStatisticsModCount() {
+ return getStatisticsManager().getStatListModCount();
+ }
+
+ /**
+ * Returns an array of all the current statistic resource instances.
+ */
+ @Override
+ public final Statistics[] getStatistics() {
+ return getStatisticsManager().getStatistics();
+ }
+
+ /**
+ * Returns a unique id for the sampler's system.
+ */
+ @Override
+ public final long getSystemId() {
+ return getStatisticsManager().getId();
+ }
+
+ /**
+ * Returns the time this sampler's system was started.
+ */
+ @Override
+ public final long getSystemStartTime() {
+ return getStatisticsManager().getStartTime();
+ }
+
+ /**
+ * Returns the path to this sampler's system directory; if it has one.
+ */
+ @Override
+ public final String getSystemDirectoryPath() {
+ try {
+ return SocketCreator.getHostName(SocketCreator.getLocalHost());
+ } catch (UnknownHostException ignore) {
+ return "";
+ }
+ }
+
+ @Override
+ public boolean waitForSample(long timeout) throws InterruptedException {
+ final long endTime = System.currentTimeMillis() + timeout;
+ final int startSampleCount = this.samplerStats.getSampleCount();
+ while (System.currentTimeMillis() < endTime &&
+ this.samplerStats.getSampleCount() <= startSampleCount) {
+ Thread.sleep(WAIT_FOR_SLEEP_INTERVAL);
+ }
+ return this.samplerStats.getSampleCount() > startSampleCount;
+ }
+
+ @Override
+ public SampleCollector waitForSampleCollector(long timeout) throws InterruptedException {
+ final long endTime = System.currentTimeMillis() + timeout;
+ while (System.currentTimeMillis() < endTime &&
+ this.sampleCollector == null || !this.sampleCollector.isInitialized()) {
+ Thread.sleep(WAIT_FOR_SLEEP_INTERVAL);
+ }
+ return this.sampleCollector;
+ }
+
+ /**
+ * This service's main loop
+ */
+ @Override
+ public final void run() {
+ NanoTimer timer = new NanoTimer();
+
+ final boolean isDebugEnabled_STATISTICS = logger.isTraceEnabled(LogMarker.STATISTICS);
+ if (isDebugEnabled_STATISTICS) {
+ logger.trace(LogMarker.STATISTICS, "HostStatSampler started");
+ }
+ boolean latchCountedDown = false;
+ try {
+ initSpecialStats();
+
+ this.sampleCollector = new SampleCollector(this);
+ this.sampleCollector.initialize(this, NanoTimer.getTime());
+
+ this.statSamplerInitializedLatch.countDown();
+ latchCountedDown = true;
+
+ timer.reset();
+ // subtract getNanoRate from lastTS to force a quick initial sample
+ long nanosLastTimeStamp = timer.getLastResetTime() - getNanoRate();
+ while (!stopRequested()) {
+ SystemFailure.checkFailure();
+ if (Thread.currentThread().isInterrupted()) {
+ break;
+ }
+ final long nanosBeforeSleep = timer.getLastResetTime();
+ final long nanosToDelay = nanosLastTimeStamp + getNanoRate();
+ delay(timer, nanosToDelay);
+ nanosLastTimeStamp = timer.getLastResetTime();
+ if (!stopRequested() && isSamplingEnabled()) {
+ final long nanosTimeStamp = timer.getLastResetTime();
+ final long nanosElapsedSleeping = nanosTimeStamp - nanosBeforeSleep;
+ checkElapsedSleepTime(nanosElapsedSleeping);
+ if (stopRequested()) break;
+ sampleSpecialStats(false);
+ if (stopRequested()) break;
+ checkListeners();
+ if (stopRequested()) break;
+
+ this.sampleCollector.sample(nanosTimeStamp);
+
+ final long nanosSpentWorking = timer.reset();
+ accountForTimeSpentWorking(nanosSpentWorking, nanosElapsedSleeping);
+ } else if (!stopRequested() && !isSamplingEnabled()) {
+ sampleSpecialStats(true); // fixes bug 42527
+ }
+ }
+ }
+ catch (InterruptedException ex) {
+ // Silently exit
+ }
+ catch (CancelException ex) {
+ // Silently exit
+ }
+ catch (RuntimeException ex) {
+ logger.fatal(LogMarker.STATISTICS, ex.getMessage(), ex);
+ throw ex;
+ }
+ catch (VirtualMachineError err) {
+ SystemFailure.initiateFailure(err);
+ // If this ever returns, rethrow the error. We're poisoned
+ // now, so don't let this thread continue.
+ throw err;
+ }
+ catch (Error ex) {
+ // Whenever you catch Error or Throwable, you must also
+ // catch VirtualMachineError (see above). However, there is
+ // _still_ a possibility that you are dealing with a cascading
+ // error condition, so you also need to check to see if the JVM
+ // is still usable:
+ SystemFailure.checkFailure();
+ logger.fatal(LogMarker.STATISTICS, ex.getMessage(), ex);
+ throw ex;
+ } finally {
+ try {
+ closeSpecialStats();
+ if (this.sampleCollector != null) {
+ this.sampleCollector.close();
+ }
+ } finally {
+ if (!latchCountedDown) {
+ // Make sure the latch gets counted down since
+ // other threads wait for this to indicate that
+ // the sampler is initialized.
+ this.statSamplerInitializedLatch.countDown();
+ }
+ }
+ if (isDebugEnabled_STATISTICS) {
+ logger.trace(LogMarker.STATISTICS, "HostStatSampler stopped");
+ }
+ }
+ }
+
+ /**
+ * Starts the main thread for this service.
+ * @throws IllegalStateException if an instance of the {@link #statThread} is still running from a previous DistributedSystem.
+ */
+ public final void start() {
+ synchronized(HostStatSampler.class) {
+ if (statThread != null) {
+ try {
+ int msToWait = getSampleRate() + 100;
+ statThread.join(msToWait);
+ } catch (InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ if (statThread.isAlive()) {
+ throw new IllegalStateException(LocalizedStrings.HostStatSampler_STATISTICS_SAMPLING_THREAD_IS_ALREADY_RUNNING_INDICATING_AN_INCOMPLETE_SHUTDOWN_OF_A_PREVIOUS_CACHE.toLocalizedString());
+ }
+ }
+ ThreadGroup group =
+ LoggingThreadGroup.createThreadGroup("StatSampler Threads");
+
+ this.callbackSampler.start(getStatisticsManager(), group, getSampleRate(), TimeUnit.MILLISECONDS);
+ statThread = new Thread(group, this);
+ statThread.setName(statThread.getName() + " StatSampler");
+ statThread.setPriority(Thread.MAX_PRIORITY);
+ statThread.setDaemon(true);
+ statThread.start();
+ // fix #46310 (race between management and sampler init) by waiting for init here
+ try {
+ waitForInitialization(INITIALIZATION_TIMEOUT_MILLIS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }
+
+ /**
+ * Tell this service's main thread to terminate.
+ */
+ public final void stop() {
+ stop(true);
+ }
+ private final void stop(boolean interruptIfAlive) {
+ synchronized (HostStatSampler.class) {
+ this.callbackSampler.stop();
+ if ( statThread == null) {
+ return;
+ }
+
+ this.stopRequested = true;
+ synchronized (this) {
+ this.notifyAll();
+ }
+ try {
+ statThread.join(5000);
+ } catch (InterruptedException ignore) {
+ //It is important that we shutdown so we'll continue trying for another 2 seconds
+ try {
+ statThread.join(2000);
+ } catch (InterruptedException ex) {
+ } finally {
+ Thread.currentThread().interrupt();
+ }
+ } finally {
+ if ( statThread.isAlive() ) {
+ if (interruptIfAlive) {
+ // It is still alive so interrupt the thread
+ statThread.interrupt();
+ stop(false);
+ } else {
+ logger.warn(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.HostStatSampler_HOSTSTATSAMPLER_THREAD_COULD_NOT_BE_STOPPED));
+ }
+ } else {
+ this.stopRequested = false;
+ statThread = null;
+ }
+ }
+ }
+ }
+
+ public final boolean isAlive() {
+ synchronized (HostStatSampler.class) {
+ return statThread != null && statThread.isAlive();
+ }
+ }
+
+ /**
+ * Waits for the special statistics to be initialized. For tests, please
+ * use {@link #waitForInitialization(long)} instead.
+ *
+ * @see #initSpecialStats
+ * @since GemFire 3.5
+ */
+ public final void waitForInitialization() throws InterruptedException {
+ this.statSamplerInitializedLatch.await();
+ }
+
+ /**
+ * Waits for the special statistics to be initialized. This overridden
+ * version of {@link #waitForInitialization()} should always be used
+ * within tests.
+ *
+ * @see #initSpecialStats
+ * @since GemFire 7.0
+ */
+ public final boolean waitForInitialization(long ms) throws InterruptedException {
+ return this.statSamplerInitializedLatch.await(ms);
+ }
+
+ public final void changeArchive(File newFile) {
+ this.sampleCollector.changeArchive(newFile, NanoTimer.getTime());
+ }
+
+ /**
+ * Returns the <code>VMStatsContract</code> for this VM.
+ *
+ * @since GemFire 3.5
+ */
+ public final VMStatsContract getVMStats() {
+ return this.vmStats;
+ }
+
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder(getClass().getName());
+ sb.append("@").append(System.identityHashCode(this));
+ return sb.toString();
+ }
+
+ protected abstract void checkListeners();
+
+ /**
+ * Gets the sample rate in milliseconds
+ */
+ protected abstract int getSampleRate();
+
+ /**
+ * Returns true if sampling is enabled.
+ */
+ public abstract boolean isSamplingEnabled();
+
+ /**
+ * Returns the statistics manager using this sampler.
+ */
+ protected abstract StatisticsManager getStatisticsManager();
+
+ protected OsStatisticsFactory getOsStatisticsFactory() {
+ return null;
+ }
+
+ protected void initProcessStats(long id) {
+ // do nothing by default
+ }
+
+ protected void sampleProcessStats(boolean prepareOnly) {
+ // do nothing by default
+ }
+
+ protected void closeProcessStats() {
+ // do nothing by default
+ }
+
+ protected long getSpecialStatsId() {
+ return getStatisticsManager().getId();
+ }
+
+ protected final boolean fileSizeLimitInKB() {
+ return this.fileSizeLimitInKB;
+ }
+
+ protected final boolean osStatsDisabled() {
+ return this.osStatsDisabled;
+ }
+
+ protected final boolean stopRequested() {
+ return stopper.isCancelInProgress() || this.stopRequested;
+ }
+
+ public final SampleCollector getSampleCollector() {
+ return this.sampleCollector;
+ }
+
+ /**
+ * Initialize any special sampler stats
+ */
+ private synchronized void initSpecialStats() {
+ // add a vm resource
+ long id = getSpecialStatsId();
+ this.vmStats = VMStatsContractFactory.create(getStatisticsManager(), id);
+ initProcessStats(id);
+ }
+
+ /**
+ * Closes down anything initialied by initSpecialStats.
+ */
+ private synchronized void closeSpecialStats() {
+ if (this.vmStats != null) {
+ this.vmStats.close();
+ }
+ closeProcessStats();
+ }
+
+ /**
+ * Called when this sampler has spent some time working and wants
+ * it to be accounted for.
+ */
+ private void accountForTimeSpentWorking(long nanosSpentWorking,
+ long nanosSpentSleeping) {
+ this.samplerStats.tookSample(
+ nanosSpentWorking, getStatisticsManager().getStatisticsCount(), nanosSpentSleeping);
+ }
+
+ /**
+ * @param timer a NanoTimer used to compute the elapsed delay
+ * @param nanosToDelay the timestamp to delay until it is the current time
+ */
+ private void delay(NanoTimer timer, final long nanosToDelay) throws InterruptedException {
+ timer.reset();
+ long now = timer.getLastResetTime();
+ long remainingNanos = nanosToDelay - now;
+ if (remainingNanos <= 0) {
+ remainingNanos = NanoTimer.millisToNanos(MIN_MS_SLEEP);
+ }
+ while (remainingNanos > 0 && !stopRequested()) {
+ long ms = NanoTimer.nanosToMillis(remainingNanos);
+ if (ms <= 0) {
+ Thread.yield();
+ } else {
+ if (ms > MIN_MS_SLEEP) {
+ ms -= MIN_MS_SLEEP;
+ }
+ synchronized (this) {
+ if (stopRequested()) {
+ // check stopRequested inside the sync to prevent a race in which the wait misses the stopper's notify.
+ return;
+ }
+ this.wait(ms); // spurious wakeup ok
+ }
+ }
+ timer.reset();
+ now = timer.getLastResetTime();
+ remainingNanos = nanosToDelay - now;
+ }
+ }
+
+ private long getNanoRate() {
+ return NanoTimer.millisToNanos(getSampleRate());
+ }
+
+ /**
+ * Collect samples of any operating system statistics
+ *
+ * @param prepareOnly
+ * set to true if you only want to call prepareForSample
+ */
+ private void sampleSpecialStats(boolean prepareOnly) {
+ List<Statistics> statsList = getStatisticsManager().getStatsList();
+ for (Statistics s : statsList) {
+ if (stopRequested()) return;
+ if (s instanceof StatisticsImpl) {
+ ((StatisticsImpl)s).prepareForSample();
+ }
+ }
+
+ if (!prepareOnly && this.vmStats != null) {
+ if (stopRequested()) return;
+ this.vmStats.refresh();
+ }
+ sampleProcessStats(prepareOnly);
+ }
+
+ /**
+ * Check the elapsed sleep time upon wakeup, and log a warning if it is longer than the delay
+ * threshold.
+ *
+ * @param elapsedSleepTime duration of sleep in nanoseconds
+ */
+ private void checkElapsedSleepTime(long elapsedSleepTime) {
+ if (STAT_SAMPLER_DELAY_THRESHOLD > 0) {
+ final long wakeupDelay = elapsedSleepTime - getNanoRate();
+ if (wakeupDelay > STAT_SAMPLER_DELAY_THRESHOLD_NANOS) {
+ this.samplerStats.incJvmPauses();
+ logger.warn(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.HostStatSampler_STATISTICS_SAMPLING_THREAD_DETECTED_A_WAKEUP_DELAY_OF_0_MS_INDICATING_A_POSSIBLE_RESOURCE_ISSUE, NanoTimer.nanosToMillis(wakeupDelay)));
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/IgnoreResourceException.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/IgnoreResourceException.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/IgnoreResourceException.java
index 2abf4b8..4e6e562 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/IgnoreResourceException.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/IgnoreResourceException.java
@@ -22,7 +22,7 @@ import com.gemstone.gemfire.GemFireCheckedException;
* Indicates that a Statistics resource instance with a null StatisticsType
* should be ignored by the statistics sampler.
* <p/>
- * Extracted from {@link com.gemstone.gemfire.internal.StatArchiveWriter}.
+ * Extracted from {@link StatArchiveWriter}.
*
* @since GemFire 7.0
*/
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatListener.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatListener.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatListener.java
new file mode 100644
index 0000000..0942e78
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatListener.java
@@ -0,0 +1,40 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+/**
+ * Implement this interface to receive call back when a stat value has changed.
+ * The listener has to be registered with statSampler. This can be done in the
+ * following manner:
+ * <code>
+ * InternalDistributedSystem internalSystem = (InternalDistributedSystem)cache
+ * .getDistributedSystem();
+ * final GemFireStatSampler sampler = internalSystem.getStatSampler();
+ * sampler.addLocalStatListener(l, stats, statName);
+ * </code>
+ *
+ *
+ */
+public interface LocalStatListener {
+ /**
+ * Invoked when the value of a statistic has changed
+ *
+ * @param value
+ * The new value of the statistic
+ */
+ public void statValueChanged( double value );
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatisticsFactory.java
new file mode 100644
index 0000000..489894b
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatisticsFactory.java
@@ -0,0 +1,103 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import org.apache.logging.log4j.Logger;
+
+import com.gemstone.gemfire.CancelCriterion;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsFactory;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
+import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
+import com.gemstone.gemfire.internal.statistics.AbstractStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.DummyStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.SimpleStatSampler;
+import com.gemstone.gemfire.internal.statistics.StatisticsManager;
+
+/**
+ * A standalone implementation of {@link StatisticsFactory}.
+ * It can be used in contexts that do not have the GemFire product
+ * or in vm's that do not have a distributed system nor a gemfire connection.
+ *
+ */
+public class LocalStatisticsFactory extends AbstractStatisticsFactory
+ implements StatisticsFactory, StatisticsManager {
+
+ private static final Logger logger = LogService.getLogger();
+
+ public static final String STATS_DISABLE_NAME_PROPERTY = "stats.disable";
+
+ private final SimpleStatSampler sampler;
+ private final boolean statsDisabled;
+
+ public LocalStatisticsFactory(CancelCriterion stopper) {
+ super(initId(), initName(), initStartTime());
+
+ this.statsDisabled = Boolean.getBoolean(STATS_DISABLE_NAME_PROPERTY);
+ if (statsDisabled) {
+ this.sampler = null;
+ logger.info(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.LocalStatisticsFactory_STATISTIC_COLLECTION_IS_DISABLED_USE_DSTATSDISABLEFALSE_TO_TURN_ON_STATISTICS));
+ } else if (stopper != null) {
+ this.sampler = new SimpleStatSampler(stopper, this);
+ this.sampler.start();
+ } else {
+ this.sampler = null;
+ }
+ }
+
+ protected static long initId() {
+ return Thread.currentThread().hashCode();
+ }
+
+ protected static String initName() {
+ return System.getProperty("stats.name", Thread.currentThread().getName());
+ }
+
+ protected static long initStartTime() {
+ return System.currentTimeMillis();
+ }
+
+ protected SimpleStatSampler getStatSampler() {
+ return this.sampler;
+ }
+
+ @Override
+ public void close() {
+ if (this.sampler != null) {
+ this.sampler.stop();
+ }
+ }
+
+ @Override
+ protected Statistics createOsStatistics(StatisticsType type, String textId, long numericId, int osStatFlags) {
+ if (this.statsDisabled) {
+ return new DummyStatisticsImpl(type, textId, numericId);
+ }
+ return super.createOsStatistics(type, textId, numericId, osStatFlags);
+ }
+
+ @Override
+ public Statistics createAtomicStatistics(StatisticsType type, String textId, long numericId) {
+ if (this.statsDisabled) {
+ return new DummyStatisticsImpl(type, textId, numericId);
+ }
+ return super.createAtomicStatistics(type, textId, numericId);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatisticsImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatisticsImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatisticsImpl.java
new file mode 100644
index 0000000..4c8733a
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/LocalStatisticsImpl.java
@@ -0,0 +1,272 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.OSProcess;
+import com.gemstone.gemfire.internal.statistics.StatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsManager;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeImpl;
+//import com.gemstone.gemfire.util.IntArray;
+//import com.gemstone.gemfire.util.LongArray;
+
+/**
+ * An implementation of {@link Statistics} that stores its statistics
+ * in local java memory.
+ *
+ * @see <A href="package-summary.html#statistics">Package introduction</A>
+ *
+ *
+ * @since GemFire 3.0
+ *
+ */
+public class LocalStatisticsImpl extends StatisticsImpl {
+
+ /** In JOM Statistics, the values of the int statistics */
+ private final int[] intStorage;
+
+ /** In JOM Statistics, the values of the long statistics */
+ private final long[] longStorage;
+
+ /** In JOM Statistics, the values of the double statistics */
+ private final double[] doubleStorage;
+
+ /** An array containing the JOM object used to lock a int statistic when
+ * it is incremented. */
+ private transient final Object[] intLocks;
+
+ /** An array containing the JOM object used to lock a long statistic when
+ * it is incremented. */
+ private transient final Object[] longLocks;
+
+ /** An array containing the JOM object used to lock a double statistic when
+ * it is incremented. */
+ private transient final Object[] doubleLocks;
+
+ /** The StatisticsFactory that created this instance */
+ private final StatisticsManager dSystem;
+
+ /////////////////////// Constructors ///////////////////////
+
+ /**
+ * Creates a new statistics instance of the given type
+ *
+ * @param type
+ * A description of the statistics
+ * @param textId
+ * Text that identifies this statistic when it is monitored
+ * @param numericId
+ * A number that displayed when this statistic is monitored
+ * @param uniqueId
+ * A number that uniquely identifies this instance
+ * @param atomicIncrements
+ * Are increment operations atomic? If only one application
+ * thread increments a statistic, then a <code>false</code>
+ * value may yield better performance.
+ * @param osStatFlags
+ * Non-zero if stats require system calls to collect them; for internal use only
+ * @param system
+ * The distributed system that determines whether or not these
+ * statistics are stored (and collected) in GemFire shared
+ * memory or in the local VM
+ */
+ public LocalStatisticsImpl(StatisticsType type, String textId,
+ long numericId,
+ long uniqueId,
+ boolean atomicIncrements,
+ int osStatFlags,
+ StatisticsManager system) {
+ super(type, calcTextId(system, textId), calcNumericId(system, numericId),
+ uniqueId, osStatFlags);
+
+ this.dSystem = system;
+
+ StatisticsTypeImpl realType = (StatisticsTypeImpl)type;
+ int intCount = realType.getIntStatCount();
+ int longCount = realType.getLongStatCount();
+ int doubleCount = realType.getDoubleStatCount();
+
+ if (intCount > 0) {
+ this.intStorage = new int[intCount];
+ if (atomicIncrements) {
+ this.intLocks = new Object[intCount];
+ for (int i = 0; i < intLocks.length; i++) {
+ intLocks[i] = new Object();
+ }
+ } else {
+ this.intLocks = null;
+ }
+ } else {
+ this.intStorage = null;
+ this.intLocks = null;
+ }
+
+ if (longCount > 0) {
+ this.longStorage = new long[longCount];
+ if (atomicIncrements) {
+ this.longLocks = new Object[longCount];
+ for (int i = 0; i < longLocks.length; i++) {
+ longLocks[i] = new Object();
+ }
+ } else {
+ this.longLocks = null;
+ }
+ } else {
+ this.longStorage = null;
+ this.longLocks = null;
+ }
+
+ if (doubleCount > 0) {
+ this.doubleStorage = new double[doubleCount];
+ if (atomicIncrements) {
+ this.doubleLocks = new Object[doubleCount];
+ for (int i = 0; i < doubleLocks.length; i++) {
+ doubleLocks[i] = new Object();
+ }
+ } else {
+ this.doubleLocks = null;
+ }
+ } else {
+ this.doubleStorage = null;
+ this.doubleLocks = null;
+ }
+ }
+
+ ////////////////////// Static Methods //////////////////////
+
+ private static long calcNumericId(StatisticsManager system, long userValue) {
+ if (userValue != 0) {
+ return userValue;
+ } else {
+ long result = OSProcess.getId(); // fix for bug 30239
+ if (result == 0) {
+ if (system != null) {
+ result = system.getId();
+ }
+ }
+ return result;
+ }
+ }
+
+ private static String calcTextId(StatisticsManager system, String userValue) {
+ if (userValue != null && !userValue.equals("")) {
+ return userValue;
+ } else {
+ if (system != null) {
+ return system.getName();
+ } else {
+ return "";
+ }
+ }
+ }
+
+ ////////////////////// Instance Methods //////////////////////
+
+ @Override
+ public final boolean isAtomic() {
+ return intLocks != null || longLocks != null || doubleLocks != null;
+ }
+
+ @Override
+ public void close() {
+ super.close();
+ if (this.dSystem != null) {
+ dSystem.destroyStatistics(this);
+ }
+ }
+
+ //////////////////////// store() Methods ///////////////////////
+
+ @Override
+ protected final void _setInt(int offset, int value) {
+ this.intStorage[offset] = value;
+ }
+
+ @Override
+ protected final void _setLong(int offset, long value) {
+ this.longStorage[offset] = value;
+ }
+
+ @Override
+ protected final void _setDouble(int offset, double value) {
+ this.doubleStorage[offset] = value;
+ }
+
+ /////////////////////// get() Methods ///////////////////////
+
+ @Override
+ protected final int _getInt(int offset) {
+ return this.intStorage[offset];
+ }
+
+ @Override
+ protected final long _getLong(int offset) {
+ return this.longStorage[offset];
+ }
+
+ @Override
+ protected final double _getDouble(int offset) {
+ return this.doubleStorage[offset];
+ }
+
+ //////////////////////// inc() Methods ////////////////////////
+
+ @Override
+ protected final void _incInt(int offset, int delta) {
+ if (this.intLocks != null) {
+ synchronized (this.intLocks[offset]) {
+ this.intStorage[offset] += delta;
+ }
+ } else {
+ this.intStorage[offset] += delta;
+ }
+ }
+
+ @Override
+ protected final void _incLong(int offset, long delta) {
+ if (this.longLocks != null) {
+ synchronized (this.longLocks[offset]) {
+ this.longStorage[offset] += delta;
+ }
+ } else {
+ this.longStorage[offset] += delta;
+ }
+ }
+
+ @Override
+ protected final void _incDouble(int offset, double delta) {
+ if (this.doubleLocks != null) {
+ synchronized (this.doubleLocks[offset]) {
+ this.doubleStorage[offset] += delta;
+ }
+ } else {
+ this.doubleStorage[offset] += delta;
+ }
+ }
+
+ /////////////////// internal package methods //////////////////
+
+ final int[] _getIntStorage() {
+ return this.intStorage;
+ }
+ final long[] _getLongStorage() {
+ return this.longStorage;
+ }
+ final double[] _getDoubleStorage() {
+ return this.doubleStorage;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceInstance.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceInstance.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceInstance.java
index 0de95e2..6d63d3c 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceInstance.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceInstance.java
@@ -24,7 +24,7 @@ import com.gemstone.gemfire.Statistics;
* instances depending on the statistics type. The ResourceInstance holds
* an array of the latest stat values.
* <p/>
- * Extracted from {@link com.gemstone.gemfire.internal.StatArchiveWriter}.
+ * Extracted from {@link StatArchiveWriter}.
*
* @since GemFire 7.0
*/
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceType.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceType.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceType.java
index d401969..fcdc1a0 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceType.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ResourceType.java
@@ -24,7 +24,7 @@ import com.gemstone.gemfire.StatisticsType;
* each ResourceInstance. The ResourceType holds an array of
* StatisticDescriptors for its StatisticsType.
* <p/>
- * Extracted from {@link com.gemstone.gemfire.internal.StatArchiveWriter}.
+ * Extracted from {@link StatArchiveWriter}.
*
* @since GemFire 7.0
*/
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/SimpleStatSampler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/SimpleStatSampler.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/SimpleStatSampler.java
new file mode 100644
index 0000000..599d42c
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/SimpleStatSampler.java
@@ -0,0 +1,112 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import java.io.File;
+
+import org.apache.logging.log4j.Logger;
+
+import com.gemstone.gemfire.CancelCriterion;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
+import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
+
+/**
+ * SimpleStatSampler is a functional implementation of HostStatSampler
+ * that samples statistics stored in local java memory and does not
+ * require any native code or additional GemFire features.
+ * <p>
+ * The StatisticsManager may be implemented by LocalStatisticsFactory and does
+ * not require a GemFire connection.
+
+ */
+public class SimpleStatSampler extends HostStatSampler {
+
+ private static final Logger logger = LogService.getLogger();
+
+ public static final String ARCHIVE_FILE_NAME_PROPERTY = "stats.archive-file";
+ public static final String FILE_SIZE_LIMIT_PROPERTY = "stats.file-size-limit";
+ public static final String DISK_SPACE_LIMIT_PROPERTY = "stats.disk-space-limit";
+ public static final String SAMPLE_RATE_PROPERTY = "stats.sample-rate";
+
+ public static final String DEFAULT_ARCHIVE_FILE_NAME = "stats.gfs";
+ public static final long DEFAULT_FILE_SIZE_LIMIT = 0;
+ public static final long DEFAULT_DISK_SPACE_LIMIT = 0;
+ public static final int DEFAULT_SAMPLE_RATE = 1000;
+
+ private final File archiveFileName = new File(System.getProperty(ARCHIVE_FILE_NAME_PROPERTY, DEFAULT_ARCHIVE_FILE_NAME));
+ private final long archiveFileSizeLimit = Long.getLong(FILE_SIZE_LIMIT_PROPERTY, DEFAULT_FILE_SIZE_LIMIT).longValue() * (1024*1024);
+ private final long archiveDiskSpaceLimit = Long.getLong(DISK_SPACE_LIMIT_PROPERTY, DEFAULT_DISK_SPACE_LIMIT).longValue() * (1024*1024);
+ private final int sampleRate = Integer.getInteger(SAMPLE_RATE_PROPERTY, DEFAULT_SAMPLE_RATE).intValue();
+
+ private final StatisticsManager sm;
+
+ public SimpleStatSampler(CancelCriterion stopper, StatisticsManager sm) {
+ super(stopper, new StatSamplerStats(sm, sm.getId()));
+ this.sm = sm;
+ logger.info(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.SimpleStatSampler_STATSSAMPLERATE_0, getSampleRate()));
+ }
+
+ @Override
+ protected void checkListeners() {
+ // do nothing
+ }
+
+ @Override
+ public File getArchiveFileName() {
+ return this.archiveFileName;
+ }
+
+ @Override
+ public long getArchiveFileSizeLimit() {
+ if (fileSizeLimitInKB()) {
+ return this.archiveFileSizeLimit / 1024;
+ } else {
+ return this.archiveFileSizeLimit;
+ }
+ }
+
+ @Override
+ public long getArchiveDiskSpaceLimit() {
+ if (fileSizeLimitInKB()) {
+ return this.archiveDiskSpaceLimit / 1024;
+ } else {
+ return this.archiveDiskSpaceLimit;
+ }
+ }
+
+ @Override
+ public String getProductDescription() {
+ return "Unknown product";
+ }
+
+ @Override
+ protected StatisticsManager getStatisticsManager() {
+ return this.sm;
+ }
+
+ @Override
+ protected int getSampleRate() {
+ return this.sampleRate;
+ }
+
+ @Override
+ public boolean isSamplingEnabled() {
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveDescriptor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveDescriptor.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveDescriptor.java
index 6d6624a..54d6af0 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveDescriptor.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveDescriptor.java
@@ -18,11 +18,11 @@ package com.gemstone.gemfire.internal.statistics;
/**
* Descriptor containing all of the parameters required to construct a new
- * instance of a {@link com.gemstone.gemfire.internal.StatArchiveWriter}.
+ * instance of a {@link StatArchiveWriter}.
* This describes the statistics archive.
* <p/>
* This is a constructor parameter object for {@link
- * com.gemstone.gemfire.internal.StatArchiveWriter}.
+ * StatArchiveWriter}.
* <p/>
* {@link StatArchiveDescriptor.Builder} is used for constructing instances
* instead of a constructor with many similar parameters (ie, multiple Strings
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveFormat.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveFormat.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveFormat.java
new file mode 100644
index 0000000..4651b5d
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveFormat.java
@@ -0,0 +1,197 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+/**
+ * StatArchiveFormat defines constants related to the statistic archive
+ * file format.
+ */
+public interface StatArchiveFormat {
+ /**
+ * ARCHIVE_VERSION identifies the format of the contents of the archive.
+ * It should be changed any time an incompatible change is made.
+ * Its current value is <code>3</code>.
+ * <p>
+ * <ol>
+ * <li> Changed from 2 to 3 with addition of <code>RESOURCE_INSTANCE_INITIALIZE_TOKEN</code>
+ * <li> Changed from 3 to 4 with addition of largerBetter boolean in statistic descriptor
+ * </ol>
+ */
+ public static final byte ARCHIVE_VERSION=4;
+
+ /**
+ * Token consists of a timestamp and any statistic value changes.
+ */
+ public static final byte SAMPLE_TOKEN=0;
+ /**
+ * Token defines a new resource type.
+ */
+ public static final byte RESOURCE_TYPE_TOKEN=1;
+ /**
+ * Token defines a new resource instance.
+ */
+ public static final byte RESOURCE_INSTANCE_CREATE_TOKEN=2;
+ /**
+ * Token notes that a previous resource instance no longer exists
+ * and thus will have any more samples of its statistic values taken.
+ */
+ public static final byte RESOURCE_INSTANCE_DELETE_TOKEN=3;
+ /**
+ * Token defines a new resource instance with initial data.
+ */
+ public static final byte RESOURCE_INSTANCE_INITIALIZE_TOKEN=4;
+ /**
+ * Token defines a new archive and provides some global information
+ * about the environment the archive was created in.
+ */
+ public static final byte HEADER_TOKEN=77;
+
+ /**
+ * The value used to signal the end of a list of resource instances.
+ */
+ public static final int ILLEGAL_RESOURCE_INST_ID=-1;
+ /**
+ * The maximum value a resource inst id can have and still be stored
+ * in the archive as an unsigned byte.
+ */
+ public static final int MAX_BYTE_RESOURCE_INST_ID=252;
+ /**
+ * Used to say that the next two bytes contain the resource inst id
+ * as an unsigned short.
+ */
+ public static final int SHORT_RESOURCE_INST_ID_TOKEN=253;
+ /**
+ * Used to say that the next four bytes contain the resource inst id
+ * as an int.
+ */
+ public static final int INT_RESOURCE_INST_ID_TOKEN=254;
+ /**
+ * Used to say that the current byte represents the ILLEGAL_RESOURCE_INST_ID.
+ */
+ public static final int ILLEGAL_RESOURCE_INST_ID_TOKEN=255;
+ /**
+ * The maximum value a resource inst id can have and still be stored
+ * in the archive as an unsigned short.
+ */
+ public static final int MAX_SHORT_RESOURCE_INST_ID=65535;
+ /**
+ * The value used to signal the end of a list of statistic samples.
+ */
+ public static final int ILLEGAL_STAT_OFFSET=255;
+
+ /**
+ * The maximum value a timestamp can have and still be stored
+ * in the archive as an unsigned short.
+ */
+ public static final int MAX_SHORT_TIMESTAMP=65534;
+ /**
+ * Means the next 4 bytes contain the timestamp as an int.
+ */
+ public static final int INT_TIMESTAMP_TOKEN=65535;
+
+ /**
+ * The maximum value a compact value can have and still be stored
+ * in the archive as one byte.
+ */
+ public static final int MAX_1BYTE_COMPACT_VALUE=Byte.MAX_VALUE;
+ /**
+ * The minimum value a compact value can have and still be stored
+ * in the archive as one byte.
+ */
+ public static final int MIN_1BYTE_COMPACT_VALUE=Byte.MIN_VALUE+7;
+ /**
+ * The maximum value a compact value can have and still be stored
+ * in the archive as two bytes.
+ */
+ public static final int MAX_2BYTE_COMPACT_VALUE=Short.MAX_VALUE;
+ /**
+ * The minimum value a compact value can have and still be stored
+ * in the archive as two bytes.
+ */
+ public static final int MIN_2BYTE_COMPACT_VALUE=Short.MIN_VALUE;
+
+ /**
+ * Means the next 2 bytes hold the compact value's data.
+ */
+ public static final int COMPACT_VALUE_2_TOKEN=Byte.MIN_VALUE;
+ /**
+ * Means the next 3 bytes hold the compact value's data.
+ */
+ public static final int COMPACT_VALUE_3_TOKEN=Byte.MIN_VALUE+1;
+ /**
+ * Means the next 4 bytes hold the compact value's data.
+ */
+ public static final int COMPACT_VALUE_4_TOKEN=Byte.MIN_VALUE+2;
+ /**
+ * Means the next 5 bytes hold the compact value's data.
+ */
+ public static final int COMPACT_VALUE_5_TOKEN=Byte.MIN_VALUE+3;
+ /**
+ * Means the next 6 bytes hold the compact value's data.
+ */
+ public static final int COMPACT_VALUE_6_TOKEN=Byte.MIN_VALUE+4;
+ /**
+ * Means the next 7 bytes hold the compact value's data.
+ */
+ public static final int COMPACT_VALUE_7_TOKEN=Byte.MIN_VALUE+5;
+ /**
+ * Means the next 8 bytes hold the compact value's data.
+ */
+ public static final int COMPACT_VALUE_8_TOKEN=Byte.MIN_VALUE+6;
+
+ /**
+ * Statistic represents a <code>boolean</code> java primitive.
+ */
+ public static final int BOOLEAN_CODE = 1;
+ /**
+ * Statistic represents a <code>char</code> java primitive.
+ */
+ public static final int CHAR_CODE = 2;
+ /**
+ * Statistic represents a <code>char</code> java primitive.
+ */
+ public static final int WCHAR_CODE = 12;
+ /**
+ * Statistic represents a <code>byte</code> java primitive.
+ */
+ public static final int BYTE_CODE = 3;
+ /**
+ * Statistic represents a <code>short</code> java primitive.
+ */
+ public static final int SHORT_CODE = 4;
+ /**
+ * Statistic represents a <code>int</code> java primitive.
+ */
+ public static final int INT_CODE = 5;
+ /**
+ * Statistic represents a <code>long</code> java primitive.
+ */
+ public static final int LONG_CODE = 6;
+ /**
+ * Statistic represents a <code>float</code> java primitive.
+ */
+ public static final int FLOAT_CODE = 7;
+ /**
+ * Statistic represents a <code>double</code> java primitive.
+ */
+ public static final int DOUBLE_CODE = 8;
+ /**
+ * Number of nanoseconds in one millisecond
+ */
+ public static final long NANOS_PER_MILLI = 1000000;
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandler.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandler.java
index e686ad6..fc9030c 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandler.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandler.java
@@ -28,7 +28,6 @@ import org.apache.logging.log4j.Logger;
import com.gemstone.gemfire.GemFireException;
import com.gemstone.gemfire.GemFireIOException;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import com.gemstone.gemfire.internal.StatArchiveWriter;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.internal.logging.InternalLogWriter;
import com.gemstone.gemfire.internal.logging.LogService;
@@ -40,13 +39,13 @@ import com.gemstone.gemfire.internal.logging.log4j.LogWriterAppenders;
import com.gemstone.gemfire.internal.logging.log4j.LogWriterLogger;
/**
- * Extracted from {@link com.gemstone.gemfire.internal.HostStatSampler} and
- * {@link com.gemstone.gemfire.internal.GemFireStatSampler}.
+ * Extracted from {@link HostStatSampler} and
+ * {@link GemFireStatSampler}.
* <p/>
* The StatArchiveHandler handles statistics samples by archiving them to a
* file. This handler provides archive file rolling (file size limit) and
* removal (disk space limit). This handler creates and uses an instance of
- * {@link com.gemstone.gemfire.internal.StatArchiveWriter} for the currently
+ * {@link StatArchiveWriter} for the currently
* open archive file (unless archiving is disabled).
*
* @since GemFire 7.0
@@ -100,7 +99,7 @@ public class StatArchiveHandler implements SampleHandler {
}
/**
- * Closes any {@link com.gemstone.gemfire.internal.StatArchiveWriter}
+ * Closes any {@link StatArchiveWriter}
* currently in use by this handler.
* @throws GemFireException
*/
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandlerConfig.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandlerConfig.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandlerConfig.java
index dd46013..ea07827 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandlerConfig.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveHandlerConfig.java
@@ -22,7 +22,7 @@ import java.io.File;
* Defines the contract enabling the {@link StatArchiveHandler} to retrieve
* configuration details (some of which may change at runtime).
* <p/>
- * Implemented by {@link com.gemstone.gemfire.internal.HostStatSampler}.
+ * Implemented by {@link HostStatSampler}.
* @since GemFire 7.0
* @see com.gemstone.gemfire.distributed.internal.RuntimeDistributionConfigImpl
[20/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatisticsFactory.java
deleted file mode 100644
index 6f8315a..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatisticsFactory.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import org.apache.logging.log4j.Logger;
-
-import com.gemstone.gemfire.CancelCriterion;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsFactory;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
-import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
-
-/**
- * A standalone implementation of {@link StatisticsFactory}.
- * It can be used in contexts that do not have the GemFire product
- * or in vm's that do not have a distributed system nor a gemfire connection.
- *
- */
-public class LocalStatisticsFactory extends AbstractStatisticsFactory
- implements StatisticsFactory, StatisticsManager {
-
- private static final Logger logger = LogService.getLogger();
-
- public static final String STATS_DISABLE_NAME_PROPERTY = "stats.disable";
-
- private final SimpleStatSampler sampler;
- private final boolean statsDisabled;
-
- public LocalStatisticsFactory(CancelCriterion stopper) {
- super(initId(), initName(), initStartTime());
-
- this.statsDisabled = Boolean.getBoolean(STATS_DISABLE_NAME_PROPERTY);
- if (statsDisabled) {
- this.sampler = null;
- logger.info(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.LocalStatisticsFactory_STATISTIC_COLLECTION_IS_DISABLED_USE_DSTATSDISABLEFALSE_TO_TURN_ON_STATISTICS));
- } else if (stopper != null) {
- this.sampler = new SimpleStatSampler(stopper, this);
- this.sampler.start();
- } else {
- this.sampler = null;
- }
- }
-
- protected static long initId() {
- return Thread.currentThread().hashCode();
- }
-
- protected static String initName() {
- return System.getProperty("stats.name", Thread.currentThread().getName());
- }
-
- protected static long initStartTime() {
- return System.currentTimeMillis();
- }
-
- protected SimpleStatSampler getStatSampler() {
- return this.sampler;
- }
-
- @Override
- public void close() {
- if (this.sampler != null) {
- this.sampler.stop();
- }
- }
-
- @Override
- protected Statistics createOsStatistics(StatisticsType type, String textId, long numericId, int osStatFlags) {
- if (this.statsDisabled) {
- return new DummyStatisticsImpl(type, textId, numericId);
- }
- return super.createOsStatistics(type, textId, numericId, osStatFlags);
- }
-
- @Override
- public Statistics createAtomicStatistics(StatisticsType type, String textId, long numericId) {
- if (this.statsDisabled) {
- return new DummyStatisticsImpl(type, textId, numericId);
- }
- return super.createAtomicStatistics(type, textId, numericId);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatisticsImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatisticsImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatisticsImpl.java
deleted file mode 100644
index cf59e1f..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatisticsImpl.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-//import com.gemstone.gemfire.util.IntArray;
-//import com.gemstone.gemfire.util.LongArray;
-
-/**
- * An implementation of {@link Statistics} that stores its statistics
- * in local java memory.
- *
- * @see <A href="package-summary.html#statistics">Package introduction</A>
- *
- *
- * @since GemFire 3.0
- *
- */
-public class LocalStatisticsImpl extends StatisticsImpl {
-
- /** In JOM Statistics, the values of the int statistics */
- private final int[] intStorage;
-
- /** In JOM Statistics, the values of the long statistics */
- private final long[] longStorage;
-
- /** In JOM Statistics, the values of the double statistics */
- private final double[] doubleStorage;
-
- /** An array containing the JOM object used to lock a int statistic when
- * it is incremented. */
- private transient final Object[] intLocks;
-
- /** An array containing the JOM object used to lock a long statistic when
- * it is incremented. */
- private transient final Object[] longLocks;
-
- /** An array containing the JOM object used to lock a double statistic when
- * it is incremented. */
- private transient final Object[] doubleLocks;
-
- /** The StatisticsFactory that created this instance */
- private final StatisticsManager dSystem;
-
- /////////////////////// Constructors ///////////////////////
-
- /**
- * Creates a new statistics instance of the given type
- *
- * @param type
- * A description of the statistics
- * @param textId
- * Text that identifies this statistic when it is monitored
- * @param numericId
- * A number that displayed when this statistic is monitored
- * @param uniqueId
- * A number that uniquely identifies this instance
- * @param atomicIncrements
- * Are increment operations atomic? If only one application
- * thread increments a statistic, then a <code>false</code>
- * value may yield better performance.
- * @param osStatFlags
- * Non-zero if stats require system calls to collect them; for internal use only
- * @param system
- * The distributed system that determines whether or not these
- * statistics are stored (and collected) in GemFire shared
- * memory or in the local VM
- */
- public LocalStatisticsImpl(StatisticsType type, String textId,
- long numericId,
- long uniqueId,
- boolean atomicIncrements,
- int osStatFlags,
- StatisticsManager system) {
- super(type, calcTextId(system, textId), calcNumericId(system, numericId),
- uniqueId, osStatFlags);
-
- this.dSystem = system;
-
- StatisticsTypeImpl realType = (StatisticsTypeImpl)type;
- int intCount = realType.getIntStatCount();
- int longCount = realType.getLongStatCount();
- int doubleCount = realType.getDoubleStatCount();
-
- if (intCount > 0) {
- this.intStorage = new int[intCount];
- if (atomicIncrements) {
- this.intLocks = new Object[intCount];
- for (int i = 0; i < intLocks.length; i++) {
- intLocks[i] = new Object();
- }
- } else {
- this.intLocks = null;
- }
- } else {
- this.intStorage = null;
- this.intLocks = null;
- }
-
- if (longCount > 0) {
- this.longStorage = new long[longCount];
- if (atomicIncrements) {
- this.longLocks = new Object[longCount];
- for (int i = 0; i < longLocks.length; i++) {
- longLocks[i] = new Object();
- }
- } else {
- this.longLocks = null;
- }
- } else {
- this.longStorage = null;
- this.longLocks = null;
- }
-
- if (doubleCount > 0) {
- this.doubleStorage = new double[doubleCount];
- if (atomicIncrements) {
- this.doubleLocks = new Object[doubleCount];
- for (int i = 0; i < doubleLocks.length; i++) {
- doubleLocks[i] = new Object();
- }
- } else {
- this.doubleLocks = null;
- }
- } else {
- this.doubleStorage = null;
- this.doubleLocks = null;
- }
- }
-
- ////////////////////// Static Methods //////////////////////
-
- private static long calcNumericId(StatisticsManager system, long userValue) {
- if (userValue != 0) {
- return userValue;
- } else {
- long result = OSProcess.getId(); // fix for bug 30239
- if (result == 0) {
- if (system != null) {
- result = system.getId();
- }
- }
- return result;
- }
- }
-
- private static String calcTextId(StatisticsManager system, String userValue) {
- if (userValue != null && !userValue.equals("")) {
- return userValue;
- } else {
- if (system != null) {
- return system.getName();
- } else {
- return "";
- }
- }
- }
-
- ////////////////////// Instance Methods //////////////////////
-
- @Override
- public final boolean isAtomic() {
- return intLocks != null || longLocks != null || doubleLocks != null;
- }
-
- @Override
- public void close() {
- super.close();
- if (this.dSystem != null) {
- dSystem.destroyStatistics(this);
- }
- }
-
- //////////////////////// store() Methods ///////////////////////
-
- @Override
- protected final void _setInt(int offset, int value) {
- this.intStorage[offset] = value;
- }
-
- @Override
- protected final void _setLong(int offset, long value) {
- this.longStorage[offset] = value;
- }
-
- @Override
- protected final void _setDouble(int offset, double value) {
- this.doubleStorage[offset] = value;
- }
-
- /////////////////////// get() Methods ///////////////////////
-
- @Override
- protected final int _getInt(int offset) {
- return this.intStorage[offset];
- }
-
- @Override
- protected final long _getLong(int offset) {
- return this.longStorage[offset];
- }
-
- @Override
- protected final double _getDouble(int offset) {
- return this.doubleStorage[offset];
- }
-
- //////////////////////// inc() Methods ////////////////////////
-
- @Override
- protected final void _incInt(int offset, int delta) {
- if (this.intLocks != null) {
- synchronized (this.intLocks[offset]) {
- this.intStorage[offset] += delta;
- }
- } else {
- this.intStorage[offset] += delta;
- }
- }
-
- @Override
- protected final void _incLong(int offset, long delta) {
- if (this.longLocks != null) {
- synchronized (this.longLocks[offset]) {
- this.longStorage[offset] += delta;
- }
- } else {
- this.longStorage[offset] += delta;
- }
- }
-
- @Override
- protected final void _incDouble(int offset, double delta) {
- if (this.doubleLocks != null) {
- synchronized (this.doubleLocks[offset]) {
- this.doubleStorage[offset] += delta;
- }
- } else {
- this.doubleStorage[offset] += delta;
- }
- }
-
- /////////////////// internal package methods //////////////////
-
- final int[] _getIntStorage() {
- return this.intStorage;
- }
- final long[] _getLongStorage() {
- return this.longStorage;
- }
- final double[] _getDoubleStorage() {
- return this.doubleStorage;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/OSXProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/OSXProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/OSXProcessStats.java
deleted file mode 100644
index 0706c7b..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/OSXProcessStats.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * <P>This class provides the interface for statistics about a
- * Mac OS X operating system process that is using a GemFire system.
- */
-public class OSXProcessStats
-{
-// private final static int imageSizeINT = 0;
-// private final static int rssSizeINT = 1;
-
- private final static StatisticsType myType;
-
- private static void checkOffset(String name, int offset) {
- int id = myType.nameToId(name);
- Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
- }
-
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- myType = f.createType("OSXProcessStats",
- "Statistics on a OS X process.",
- new StatisticDescriptor[] {
- f.createIntGauge("dummyStat",
- "Placeholder",
- "megabytes")
-// f.createIntGauge("imageSize",
-// "The size of the process's image in megabytes.",
-// "megabytes"),
-// f.createIntGauge("rssSize",
-// "The size of the process's resident set size in megabytes.",
-// "megabytes"),
- });
-// checkOffset("imageSize", imageSizeINT);
-// checkOffset("rssSize", rssSizeINT);
- }
-
- private OSXProcessStats() {
- // no instances allowed
- }
- public static StatisticsType getType() {
- return myType;
- }
-
- /**
- * Returns a <code>ProcessStats</code> that wraps OS X process
- * <code>Statistics</code>.
- *
- * @since GemFire 3.5
- */
- static ProcessStats createProcessStats(final Statistics stats) {
- if (stats instanceof LocalStatisticsImpl) {
- HostStatHelper.refresh((LocalStatisticsImpl) stats);
- } // otherwise its a Dummy implementation so do nothing
- return new ProcessStats(stats) {
- @Override
- public long getProcessSize() {
-// return stats.getInt(rssSizeINT);
- return 0L;
- }
- };
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/OSXSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/OSXSystemStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/OSXSystemStats.java
deleted file mode 100644
index 8d440ca..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/OSXSystemStats.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * <P>This class provides the interface for statistics about the
- * OS X machine a GemFire system is running on.
- */
-public class OSXSystemStats
-{
-
- // shared fields
-// private final static int allocatedSwapINT = 0;
-// private final static int bufferMemoryINT = 1;
-// private final static int contextSwitchesINT = 2;
-// private final static int cpuActiveINT = 3;
-// private final static int cpuIdleINT = 4;
-// private final static int cpuNiceINT = 5;
-// private final static int cpuSystemINT = 6;
-// private final static int cpuUserINT = 7;
-// private final static int cpusINT = 8;
-// private final static int freeMemoryINT = 9;
-// private final static int pagesPagedInINT = 10;
-// private final static int pagesPagedOutINT = 11;
-// private final static int pagesSwappedInINT = 12;
-// private final static int pagesSwappedOutINT = 13;
-// private final static int physicalMemoryINT = 14;
-// private final static int processCreatesINT = 15;
-// private final static int processesINT = 16;
-// private final static int sharedMemoryINT = 17;
-// private final static int unallocatedSwapINT = 18;
-//
-// private final static int loopbackPacketsLONG = 0;
-// private final static int loopbackBytesLONG = 1;
-// private final static int recvPacketsLONG = 2;
-// private final static int recvBytesLONG = 3;
-// private final static int recvErrorsLONG = 4;
-// private final static int recvDropsLONG = 5;
-// private final static int xmitPacketsLONG = 6;
-// private final static int xmitBytesLONG = 7;
-// private final static int xmitErrorsLONG = 8;
-// private final static int xmitDropsLONG = 9;
-// private final static int xmitCollisionsLONG = 10;
-//
-// private final static int loadAverage1DOUBLE = 0;
-// private final static int loadAverage15DOUBLE = 1;
-// private final static int loadAverage5DOUBLE = 2;
-
- private final static StatisticsType myType;
-
- private static void checkOffset(String name, int offset) {
- int id = myType.nameToId(name);
- Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
- }
-
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- myType = f.createType("OSXSystemStats",
- "Statistics on an OS X machine.",
- new StatisticDescriptor[] {
- f.createIntGauge("dummyStat",
- "Place holder statistic until Stats are implimented for the Mac OS X Platform.",
- "megabytes"),
-// f.createIntGauge("allocatedSwap",
-// "The number of megabytes of swap space have actually been written to. Swap space must be reserved before it can be allocated.",
-// "megabytes"),
-// f.createIntGauge("bufferMemory",
-// "The number of megabytes of memory allocated to buffers.",
-// "megabytes"),
-// f.createIntCounter("contextSwitches",
-// "The total number of context switches from one thread to another on the computer. Thread switches can occur either inside of a single process or across processes. A thread switch may be caused either by one thread asking another for information, or by a thread being preempted by another, higher priority thread becoming ready to run.",
-// "operations", false),
-// f.createIntGauge("cpuActive",
-// "The percentage of the total available time that has been used in a non-idle state.",
-// "%"),
-// f.createIntGauge("cpuIdle",
-// "The percentage of the total available time that has been spent sleeping.",
-// "%", true),
-// f.createIntGauge("cpuNice",
-// "The percentage of the total available time that has been used to execute user code in processes with low priority.",
-// "%"),
-// f.createIntGauge("cpuSystem",
-// "The percentage of the total available time that has been used to execute system (i.e. kernel) code.",
-// "%"),
-// f.createIntGauge("cpuUser",
-// "The percentage of the total available time that has been used to execute user code.",
-// "%"),
-// f.createIntGauge("cpus",
-// "The number of online cpus on the local machine.",
-// "items"),
-// f.createIntGauge("freeMemory",
-// "The number of megabytes of unused memory on the machine.",
-// "megabytes", true),
-// f.createIntCounter("pagesPagedIn",
-// "The total number of pages that have been brought into memory from disk by the operating system's memory manager.",
-// "pages", false),
-// f.createIntCounter("pagesPagedOut",
-// "The total number of pages that have been flushed from memory to disk by the operating system's memory manager.",
-// "pages", false),
-// f.createIntCounter("pagesSwappedIn",
-// "The total number of swap pages that have been read in from disk by the operating system's memory manager.",
-// "pages", false),
-// f.createIntCounter("pagesSwappedOut",
-// "The total number of swap pages that have been written out to disk by the operating system's memory manager.",
-// "pages", false),
-// f.createIntGauge("physicalMemory",
-// "The actual amount of total physical memory on the machine.",
-// "megabytes", true),
-// f.createIntCounter("processCreates",
-// "The total number of times a process has been created.",
-// "operations", false),
-// f.createIntGauge("processes",
-// "The number of processes in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Each process represents the running of a program.",
-// "processes"),
-// f.createIntGauge("sharedMemory",
-// "The number of megabytes of shared memory on the machine.",
-// "megabytes", true),
-// f.createIntGauge("unallocatedSwap",
-// "The number of megabytes of swap space that have not been allocated.",
-// "megabytes", true),
-//
-// f.createLongCounter("loopbackPackets",
-// "The number of network packets sent (or received) on the loopback interface",
-// "packets", false),
-// f.createLongCounter("loopbackBytes",
-// "The number of network bytes sent (or received) on the loopback interface",
-// "bytes", false),
-// f.createLongCounter("recvPackets",
-// "The total number of network packets received (excluding loopback)",
-// "packets", false),
-// f.createLongCounter("recvBytes",
-// "The total number of network bytes received (excluding loopback)",
-// "bytes", false),
-// f.createLongCounter("recvErrors",
-// "The total number of network receive errors",
-// "errors", false),
-// f.createLongCounter("recvDrops",
-// "The total number network receives dropped",
-// "packets", false),
-// f.createLongCounter("xmitPackets",
-// "The total number of network packets transmitted (excluding loopback)",
-// "packets", false),
-// f.createLongCounter("xmitBytes",
-// "The total number of network bytes transmitted (excluding loopback)",
-// "bytes", false),
-// f.createLongCounter("xmitErrors",
-// "The total number of network transmit errors",
-// "errors", false),
-// f.createLongCounter("xmitDrops",
-// "The total number of network transmits dropped",
-// "packets", false),
-// f.createLongCounter("xmitCollisions",
-// "The total number of network transmit collisions",
-// "collisions", false),
-//
-//
-// f.createDoubleGauge("loadAverage1",
-// "The average number of threads in the run queue or waiting for disk I/O over the last minute.",
-// "threads"),
-// f.createDoubleGauge("loadAverage15",
-// "The average number of threads in the run queue or waiting for disk I/O over the last fifteen minutes.",
-// "threads"),
-// f.createDoubleGauge("loadAverage5",
-// "The average number of threads in the run queue or waiting for disk I/O over the last five minutes.",
-// "threads"),
- });
-
-// checkOffset("allocatedSwap", allocatedSwapINT);
-// checkOffset("bufferMemory", bufferMemoryINT);
-// checkOffset("contextSwitches", contextSwitchesINT);
-// checkOffset("cpuActive", cpuActiveINT);
-// checkOffset("cpuIdle", cpuIdleINT);
-// checkOffset("cpuNice", cpuNiceINT);
-// checkOffset("cpuSystem", cpuSystemINT);
-// checkOffset("cpuUser", cpuUserINT);
-// checkOffset("cpus", cpusINT);
-// checkOffset("freeMemory", freeMemoryINT);
-// checkOffset("pagesPagedIn", pagesPagedInINT);
-// checkOffset("pagesPagedOut", pagesPagedOutINT);
-// checkOffset("pagesSwappedIn", pagesSwappedInINT);
-// checkOffset("pagesSwappedOut", pagesSwappedOutINT);
-// checkOffset("physicalMemory", physicalMemoryINT);
-// checkOffset("processCreates", processCreatesINT);
-// checkOffset("processes", processesINT);
-// checkOffset("sharedMemory", sharedMemoryINT);
-// checkOffset("unallocatedSwap", unallocatedSwapINT);
-//
-// checkOffset("loopbackPackets", loopbackPacketsLONG);
-// checkOffset("loopbackBytes", loopbackBytesLONG);
-// checkOffset("recvPackets", recvPacketsLONG);
-// checkOffset("recvBytes", recvBytesLONG);
-// checkOffset("recvErrors", recvErrorsLONG);
-// checkOffset("recvDrops", recvDropsLONG);
-// checkOffset("xmitPackets", xmitPacketsLONG);
-// checkOffset("xmitBytes", xmitBytesLONG);
-// checkOffset("xmitErrors", xmitErrorsLONG);
-// checkOffset("xmitDrops", xmitDropsLONG);
-// checkOffset("xmitCollisions", xmitCollisionsLONG);
-//
-// checkOffset("loadAverage1", loadAverage1DOUBLE);
-// checkOffset("loadAverage15", loadAverage15DOUBLE);
-// checkOffset("loadAverage5", loadAverage5DOUBLE);
- }
-
- private OSXSystemStats() {
- // no instances allowed
- }
- public static StatisticsType getType() {
- return myType;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/OsStatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/OsStatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/OsStatisticsFactory.java
deleted file mode 100644
index 7dac90e..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/OsStatisticsFactory.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * Instances of this interface provide methods that create operating system
- * instances of {@link com.gemstone.gemfire.Statistics}. Its for internal use
- * only.
- *
- * {@link com.gemstone.gemfire.distributed.DistributedSystem} is an OS
- * statistics factory.
- * <P>
- * @see <A href="package-summary.html#statistics">Package introduction</A>
- *
- *
- * @since GemFire 3.0
- */
-public interface OsStatisticsFactory {
- /**
- * Creates and returns a OS {@link Statistics} instance of the given {@link StatisticsType type}, <code>textId</code>, <code>numericId</code>, and <code>osStatFlags</code>..
- * <p>
- * The created instance may not be {@link Statistics#isAtomic atomic}.
- */
- public Statistics createOsStatistics(StatisticsType type, String textId, long numericId, int osStatFlags);
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/ProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/ProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/ProcessStats.java
deleted file mode 100644
index c80e340..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/ProcessStats.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.Statistics;
-
-/**
- * Abstracts the process statistics that are common on all platforms.
- * This is necessary for monitoring the health of GemFire components.
- *
- *
- * @since GemFire 3.5
- * */
-public abstract class ProcessStats {
-
- /** The underlying statistics */
- private final Statistics stats;
-
- /**
- * Creates a new <code>ProcessStats</code> that wraps the given
- * <code>Statistics</code>.
- */
- ProcessStats(Statistics stats) {
- this.stats = stats;
- }
-
- /**
- * Closes these process stats
- *
- * @see Statistics#close
- */
- public final void close() {
- this.stats.close();
- }
-
- public final Statistics getStatistics() {
- return this.stats;
- }
-
- /**
- * Returns the size of this process (resident set on UNIX or working
- * set on Windows) in megabytes
- */
- public abstract long getProcessSize();
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/SimpleStatSampler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/SimpleStatSampler.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/SimpleStatSampler.java
deleted file mode 100644
index b3cc56b..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/SimpleStatSampler.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import java.io.File;
-
-import org.apache.logging.log4j.Logger;
-
-import com.gemstone.gemfire.CancelCriterion;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
-import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
-
-/**
- * SimpleStatSampler is a functional implementation of HostStatSampler
- * that samples statistics stored in local java memory and does not
- * require any native code or additional GemFire features.
- * <p>
- * The StatisticsManager may be implemented by LocalStatisticsFactory and does
- * not require a GemFire connection.
-
- */
-public class SimpleStatSampler extends HostStatSampler {
-
- private static final Logger logger = LogService.getLogger();
-
- public static final String ARCHIVE_FILE_NAME_PROPERTY = "stats.archive-file";
- public static final String FILE_SIZE_LIMIT_PROPERTY = "stats.file-size-limit";
- public static final String DISK_SPACE_LIMIT_PROPERTY = "stats.disk-space-limit";
- public static final String SAMPLE_RATE_PROPERTY = "stats.sample-rate";
-
- public static final String DEFAULT_ARCHIVE_FILE_NAME = "stats.gfs";
- public static final long DEFAULT_FILE_SIZE_LIMIT = 0;
- public static final long DEFAULT_DISK_SPACE_LIMIT = 0;
- public static final int DEFAULT_SAMPLE_RATE = 1000;
-
- private final File archiveFileName = new File(System.getProperty(ARCHIVE_FILE_NAME_PROPERTY, DEFAULT_ARCHIVE_FILE_NAME));
- private final long archiveFileSizeLimit = Long.getLong(FILE_SIZE_LIMIT_PROPERTY, DEFAULT_FILE_SIZE_LIMIT).longValue() * (1024*1024);
- private final long archiveDiskSpaceLimit = Long.getLong(DISK_SPACE_LIMIT_PROPERTY, DEFAULT_DISK_SPACE_LIMIT).longValue() * (1024*1024);
- private final int sampleRate = Integer.getInteger(SAMPLE_RATE_PROPERTY, DEFAULT_SAMPLE_RATE).intValue();
-
- private final StatisticsManager sm;
-
- public SimpleStatSampler(CancelCriterion stopper, StatisticsManager sm) {
- super(stopper, new StatSamplerStats(sm, sm.getId()));
- this.sm = sm;
- logger.info(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.SimpleStatSampler_STATSSAMPLERATE_0, getSampleRate()));
- }
-
- @Override
- protected void checkListeners() {
- // do nothing
- }
-
- @Override
- public File getArchiveFileName() {
- return this.archiveFileName;
- }
-
- @Override
- public long getArchiveFileSizeLimit() {
- if (fileSizeLimitInKB()) {
- return this.archiveFileSizeLimit / 1024;
- } else {
- return this.archiveFileSizeLimit;
- }
- }
-
- @Override
- public long getArchiveDiskSpaceLimit() {
- if (fileSizeLimitInKB()) {
- return this.archiveDiskSpaceLimit / 1024;
- } else {
- return this.archiveDiskSpaceLimit;
- }
- }
-
- @Override
- public String getProductDescription() {
- return "Unknown product";
- }
-
- @Override
- protected StatisticsManager getStatisticsManager() {
- return this.sm;
- }
-
- @Override
- protected int getSampleRate() {
- return this.sampleRate;
- }
-
- @Override
- public boolean isSamplingEnabled() {
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/SolarisProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/SolarisProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/SolarisProcessStats.java
deleted file mode 100644
index d07d398..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/SolarisProcessStats.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * <P>This class provides the interface for statistics about a
- * Solaris operating system process that is using a GemFire system.
- */
-public class SolarisProcessStats
-{
- private final static int allOtherSleepTimeINT = 0;
- private final static int characterIoINT = 1;
- private final static int dataFaultSleepTimeINT = 2;
- private final static int heapSizeINT = 3;
- private final static int imageSizeINT = 4;
- private final static int involContextSwitchesINT = 5;
- private final static int kernelFaultSleepTimeINT = 6;
- private final static int lockWaitSleepTimeINT = 7;
- private final static int lwpCurCountINT = 8;
- private final static int lwpTotalCountINT = 9;
- private final static int majorFaultsINT = 10;
- private final static int messagesRecvINT = 11;
- private final static int messagesSentINT = 12;
- private final static int minorFaultsINT = 13;
- private final static int rssSizeINT = 14;
- private final static int signalsReceivedINT = 15;
- private final static int systemCallsINT = 16;
- private final static int stackSizeINT = 17;
- private final static int stoppedTimeINT = 18;
- private final static int systemTimeINT = 19;
- private final static int textFaultSleepTimeINT = 20;
- private final static int trapTimeINT = 21;
- private final static int userTimeINT = 22;
- private final static int volContextSwitchesINT = 23;
- private final static int waitCpuTimeINT = 24;
-
- private final static int activeTimeLONG = 0;
-
- private final static int cpuUsedDOUBLE = 0;
- private final static int memoryUsedDOUBLE = 1;
-
- private final static StatisticsType myType;
-
- private static void checkOffset(String name, int offset) {
- int id = myType.nameToId(name);
- Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
- }
-
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- myType = f.createType("SolarisProcessStats",
- "Statistics on a Solaris process.",
- new StatisticDescriptor[] {
- f.createIntCounter("allOtherSleepTime",
- "The number of milliseconds the process has been sleeping for some reason not tracked by any other stat. Note that all lwp's contribute to this stat's value so check lwpCurCount to understand large values.",
- "milliseconds", false),
- f.createIntCounter("characterIo",
- "The number of characters read and written.",
- "bytes"),
- f.createIntCounter("dataFaultSleepTime",
- "The number of milliseconds the process has been faulting in data pages.",
- "milliseconds", false),
- f.createIntGauge("heapSize",
- "The size of the process's heap in megabytes.",
- "megabytes"),
- f.createIntGauge("imageSize",
- "The size of the process's image in megabytes.",
- "megabytes"),
- f.createIntCounter("involContextSwitches",
- "The number of times the process was forced to do a context switch.",
- "operations", false),
- f.createIntCounter("kernelFaultSleepTime",
- "The number of milliseconds the process has been faulting in kernel pages.",
- "milliseconds", false),
- f.createIntCounter("lockWaitSleepTime",
- "The number of milliseconds the process has been waiting for a user lock. Note that all lwp's contribute to this stat's value so check lwpCurCount to understand large values.",
- "milliseconds", false),
- f.createIntGauge("lwpCurCount",
- "The current number of light weight processes that exist in the process.",
- "threads"),
- f.createIntCounter("lwpTotalCount",
- "The total number of light weight processes that have ever contributed to the process's statistics.",
- "threads", false),
- f.createIntCounter("majorFaults",
- "The number of times the process has had a page fault that needed disk access.",
- "operations", false),
- f.createIntCounter("messagesRecv",
- "The number of messages received by the process.",
- "messages"),
- f.createIntCounter("messagesSent",
- "The number of messages sent by the process.",
- "messages"),
- f.createIntCounter("minorFaults",
- "The number of times the process has had a page fault that did not need disk access.",
- "operations", false),
- f.createIntGauge("rssSize",
- "The size of the process's resident set size in megabytes.",
- "megabytes"),
- f.createIntCounter("signalsReceived",
- "The total number of operating system signals this process has received.",
- "signals", false),
- f.createIntCounter("systemCalls",
- "The total number system calls done by this process.",
- "operations"),
- f.createIntGauge("stackSize",
- "The size of the process's stack in megabytes.",
- "megabytes"),
- f.createIntCounter("stoppedTime",
- "The number of milliseconds the process has been stopped.",
- "milliseconds", false),
- f.createIntCounter("systemTime",
- "The number of milliseconds the process has been using the CPU to execute system calls.",
- "milliseconds", false),
- f.createIntCounter("textFaultSleepTime",
- "The number of milliseconds the process has been faulting in text pages.",
- "milliseconds", false),
- f.createIntCounter("trapTime",
- "The number of milliseconds the process has been in system traps.",
- "milliseconds", false),
- f.createIntCounter("userTime",
- "The number of milliseconds the process has been using the CPU to execute user code.",
- "milliseconds", false),
- f.createIntCounter("volContextSwitches",
- "The number of voluntary context switches done by the process.",
- "operations", false),
- f.createIntCounter("waitCpuTime",
- "The number of milliseconds the process has been waiting for a CPU due to latency.",
- "milliseconds", false),
-
-
- f.createLongCounter("activeTime",
- "The number of milliseconds the process has been using the CPU to execute user or system code.",
- "milliseconds", false),
-
-
- f.createDoubleGauge("cpuUsed",
- "The percentage of recent cpu time used by the process.",
- "%"),
- f.createDoubleGauge("memoryUsed",
- "The percentage of real memory used by the process.",
- "%")
- });
-
- checkOffset("allOtherSleepTime", allOtherSleepTimeINT);
- checkOffset("characterIo", characterIoINT);
- checkOffset("dataFaultSleepTime", dataFaultSleepTimeINT);
- checkOffset("heapSize", heapSizeINT);
- checkOffset("imageSize", imageSizeINT);
- checkOffset("involContextSwitches", involContextSwitchesINT);
- checkOffset("kernelFaultSleepTime", kernelFaultSleepTimeINT);
- checkOffset("lockWaitSleepTime", lockWaitSleepTimeINT);
- checkOffset("lwpCurCount", lwpCurCountINT);
- checkOffset("lwpTotalCount", lwpTotalCountINT);
- checkOffset("majorFaults", majorFaultsINT);
- checkOffset("messagesRecv", messagesRecvINT);
- checkOffset("messagesSent", messagesSentINT);
- checkOffset("minorFaults", minorFaultsINT);
- checkOffset("rssSize", rssSizeINT);
- checkOffset("signalsReceived", signalsReceivedINT);
- checkOffset("systemCalls", systemCallsINT);
- checkOffset("stackSize", stackSizeINT);
- checkOffset("stoppedTime", stoppedTimeINT);
- checkOffset("systemTime", systemTimeINT);
- checkOffset("textFaultSleepTime", textFaultSleepTimeINT);
- checkOffset("trapTime", trapTimeINT);
- checkOffset("userTime", userTimeINT);
- checkOffset("volContextSwitches", volContextSwitchesINT);
- checkOffset("waitCpuTime", waitCpuTimeINT);
-
- checkOffset("activeTime", activeTimeLONG);
-
- checkOffset("cpuUsed", cpuUsedDOUBLE);
- checkOffset("memoryUsed", memoryUsedDOUBLE);
- }
-
- private SolarisProcessStats() {
- // no instances allowed
- }
- public static StatisticsType getType() {
- return myType;
- }
-
- /**
- * Returns a <code>ProcessStats</code> that wraps Solaris process
- * <code>Statistics</code>.
- *
- * @since GemFire 3.5
- */
- static ProcessStats createProcessStats(final Statistics stats) {
- if (stats instanceof LocalStatisticsImpl) {
- HostStatHelper.refresh((LocalStatisticsImpl) stats);
- } // otherwise its a Dummy implementation so do nothing
- return new ProcessStats(stats) {
- @Override
- public long getProcessSize() {
- return stats.getInt(rssSizeINT);
- }
- };
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/SolarisSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/SolarisSystemStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/SolarisSystemStats.java
deleted file mode 100644
index 9f56943..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/SolarisSystemStats.java
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * <P>This class provides the interface for statistics about the
- * Solaris machine a GemFire system is running on.
- */
-public class SolarisSystemStats
-{
- private final static int allocatedSwapINT = 0;
- private final static int cpuActiveINT = 1;
- private final static int cpuIdleINT = 2;
- private final static int cpuIoWaitINT = 3;
- private final static int cpuSwapWaitINT = 4;
- private final static int cpuSystemINT = 5;
- private final static int cpuUserINT = 6;
- private final static int cpuWaitingINT = 7;
- private final static int cpusINT = 8;
- private final static int freeMemoryINT = 9;
- private final static int physicalMemoryINT = 10;
- private final static int processesINT = 11;
- private final static int reservedSwapINT = 12;
- private final static int schedulerRunCountINT = 13;
- private final static int schedulerSwapCountINT = 14;
- private final static int schedulerWaitCountINT = 15;
- private final static int unreservedSwapINT = 16;
- private final static int unallocatedSwapINT = 17;
-
- private final static int anonymousPagesFreedLONG = 0;
- private final static int anonymousPagesPagedInLONG = 1;
- private final static int anonymousPagesPagedOutLONG = 2;
- private final static int contextSwitchesLONG = 3;
- private final static int execPagesFreedLONG = 4;
- private final static int execPagesPagedInLONG = 5;
- private final static int execPagesPagedOutLONG = 6;
- private final static int failedMutexEntersLONG = 7;
- private final static int failedReaderLocksLONG = 8;
- private final static int failedWriterLocksLONG = 9;
- private final static int fileSystemPagesFreedLONG = 10;
- private final static int fileSystemPagesPagedInLONG = 11;
- private final static int fileSystemPagesPagedOutLONG = 12;
- private final static int hatMinorFaultsLONG = 13;
- private final static int interruptsLONG = 14;
- private final static int involContextSwitchesLONG = 15;
- private final static int majorPageFaultsLONG = 16;
- private final static int messageCountLONG = 17;
- private final static int pageDaemonCyclesLONG = 18;
- private final static int pageInsLONG = 19;
- private final static int pageOutsLONG = 20;
- private final static int pagerRunsLONG = 21;
- private final static int pagesPagedInLONG = 22;
- private final static int pagesPagedOutLONG = 23;
- private final static int pagesScannedLONG = 24;
- private final static int procsInIoWaitLONG = 25;
- private final static int protectionFaultsLONG = 26;
- private final static int semphoreOpsLONG = 27;
- private final static int softwareLockFaultsLONG = 28;
- private final static int systemCallsLONG = 29;
- private final static int systemMinorFaultsLONG = 30;
- private final static int threadCreatesLONG = 31;
- private final static int trapsLONG = 32;
- private final static int userMinorFaultsLONG = 33;
- private final static int loopbackInputPacketsLONG = 34;
- private final static int loopbackOutputPacketsLONG = 35;
- private final static int inputPacketsLONG = 36;
- private final static int inputErrorsLONG = 37;
- private final static int outputPacketsLONG = 38;
- private final static int outputErrorsLONG = 39;
- private final static int collisionsLONG = 40;
- private final static int inputBytesLONG = 41;
- private final static int outputBytesLONG = 42;
- private final static int multicastInputPacketsLONG = 43;
- private final static int multicastOutputPacketsLONG = 44;
- private final static int broadcastInputPacketsLONG = 45;
- private final static int broadcastOutputPacketsLONG = 46;
- private final static int inputPacketsDiscardedLONG = 47;
- private final static int outputPacketsDiscardedLONG = 48;
-
- private final static int loadAverage1DOUBLE = 0;
- private final static int loadAverage15DOUBLE = 1;
- private final static int loadAverage5DOUBLE = 2;
-
- private final static StatisticsType myType;
-
- private static void checkOffset(String name, int offset) {
- int id = myType.nameToId(name);
- Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
- }
-
- /*
- "\n Segments ConnectionsEstablished ConnectionsActive"
- "\n ConnectionsPassive ConnectionFailures ConnectionsReset"
- "\n SegmentsReceived SegmentsSent SegmentsRetransmitted"
- "\n SentTcpBytes RetransmittedTcpBytes AcksSent DelayedAcksSent"
- "\n ControlSegmentsSent"
- "\n AcksReceived AckedBytes DuplicateAcks AcksForUnsentData "
- "\n ReceivedInorderBytes ReceivedOutOfOrderBytes ReceivedDuplicateBytes ReceivedPartialDuplicateBytes "
- "\n RetransmitTimeouts RetransmitTimeoutDrops"
- "\n KeepAliveTimeouts KeepAliveProbes KeepAliveDrops"
- "\n ListenQueueFull HalfOpenQueueFull HalfOpenDrops"
- "\n) ");
- sprintf(buff, "%d", typeCount);
- TcpTypeCount = typeCount;
- typeCount++;
- strcat(res, buff);
- }
-
- */
-
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- myType = f.createType("SolarisSystemStats",
- "Statistics on a Solaris machine.",
- new StatisticDescriptor[] {
- f.createIntGauge("allocatedSwap",
- "The number of megabytes of swap space have actually been written to. Swap space must be reserved before it can be allocated.",
- "megabytes"),
- f.createIntGauge("cpuActive",
- "The percentage of the total available time that has been used to execute user or system code.",
- "%"),
- f.createIntGauge("cpuIdle",
- "The percentage of the total available time that has been spent sleeping.",
- "%", true),
- f.createIntGauge("cpuIoWait",
- "The percentage of the total available time that has been spent waiting for disk io to complete.",
- "%"),
- f.createIntGauge("cpuSwapWait",
- "The percentage of the total available time that has been spent waiting for paging and swapping to complete.",
- "%"),
- f.createIntGauge("cpuSystem",
- "The percentage of the total available time that has been used to execute system (i.e. kernel) code.",
- "%"),
- f.createIntGauge("cpuUser",
- "The percentage of the total available time that has been used to execute user code.",
- "%"),
- f.createIntGauge("cpuWaiting",
- "The percentage of the total available time that has been spent waiting for io, paging, or swapping.",
- "%"),
- f.createIntGauge("cpus",
- "The number of online cpus on the local machine.",
- "items"),
- f.createIntGauge("freeMemory",
- "The number of megabytes of unused memory on the machine.",
- "megabytes", true),
- f.createIntGauge("physicalMemory",
- "The actual amount of total physical memory on the machine.",
- "megabytes", true),
- f.createIntGauge("processes",
- "The number of processes in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Each process represents the running of a program.",
- "processes"),
- f.createIntGauge("reservedSwap",
- "The number of megabytes of swap space reserved for allocation by a particular process.",
- "megabytes"),
- f.createIntCounter("schedulerRunCount",
- "The total number of times the system scheduler has put a thread in its run queue.",
- "operations", false),
- f.createIntCounter("schedulerSwapCount",
- "The total number of times the system scheduler has swapped out an idle process.",
- "operations", false),
- f.createIntCounter("schedulerWaitCount",
- "The total number of times the system scheduler has removed a thread from the run queue because it was waiting for a resource.",
- "operations", false),
- f.createIntGauge("unreservedSwap",
- "The number of megabytes of swap space that are free. If this value goes to zero new processes can no longer be created.",
- "megabytes", true),
- f.createIntGauge("unallocatedSwap",
- "The number of megabytes of swap space that have not been allocated.",
- "megabytes", true),
-
-
- f.createLongCounter("anonymousPagesFreed",
- "The total number pages that contain heap, stack, or other changeable data that have been removed from memory and added to the free list.",
- "pages"),
- f.createLongCounter("anonymousPagesPagedIn",
- "The total number pages that contain heap, stack, or other changeable data that have been allocated in memory and possibly copied from disk.",
- "pages", false),
- f.createLongCounter("anonymousPagesPagedOut",
- "The total number pages that contain heap, stack, or other changeable data that have been removed from memory and copied to disk.",
- "pages", false),
- f.createLongCounter("contextSwitches",
- "The total number of context switches from one thread to another on the computer. Thread switches can occur either inside of a single process or across processes. A thread switch may be caused either by one thread asking another for information, or by a thread being preempted by another, higher priority thread becoming ready to run.",
- "operations", false),
- f.createLongCounter("execPagesFreed",
- "The total number readonly pages that contain code or data that have been removed from memory and returned to the free list.",
- "pages"),
- f.createLongCounter("execPagesPagedIn",
- "The total number readonly pages that contain code or data that have been copied from disk to memory.",
- "pages", false),
- f.createLongCounter("execPagesPagedOut",
- "The total number readonly pages that contain code or data that have been removed from memory and will need to be paged in when used again.",
- "pages", false),
- f.createLongCounter("failedMutexEnters",
- "The total number of times a thread entering a mutex had to wait for the mutex to be unlocked.",
- "operations", false),
- f.createLongCounter("failedReaderLocks",
- "The total number of times readers failed to obtain a readers/writer locks on their first try. When this happens the reader has to wait for the current writer to release the lock.",
- "operations", false),
- f.createLongCounter("failedWriterLocks",
- "The total number of times writers failed to obtain a readers/writer locks on their first try. When this happens the writer has to wait for all the current readers or the single writer to release the lock.",
- "operations", false),
- f.createLongCounter("fileSystemPagesFreed",
- "The total number of pages, that contained the contents of a file due to the file being read from a file system, that have been removed from memory and put on the free list.",
- "pages"),
- f.createLongCounter("fileSystemPagesPagedIn",
- "The total number of pages that contain the contents of a file due to the file being read from a file system.",
- "pages", false),
- f.createLongCounter("fileSystemPagesPagedOut",
- "The total number of pages, that contained the contents of a file due to the file being read from a file system, that have been removed from memory and copied to disk.",
- "pages", false),
- f.createLongCounter("hatMinorFaults",
- "The total number of hat faults. You only get these on systems with software memory management units.",
- "operations", false),
- f.createLongCounter("interrupts",
- "The total number of interrupts that have occurred on the computer.",
- "operations", false),
- f.createLongCounter("involContextSwitches",
- "The total number of times a thread was forced to give up the cpu even though it was still ready to run.",
- "operations", false),
- f.createLongCounter("majorPageFaults",
- "The total number of times a page fault required disk io to get the page",
- "operations", false),
- f.createLongCounter("messageCount",
- "The total number of msgrcv() and msgsnd() system calls.",
- "messages"),
- f.createLongCounter("pageDaemonCycles",
- "The total number of revolutions of the page daemon's scan \"clock hand\".",
- "operations", false),
- f.createLongCounter("pageIns",
- "The total number of times pages have been brought into memory from disk by the operating system's memory manager.",
- "operations", false),
- f.createLongCounter("pageOuts",
- "The total number of times pages have been flushed from memory to disk by the operating system's memory manager.",
- "operations", false),
- f.createLongCounter("pagerRuns",
- "The total number of times the pager daemon has been scheduled to run.",
- "operations", false),
- f.createLongCounter("pagesPagedIn",
- "The total number of pages that have been brought into memory from disk by the operating system's memory manager.",
- "pages", false),
- f.createLongCounter("pagesPagedOut",
- "The total number of pages that have been flushed from memory to disk by the operating system's memory manager.",
- "pages", false),
- f.createLongCounter("pagesScanned",
- "The total number pages examined by the pageout daemon. When the amount of free memory gets below a certain size, the daemon start to look for inactive memory pages to steal from processes. So I high scan rate is a good indication of needing more memory.",
- "pages", false),
- f.createLongGauge("procsInIoWait",
- "The number of processes waiting for block I/O at this instant in time.",
- "processes"),
- f.createLongCounter("protectionFaults",
- "The total number of times memory has been accessed in a way that was not allowed. This results in a segementation violation and in most cases a core dump.",
- "operations", false),
- f.createLongCounter("semphoreOps",
- "The total number of semaphore operations.",
- "operations"),
- f.createLongCounter("softwareLockFaults",
- "The total number of faults caused by software locks held on memory pages.",
- "operations", false),
- f.createLongCounter("systemCalls",
- "The total number system calls.",
- "operations"),
- f.createLongCounter("systemMinorFaults",
- "The total number of minor page faults in kernel code. Minor page faults do not require disk access.",
- "operations", false),
- f.createLongCounter("threadCreates",
- "The total number of times a thread has been created.",
- "operations", false),
- f.createLongCounter("traps",
- "The total number of traps that have occurred on the computer.",
- "operations", false),
- f.createLongCounter("userMinorFaults",
- "The total number of minor page faults in non-kernel code. Minor page faults do not require disk access.",
- "operatations", false),
- f.createLongCounter("loopbackInputPackets",
- "The total number of input packets received over the loopback network adaptor.",
- "packets"),
- f.createLongCounter("loopbackOutputPackets",
- "The total number of output packets sent over the loopback network adaptor.",
- "packets"),
- f.createLongCounter("inputPackets",
- "packets received (Solaris kstat 'ipackets')",
- "packets"),
- f.createLongCounter("inputErrors",
- "input errors (Solaris kstat 'ierrors')",
- "errors", false),
- f.createLongCounter("outputPackets",
- "Solaris kstat 'opackets'",
- "packets"),
- f.createLongCounter("outputErrors",
- "output errors (Solaris kstat 'oerrors')",
- "errors", false),
- f.createLongCounter("collisions",
- "Solaris kstat 'collisions'",
- "collisions", false),
- f.createLongCounter("inputBytes",
- "octets received (Solaris kstat 'rbytes')",
- "bytes"),
- f.createLongCounter("outputBytes",
- "octats transmitted (Solaris kstat 'obytes')",
- "bytes"),
- f.createLongCounter("multicastInputPackets",
- "multicast received (Solaris kstat 'multircv')",
- "packets"),
- f.createLongCounter("multicastOutputPackets",
- "multicast requested to be sent (Solaris kstat 'multixmt')",
- "packets"),
- f.createLongCounter("broadcastInputPackets",
- "broadcast received (Solaris kstat 'brdcstrcv')",
- "packets"),
- f.createLongCounter("broadcastOutputPackets",
- "broadcast requested to be sent (Solaris kstat 'brdcstxmt')",
- "packets"),
- f.createLongCounter("inputPacketsDiscarded",
- "number receive packets discarded (Solaris kstat 'norcvbuf')",
- "packets"),
- f.createLongCounter("outputPacketsDiscarded",
- "packets that could not be sent up because the queue was flow controlled (Solaris kstat 'noxmtbuf')",
- "packets"),
-
-
- f.createDoubleGauge("loadAverage1",
- "The average number of threads ready to run over the last minute.",
- "threads"),
- f.createDoubleGauge("loadAverage15",
- "The average number of threads ready to run over the last fifteen minutes.",
- "threads"),
- f.createDoubleGauge("loadAverage5",
- "The average number of threads ready to run over the last five minutes.",
- "threads")
- });
- checkOffset("allocatedSwap", allocatedSwapINT);
- checkOffset("cpuActive", cpuActiveINT);
- checkOffset("cpuIdle", cpuIdleINT);
- checkOffset("cpuIoWait", cpuIoWaitINT);
- checkOffset("cpuSwapWait", cpuSwapWaitINT);
- checkOffset("cpuSystem", cpuSystemINT);
- checkOffset("cpuUser", cpuUserINT);
- checkOffset("cpuWaiting", cpuWaitingINT);
- checkOffset("cpus", cpusINT);
- checkOffset("freeMemory", freeMemoryINT);
- checkOffset("physicalMemory", physicalMemoryINT);
- checkOffset("processes", processesINT);
- checkOffset("reservedSwap", reservedSwapINT);
- checkOffset("schedulerRunCount", schedulerRunCountINT);
- checkOffset("schedulerSwapCount", schedulerSwapCountINT);
- checkOffset("schedulerWaitCount", schedulerWaitCountINT);
- checkOffset("unreservedSwap", unreservedSwapINT);
- checkOffset("unallocatedSwap", unallocatedSwapINT);
-
- checkOffset("anonymousPagesFreed", anonymousPagesFreedLONG);
- checkOffset("anonymousPagesPagedIn", anonymousPagesPagedInLONG);
- checkOffset("anonymousPagesPagedOut", anonymousPagesPagedOutLONG);
- checkOffset("contextSwitches", contextSwitchesLONG);
- checkOffset("execPagesFreed", execPagesFreedLONG);
- checkOffset("execPagesPagedIn", execPagesPagedInLONG);
- checkOffset("execPagesPagedOut", execPagesPagedOutLONG);
- checkOffset("failedMutexEnters", failedMutexEntersLONG);
- checkOffset("failedReaderLocks", failedReaderLocksLONG);
- checkOffset("failedWriterLocks", failedWriterLocksLONG);
- checkOffset("fileSystemPagesFreed", fileSystemPagesFreedLONG);
- checkOffset("fileSystemPagesPagedIn", fileSystemPagesPagedInLONG);
- checkOffset("fileSystemPagesPagedOut", fileSystemPagesPagedOutLONG);
- checkOffset("hatMinorFaults", hatMinorFaultsLONG);
- checkOffset("interrupts", interruptsLONG);
- checkOffset("involContextSwitches", involContextSwitchesLONG);
- checkOffset("majorPageFaults", majorPageFaultsLONG);
- checkOffset("messageCount", messageCountLONG);
- checkOffset("pageDaemonCycles", pageDaemonCyclesLONG);
- checkOffset("pageIns", pageInsLONG);
- checkOffset("pageOuts", pageOutsLONG);
- checkOffset("pagerRuns", pagerRunsLONG);
- checkOffset("pagesPagedIn", pagesPagedInLONG);
- checkOffset("pagesPagedOut", pagesPagedOutLONG);
- checkOffset("pagesScanned", pagesScannedLONG);
- checkOffset("procsInIoWait", procsInIoWaitLONG);
- checkOffset("protectionFaults", protectionFaultsLONG);
- checkOffset("semphoreOps", semphoreOpsLONG);
- checkOffset("softwareLockFaults", softwareLockFaultsLONG);
- checkOffset("systemCalls", systemCallsLONG);
- checkOffset("systemMinorFaults", systemMinorFaultsLONG);
- checkOffset("threadCreates", threadCreatesLONG);
- checkOffset("traps", trapsLONG);
- checkOffset("userMinorFaults", userMinorFaultsLONG);
- checkOffset("loopbackInputPackets", loopbackInputPacketsLONG);
- checkOffset("loopbackOutputPackets", loopbackOutputPacketsLONG);
- checkOffset("inputPackets", inputPacketsLONG);
- checkOffset("inputErrors", inputErrorsLONG);
- checkOffset("outputPackets", outputPacketsLONG);
- checkOffset("outputErrors", outputErrorsLONG);
- checkOffset("collisions", collisionsLONG);
- checkOffset("inputBytes", inputBytesLONG);
- checkOffset("outputBytes", outputBytesLONG);
- checkOffset("multicastInputPackets", multicastInputPacketsLONG);
- checkOffset("multicastOutputPackets", multicastOutputPacketsLONG);
- checkOffset("broadcastInputPackets", broadcastInputPacketsLONG);
- checkOffset("broadcastOutputPackets", broadcastOutputPacketsLONG);
- checkOffset("inputPacketsDiscarded", inputPacketsDiscardedLONG);
- checkOffset("outputPacketsDiscarded", outputPacketsDiscardedLONG);
-
- checkOffset("loadAverage1", loadAverage1DOUBLE);
- checkOffset("loadAverage15", loadAverage15DOUBLE);
- checkOffset("loadAverage5", loadAverage5DOUBLE);
- }
-
- private SolarisSystemStats() {
- // no instances allowed
- }
- public static StatisticsType getType() {
- return myType;
- }
-}
[17/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveWriter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveWriter.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveWriter.java
deleted file mode 100644
index fcf645d..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveWriter.java
+++ /dev/null
@@ -1,733 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.GemFireIOException;
-import com.gemstone.gemfire.InternalGemFireException;
-import com.gemstone.gemfire.StatisticDescriptor;
-import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
-import com.gemstone.gemfire.internal.statistics.ResourceInstance;
-import com.gemstone.gemfire.internal.statistics.ResourceType;
-import com.gemstone.gemfire.internal.statistics.SampleHandler;
-import com.gemstone.gemfire.internal.statistics.StatArchiveDescriptor;
-import org.apache.logging.log4j.Logger;
-
-import java.io.*;
-import java.net.UnknownHostException;
-import java.util.*;
-import java.util.zip.GZIPOutputStream;
-
-/**
- * StatArchiveWriter provides APIs to write statistic snapshots to an archive
- * file.
- *
- */
-public class StatArchiveWriter implements StatArchiveFormat, SampleHandler {
-
- private static final Logger logger = LogService.getLogger();
-
- private static volatile String traceStatisticsName = null;
- private static volatile String traceStatisticsTypeName = null;
- private static volatile int traceResourceInstId = -1;
-
- private final boolean trace = Boolean.getBoolean(DistributionConfig.GEMFIRE_PREFIX + "stats.debug.traceStatArchiveWriter");
-
- private final Set<ResourceInstance> sampleWrittenForResources =
- new HashSet<ResourceInstance>();
- private final Set<ResourceInstance> addedResources =
- new HashSet<ResourceInstance>();
- private final StatArchiveDescriptor archiveDescriptor;
- private long initialDate;
- private final OutputStream outStream;
- private final MyDataOutputStream dataOut;
- private final OutputStream traceOutStream;
- private final PrintStream traceDataOut;
- private long previousMillisTimeStamp;
- private int sampleCount;
-
- /**
- * Opens a StatArchiveWriter that will archive to the specified file.
- * @throws GemFireIOException if <code>archiveName</code> can not be written to
- */
- public StatArchiveWriter(StatArchiveDescriptor archiveDescriptor) {
- this.archiveDescriptor = archiveDescriptor;
-
- if (archiveDescriptor.getArchiveName().endsWith(".gz")) {
- try {
- this.outStream = new GZIPOutputStream(new FileOutputStream(archiveDescriptor.getArchiveName()), 32768);
- } catch (IOException ex) {
- throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_COULD_NOT_OPEN_0.toLocalizedString(archiveDescriptor.getArchiveName()), ex);
- }
- } else {
- try {
- this.outStream = new BufferedOutputStream(new FileOutputStream(archiveDescriptor.getArchiveName()), 32768);
- } catch (IOException ex) {
- throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_COULD_NOT_OPEN_0.toLocalizedString(archiveDescriptor.getArchiveName()), ex);
- }
- }
-
- this.dataOut = new MyDataOutputStream(this.outStream);
-
- if (this.trace) {
- String traceFileName = archiveDescriptor.getArchiveName() + ".trace";
- try {
- this.traceOutStream = new BufferedOutputStream(new FileOutputStream(traceFileName), 32768);
- } catch (IOException ex) {
- throw new GemFireIOException("Could not open " + traceFileName, ex);
- }
- this.traceDataOut = new PrintStream(this.traceOutStream);
- } else {
- this.traceOutStream = null;
- this.traceDataOut = null;
- }
- }
-
- public String getArchiveName() {
- return this.archiveDescriptor.getArchiveName();
- }
-
- public void initialize(long nanosTimeStamp) {
- this.previousMillisTimeStamp = initPreviousMillisTimeStamp(nanosTimeStamp);
- this.initialDate = initInitialDate();
- writeHeader(this.initialDate, this.archiveDescriptor);
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder(getClass().getName());
- sb.append("@").append(System.identityHashCode(this)).append("{");
- sb.append("archiveName=").append(this.archiveDescriptor.getArchiveName());
- sb.append("productDescription=").append(this.archiveDescriptor.getProductDescription());
- sb.append("systemDirectoryPath=").append(this.archiveDescriptor.getSystemDirectoryPath());
- sb.append("systemId=").append(this.archiveDescriptor.getSystemId());
- sb.append("systemStartTime=").append(this.archiveDescriptor.getSystemStartTime());
- sb.append("previousMillisTimeStamp=").append(this.previousMillisTimeStamp);
- sb.append("initialDate=").append(this.initialDate);
- return sb.toString();
- }
-
- /**
- * Closes the statArchiver by flushing its data to disk a closing its output stream.
- * @throws GemFireIOException if the archive file could not be closed.
- */
- public final void close() {
- try {
- this.dataOut.flush();
- if (this.trace) {
- this.traceDataOut.flush();
- }
- } catch (IOException ignore) {
- }
- try {
- outStream.close();
- if (this.trace) {
- this.traceOutStream.close();
- }
- } catch (IOException ex) {
- throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_COULD_NOT_CLOSE_STATARCHIVER_FILE.toLocalizedString(), ex);
- }
- if (getSampleCount() == 0) {
- // If we are closing an empty file go ahead and delete it.
- // This prevents the fix for 46917 from leaving a bunch of
- // empty gfs files around.
- deleteFileIfPossible(new File(getArchiveName()));
- }
- }
-
- @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification="Best effort attempt to delete a GFS file without any samples.")
- private static void deleteFileIfPossible(File file) {
- file.delete();
- }
-
- /**
- * Returns the number of bytes written so far to this archive.
- * This does not take compression into account.
- */
- public final long bytesWritten() {
- return this.dataOut.getBytesWritten();
- }
-
- protected long initPreviousMillisTimeStamp(long nanosTimeStamp) {
- return NanoTimer.nanosToMillis(nanosTimeStamp);
- }
-
- protected long initInitialDate() {
- return System.currentTimeMillis();
- }
-
- protected TimeZone getTimeZone() {
- return Calendar.getInstance().getTimeZone();
- }
-
- protected String getOSInfo() {
- return System.getProperty("os.name") + " " + System.getProperty("os.version");
- }
-
- protected String getMachineInfo() {
- String machineInfo = System.getProperty("os.arch");
- try {
- String hostName = SocketCreator.getHostName(SocketCreator.getLocalHost());
- machineInfo += " " + hostName;
- } catch (UnknownHostException ignore) {
- }
- return machineInfo;
- }
-
- private void writeHeader(long initialDate, StatArchiveDescriptor archiveDescriptor) {
- if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeHeader initialDate={} archiveDescriptor={}", initialDate, archiveDescriptor);
- }
- try {
- this.dataOut.writeByte(HEADER_TOKEN);
- this.dataOut.writeByte(ARCHIVE_VERSION);
- this.dataOut.writeLong(initialDate);
- this.dataOut.writeLong(archiveDescriptor.getSystemId());
- this.dataOut.writeLong(archiveDescriptor.getSystemStartTime());
- TimeZone timeZone = getTimeZone();
- this.dataOut.writeInt(timeZone.getRawOffset());
- this.dataOut.writeUTF(timeZone.getID());
- this.dataOut.writeUTF(archiveDescriptor.getSystemDirectoryPath());
- this.dataOut.writeUTF(archiveDescriptor.getProductDescription());
- this.dataOut.writeUTF(getOSInfo());
- this.dataOut.writeUTF(getMachineInfo());
-
- if (this.trace) {
- this.traceDataOut.println("writeHeader traceStatisticsName: " + traceStatisticsName);
- this.traceDataOut.println("writeHeader traceStatisticsTypeName: " + traceStatisticsTypeName);
- this.traceDataOut.println("writeHeader#writeByte HEADER_TOKEN: " + HEADER_TOKEN);
- this.traceDataOut.println("writeHeader#writeByte ARCHIVE_VERSION: " + ARCHIVE_VERSION);
- this.traceDataOut.println("writeHeader#writeLong initialDate: " + initialDate);
- this.traceDataOut.println("writeHeader#writeLong archiveDescriptor.getSystemId(): " + archiveDescriptor.getSystemId());
- this.traceDataOut.println("writeHeader#writeLong archiveDescriptor.getSystemStartTime(): " + archiveDescriptor.getSystemStartTime());
- this.traceDataOut.println("writeHeader#writeInt timeZone.getRawOffset(): " + timeZone.getRawOffset());
- this.traceDataOut.println("writeHeader#writeUTF timeZone.getID(): " + timeZone.getID());
- this.traceDataOut.println("writeHeader#writeUTF archiveDescriptor.getSystemDirectoryPath(): " + archiveDescriptor.getSystemDirectoryPath());
- this.traceDataOut.println("writeHeader#writeUTF archiveDescriptor.getProductDescription(): " + archiveDescriptor.getProductDescription());
- this.traceDataOut.println("writeHeader#writeUTF getOSInfo(): " + getOSInfo());
- this.traceDataOut.println("writeHeader#writeUTF getMachineInfo(): " + getMachineInfo());
- }
- } catch (IOException ex) {
- throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_HEADER_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
- }
- }
-
- public void allocatedResourceType(ResourceType resourceType) {
- if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#allocatedResourceType resourceType={}", resourceType);
- }
- if (resourceType.getStatisticDescriptors().length >= ILLEGAL_STAT_OFFSET) {
- throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_COULD_NOT_ARCHIVE_TYPE_0_BECAUSE_IT_HAD_MORE_THAN_1_STATISTICS.toLocalizedString(new Object[] {resourceType.getStatisticsType().getName(), Integer.valueOf(ILLEGAL_STAT_OFFSET-1)}));
- }
- // write the type to the archive
- try {
- this.dataOut.writeByte(RESOURCE_TYPE_TOKEN);
- this.dataOut.writeInt(resourceType.getId());
- this.dataOut.writeUTF(resourceType.getStatisticsType().getName());
- this.dataOut.writeUTF(resourceType.getStatisticsType().getDescription());
- StatisticDescriptor[] stats = resourceType.getStatisticDescriptors();
- this.dataOut.writeShort(stats.length);
- if (this.trace && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(resourceType.getStatisticsType().getName()))) {
- this.traceDataOut.println("allocatedResourceType#writeByte RESOURCE_TYPE_TOKEN: " + RESOURCE_TYPE_TOKEN);
- this.traceDataOut.println("allocatedResourceType#writeInt resourceType.getId(): " + resourceType.getId());
- this.traceDataOut.println("allocatedResourceType#writeUTF resourceType.getStatisticsType().getName(): " + resourceType.getStatisticsType().getName());
- this.traceDataOut.println("allocatedResourceType#writeUTF resourceType.getStatisticsType().getDescription(): " + resourceType.getStatisticsType().getDescription());
- this.traceDataOut.println("allocatedResourceType#writeShort stats.length: " + stats.length);
- }
- for (int i=0; i < stats.length; i++) {
- this.dataOut.writeUTF(stats[i].getName());
- this.dataOut.writeByte(((StatisticDescriptorImpl)stats[i]).getTypeCode());
- this.dataOut.writeBoolean(stats[i].isCounter());
- this.dataOut.writeBoolean(stats[i].isLargerBetter());
- this.dataOut.writeUTF(stats[i].getUnit());
- this.dataOut.writeUTF(stats[i].getDescription());
- if (this.trace && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(resourceType.getStatisticsType().getName()))) {
- this.traceDataOut.println("allocatedResourceType#writeUTF stats[i].getName(): " + stats[i].getName());
- this.traceDataOut.println("allocatedResourceType#writeByte ((StatisticDescriptorImpl)stats[i]).getTypeCode(): " + ((StatisticDescriptorImpl)stats[i]).getTypeCode());
- this.traceDataOut.println("allocatedResourceType#writeBoolean stats[i].isCounter(): " + stats[i].isCounter());
- this.traceDataOut.println("allocatedResourceType#writeBoolean stats[i].isLargerBetter(): " + stats[i].isLargerBetter());
- this.traceDataOut.println("allocatedResourceType#writeUTF stats[i].getUnit(): " + stats[i].getUnit());
- this.traceDataOut.println("allocatedResourceType#writeUTF stats[i].getDescription(): " + stats[i].getDescription());
- }
- }
- } catch (IOException ex) {
- throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_NEW_RESOURCE_TYPE_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
- }
- }
-
- @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", justification="This is only for debugging and there is never more than one instance being traced because there is only one stat sampler.")
- public void allocatedResourceInstance(ResourceInstance statResource) {
- if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#allocatedResourceInstance statResource={}", statResource);
- }
- if (statResource.getResourceType().getStatisticDescriptors().length >= ILLEGAL_STAT_OFFSET) {
- throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_COULD_NOT_ARCHIVE_TYPE_0_BECAUSE_IT_HAD_MORE_THAN_1_STATISTICS.toLocalizedString(new Object[] {statResource.getResourceType().getStatisticsType().getName(), Integer.valueOf(ILLEGAL_STAT_OFFSET-1)}));
- }
- if (statResource.getStatistics().isClosed()) {
- return;
- }
- this.addedResources.add(statResource);
- try {
- this.dataOut.writeByte(RESOURCE_INSTANCE_CREATE_TOKEN);
- this.dataOut.writeInt(statResource.getId());
- this.dataOut.writeUTF(statResource.getStatistics().getTextId());
- this.dataOut.writeLong(statResource.getStatistics().getNumericId());
- this.dataOut.writeInt(statResource.getResourceType().getId());
- if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(statResource.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(statResource.getResourceType().getStatisticsType().getName()))) {
- traceResourceInstId = statResource.getId();
- this.traceDataOut.println("writeHeader traceResourceInstId: " + traceResourceInstId);
- this.traceDataOut.println("allocatedResourceInstance#writeByte RESOURCE_INSTANCE_CREATE_TOKEN: " + RESOURCE_INSTANCE_CREATE_TOKEN);
- this.traceDataOut.println("allocatedResourceInstance#writeInt statResource.getId(): " + statResource.getId());
- this.traceDataOut.println("allocatedResourceInstance#writeUTF statResource.getStatistics().getTextId(): " + statResource.getStatistics().getTextId());
- this.traceDataOut.println("allocatedResourceInstance#writeLong statResource.getStatistics().getNumericId(): " + statResource.getStatistics().getNumericId());
- this.traceDataOut.println("allocatedResourceInstance#writeInt statResource.getResourceType().getId(): " + statResource.getResourceType().getId());
- }
- } catch (IOException ex) {
- throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_NEW_RESOURCE_INSTANCE_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
- }
- }
-
- public void destroyedResourceInstance(ResourceInstance resourceInstance) {
- if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#destroyedResourceInstance resourceInstance={}", resourceInstance);
- }
- if (!this.addedResources.contains(resourceInstance)) { // Fix for bug #45377
- return;
- }
-
- this.sampleWrittenForResources.remove(resourceInstance);
- this.addedResources.remove(resourceInstance);
-
- try {
- this.dataOut.writeByte(RESOURCE_INSTANCE_DELETE_TOKEN);
- this.dataOut.writeInt(resourceInstance.getId());
- if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(resourceInstance.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(resourceInstance.getResourceType().getStatisticsType().getName()))) {
- this.traceDataOut.println("destroyedResourceInstance#writeByte RESOURCE_INSTANCE_DELETE_TOKEN: " + RESOURCE_INSTANCE_DELETE_TOKEN);
- this.traceDataOut.println("destroyedResourceInstance#writeInt resourceInstance.getId(): " + resourceInstance.getId());
- }
- } catch (IOException ex) {
- throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_DELETE_RESOURCE_INSTANCE_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
- }
- }
-
- static long calcDelta(long previousMillis, long currentMillis) {
- long delta = currentMillis - previousMillis;
- if (delta <= 0) {
- throw new IllegalArgumentException("Sample timestamp must be greater than previous timestamp (millisTimeStamp is " + currentMillis + ", previousMillis is " + previousMillis + " and delta is " + delta + ").");
- }
- return delta;
- }
-
- private void writeTimeStamp(long nanosTimeStamp) throws IOException {
- final long millisTimeStamp = NanoTimer.nanosToMillis(nanosTimeStamp);
- final long delta = calcDelta(this.previousMillisTimeStamp, millisTimeStamp);
- if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeTimeStamp millisTimeStamp={}, delta={}", millisTimeStamp, (int)delta);
- }
- if (delta > MAX_SHORT_TIMESTAMP) {
- if (delta > Integer.MAX_VALUE) {
- throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_TIMESTAMP_DELTA_0_WAS_GREATER_THAN_1.toLocalizedString(new Object[] {Long.valueOf(delta), Integer.valueOf(Integer.MAX_VALUE)}));
- }
- this.dataOut.writeShort(INT_TIMESTAMP_TOKEN);
- this.dataOut.writeInt((int)delta);
- if (this.trace) {
- this.traceDataOut.println("writeTimeStamp#writeShort INT_TIMESTAMP_TOKEN: " + INT_TIMESTAMP_TOKEN);
- this.traceDataOut.println("writeTimeStamp#writeInt (int)delta: " + (int)delta);
- }
- } else {
- this.dataOut.writeShort((int)delta);
- if (this.trace) {
- this.traceDataOut.println("writeTimeStamp#writeShort (int)delta: " + (int)delta);
- }
- }
- this.previousMillisTimeStamp = millisTimeStamp;
- }
-
- /**
- * Writes the resource instance id to the <code>dataOut</code> stream.
- */
- private void writeResourceInst(int instId) throws IOException {
- if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeResourceInst instId={}", instId);
- }
- if (instId > MAX_BYTE_RESOURCE_INST_ID) {
- if (instId > MAX_SHORT_RESOURCE_INST_ID) {
- this.dataOut.writeByte(INT_RESOURCE_INST_ID_TOKEN);
- this.dataOut.writeInt(instId);
- if (this.trace && (traceResourceInstId == -1 || traceResourceInstId == instId)) {
- this.traceDataOut.println("writeResourceInst#writeByte INT_RESOURCE_INST_ID_TOKEN: " + INT_RESOURCE_INST_ID_TOKEN);
- if (instId == ILLEGAL_RESOURCE_INST_ID) {
- this.traceDataOut.println("writeResourceInst#writeInt ILLEGAL_RESOURCE_INST_ID: " + ILLEGAL_RESOURCE_INST_ID);
- } else {
- this.traceDataOut.println("writeResourceInst#writeInt instId: " + instId);
- }
- }
- } else {
- this.dataOut.writeByte(SHORT_RESOURCE_INST_ID_TOKEN);
- this.dataOut.writeShort(instId);
- if (this.trace && (traceResourceInstId == -1 || traceResourceInstId == instId)) {
- this.traceDataOut.println("writeResourceInst#writeByte SHORT_RESOURCE_INST_ID_TOKEN: " + SHORT_RESOURCE_INST_ID_TOKEN);
- if (instId == ILLEGAL_RESOURCE_INST_ID) {
- this.traceDataOut.println("writeResourceInst#writeShort ILLEGAL_RESOURCE_INST_ID: " + ILLEGAL_RESOURCE_INST_ID);
- } else {
- this.traceDataOut.println("writeResourceInst#writeShort instId: " + instId);
- }
- }
- }
- } else {
- this.dataOut.writeByte(instId);
- if (this.trace && (traceResourceInstId == -1 || traceResourceInstId == instId)) {
- if (instId == ILLEGAL_RESOURCE_INST_ID) {
- this.traceDataOut.println("writeResourceInst#writeByte ILLEGAL_RESOURCE_INST_ID: " + ILLEGAL_RESOURCE_INST_ID);
- } else {
- this.traceDataOut.println("writeResourceInst#writeByte instId: " + instId);
- }
- }
- }
- }
-
- public void sampled(long nanosTimeStamp, List<ResourceInstance> resourceInstances) {
- if (logger.isTraceEnabled(LogMarker.STATISTICS)) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#sampled nanosTimeStamp={}, resourceInstances={}", nanosTimeStamp, resourceInstances);
- }
- try {
- this.dataOut.writeByte(SAMPLE_TOKEN);
- if (this.trace) {
- this.traceDataOut.println("sampled#writeByte SAMPLE_TOKEN: " + SAMPLE_TOKEN);
- }
- writeTimeStamp(nanosTimeStamp);
- for (ResourceInstance ri : resourceInstances) {
- writeSample(ri);
- }
- writeResourceInst(ILLEGAL_RESOURCE_INST_ID);
- this.dataOut.flush();
- if (this.trace) {
- this.traceDataOut.flush();
- }
- } catch (IOException ex) {
- throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_FAILED_WRITING_SAMPLE_TO_STATISTIC_ARCHIVE.toLocalizedString(), ex);
- }
- this.sampleCount++; // only inc after sample done w/o an exception thrown
- }
-
- public int getSampleCount() {
- return this.sampleCount;
- }
-
- private void writeSample(ResourceInstance ri) throws IOException {
- final boolean isDebugEnabled_STATISTICS = logger.isTraceEnabled(LogMarker.STATISTICS);
- if (isDebugEnabled_STATISTICS) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeSample ri={}", ri);
- }
- if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(ri.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(ri.getResourceType().getStatisticsType().getName()))) {
- this.traceDataOut.println("writeSample#writeSample for ri=" + ri);
- }
- if (ri.getStatistics().isClosed()) {
- return;
- }
- StatisticDescriptor[] stats = ri.getResourceType().getStatisticDescriptors();
- if (stats.length > 254) {
- throw new Error("StatisticsType " + ri.getResourceType().getStatisticsType().getName() + " has too many stats: " + stats.length);
- }
- boolean wroteInstId = false;
- boolean checkForChange = true;
-
- if (!this.sampleWrittenForResources.contains(ri)) {
- // first time for this instance so all values need to be written
- checkForChange = false;
- this.sampleWrittenForResources.add(ri);
- }
-
- long[] previousStatValues = ri.getPreviousStatValues();
- if (isDebugEnabled_STATISTICS) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeSample checkForChange={}, previousStatValues={}, stats.length={}",
- checkForChange, Arrays.toString(previousStatValues), stats.length);
- }
- if (previousStatValues == null) {
- previousStatValues = new long[stats.length];
- ri.setPreviousStatValues(previousStatValues);
- }
-
- int statsWritten = 0;
- try {
- for (int i=0; i < stats.length; i++) {
- long value = ri.getLatestStatValues()[i];
- if (!checkForChange || value != previousStatValues[i]) {
- long delta = checkForChange ? value - previousStatValues[i] : value;
- if (!wroteInstId) {
- wroteInstId = true;
- writeResourceInst(ri.getId());
- }
- this.dataOut.writeByte(i);
- if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(ri.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(ri.getResourceType().getStatisticsType().getName()))) {
- this.traceDataOut.println("writeSample#writeByte i: " + i);
- }
- if (isDebugEnabled_STATISTICS) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeStatValue stats[{}]={}, delta={}", i, stats[i], delta);
- }
- writeStatValue(stats[i], delta, this.dataOut);
- if (this.trace && (traceStatisticsName == null || traceStatisticsName.equals(ri.getStatistics().getTextId())) && (traceStatisticsTypeName == null || traceStatisticsTypeName.equals(ri.getResourceType().getStatisticsType().getName()))) {
- byte typeCode = ((StatisticDescriptorImpl)stats[i]).getTypeCode();
- switch(typeCode) {
- case BYTE_CODE:
- this.traceDataOut.println("writeStatValue#writeByte " + typeCodeToString(typeCode) + " delta: " + delta);
- break;
- case SHORT_CODE:
- this.traceDataOut.println("writeStatValue#writeShort" + typeCodeToString(typeCode) + " delta: " + delta);
- break;
- case INT_CODE:
- case FLOAT_CODE:
- case LONG_CODE:
- case DOUBLE_CODE:
- this.traceDataOut.println("writeStatValue#writeCompactValue " + typeCodeToString(typeCode) + " delta: " + delta);
- break;
- default:
- }
- }
- }
- }
- } catch (IllegalStateException closedEx) {
- // resource was closed causing getStatValue to throw this exception
- }
-
- if (wroteInstId) {
- this.dataOut.writeByte(ILLEGAL_STAT_OFFSET);
- if (this.trace && (traceStatisticsName == null
- || traceStatisticsName.equals(ri.getStatistics().getTextId()))
- && (traceStatisticsTypeName == null
- || traceStatisticsTypeName.equals(ri.getResourceType().getStatisticsType().getName()))) {
- this.traceDataOut.println("writeSample#writeByte ILLEGAL_STAT_OFFSET: " + ILLEGAL_STAT_OFFSET);
- }
- }
- if (isDebugEnabled_STATISTICS) {
- logger.trace(LogMarker.STATISTICS, "StatArchiveWriter#writeSample statsWritten={}", statsWritten);
- }
- }
-
- public static void writeCompactValue(long v, DataOutput dataOut) throws IOException {
- if (v <= MAX_1BYTE_COMPACT_VALUE && v >= MIN_1BYTE_COMPACT_VALUE) {
- dataOut.writeByte((int)v);
- } else if (v <= MAX_2BYTE_COMPACT_VALUE && v >= MIN_2BYTE_COMPACT_VALUE) {
- dataOut.writeByte(COMPACT_VALUE_2_TOKEN);
- dataOut.writeShort((int)v);
- } else {
- byte[] buffer = new byte[8];
- int idx = 0;
- long originalValue = v;
- if (v < 0) {
- while (v != -1 && v != 0) {
- buffer[idx++] = (byte)(v & 0xFF);
- v >>= 8;
- }
- // On windows v goes to zero somtimes; seems like a bug
- if (v == 0) {
- // when this happens we end up with a bunch of -1 bytes
- // so strip off the high order ones
- while (buffer[idx-1] == -1) {
- idx--;
- }
- // System.out.print("DEBUG: originalValue=" + originalValue);
- // for (int dbx=0; dbx<idx; dbx++) {
- // System.out.print(" " + buffer[dbx]);
- // }
- // System.out.println();
- }
- if ((buffer[idx-1] & 0x80) == 0) {
- /* If the most significant byte does not have its high order bit set
- * then add a -1 byte so we know this is a negative number
- */
- buffer[idx++] = -1;
- }
- } else {
- while (v != 0) {
- buffer[idx++] = (byte)(v & 0xFF);
- v >>= 8;
- }
- if ((buffer[idx-1] & 0x80) != 0) {
- /* If the most significant byte has its high order bit set
- * then add a zero byte so we know this is a positive number
- */
- buffer[idx++] = 0;
- }
- }
- if (idx <= 2) {
- throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_EXPECTED_IDX_TO_BE_GREATER_THAN_2_IT_WAS_0_FOR_THE_VALUE_1.toLocalizedString(new Object[] {Integer.valueOf(idx), Long.valueOf(originalValue)}));
- }
- int token = COMPACT_VALUE_2_TOKEN + (idx - 2);
- dataOut.writeByte(token);
- for (int i=idx-1; i >= 0; i--) {
- dataOut.writeByte(buffer[i]);
- }
- }
- }
-
- public static long readCompactValue(DataInput dataIn) throws IOException {
- long v = dataIn.readByte();
- boolean dump = false;
- if (dump) {
- System.out.print("compactValue(byte1)=" + v);
- }
- if (v < MIN_1BYTE_COMPACT_VALUE) {
- if (v == COMPACT_VALUE_2_TOKEN) {
- v = dataIn.readShort();
- if (dump) {
- System.out.print("compactValue(short)=" + v);
- }
- } else {
- int bytesToRead = ((byte)v - COMPACT_VALUE_2_TOKEN) + 2;
- v = dataIn.readByte(); // note the first byte will be a signed byte.
- if (dump) {
- System.out.print("compactValue(" + bytesToRead + ")=" + v);
- }
- bytesToRead--;
- while (bytesToRead > 0) {
- v <<= 8;
- v |= dataIn.readUnsignedByte();
- bytesToRead--;
- }
- }
- }
- return v;
- }
-
- protected static void writeStatValue(StatisticDescriptor f, long v, DataOutput dataOut) throws IOException {
- byte typeCode = ((StatisticDescriptorImpl)f).getTypeCode();
- writeStatValue(typeCode, v, dataOut);
- }
-
- public static void writeStatValue(byte typeCode, long v, DataOutput dataOut) throws IOException {
- switch(typeCode) {
- case BYTE_CODE:
- dataOut.writeByte((int)v);
- break;
- case SHORT_CODE:
- dataOut.writeShort((int)v);
- break;
- case INT_CODE:
- case FLOAT_CODE:
- case LONG_CODE:
- case DOUBLE_CODE:
- writeCompactValue(v, dataOut);
- break;
- default:
- throw new InternalGemFireException(LocalizedStrings.StatArchiveWriter_UNEXPECTED_TYPE_CODE_0.toLocalizedString(Byte.valueOf(typeCode)));
- }
- }
-
- protected static void setTraceFilter(String traceStatisticsName, String traceStatisticsTypeName) {
- StatArchiveWriter.traceStatisticsName = traceStatisticsName;
- StatArchiveWriter.traceStatisticsTypeName = traceStatisticsTypeName;
- StatArchiveWriter.traceResourceInstId = -1;
- }
-
- protected static void clearTraceFilter() {
- StatArchiveWriter.traceStatisticsName = null;
- StatArchiveWriter.traceStatisticsTypeName = null;
- StatArchiveWriter.traceResourceInstId = -1;
- }
-
- private static String typeCodeToString(byte typeCode) {
- switch(typeCode) {
- case BYTE_CODE:
- return "BYTE_CODE";
- case SHORT_CODE:
- return "SHORT_CODE";
- case INT_CODE:
- return "INT_CODE";
- case FLOAT_CODE:
- return "FLOAT_CODE";
- case LONG_CODE:
- return "LONG_CODE";
- case DOUBLE_CODE:
- return "DOUBLE_CODE";
- default:
- return "unknown typeCode " + typeCode;
- }
- }
-
- private static class MyDataOutputStream implements DataOutput {
- private long bytesWritten = 0;
- private final DataOutputStream dataOut;
-
- public MyDataOutputStream(OutputStream out) {
- this.dataOut = new DataOutputStream(out);
- }
-
- public final long getBytesWritten() {
- return this.bytesWritten;
- }
- public final void flush() throws IOException {
- this.dataOut.flush();
- }
- @SuppressWarnings("unused")
- public final void close() throws IOException {
- this.dataOut.close();
- }
-
- public final void write(int b) throws IOException {
- throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
- }
- public final void write(byte[] b, int off, int len) throws IOException {
- throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
- }
- public final void write(byte[] b) throws IOException {
- throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
- }
- public final void writeBytes(String v) throws IOException {
- throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
- }
- public final void writeChar(int v) throws IOException {
- throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
- }
- public final void writeChars(String v) throws IOException {
- throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
- }
- public final void writeDouble(double v) throws IOException {
- throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
- }
- public final void writeFloat(float v) throws IOException {
- throw new RuntimeException(LocalizedStrings.StatArchiveWriter_METHOD_UNIMPLEMENTED.toLocalizedString());
- }
-
- public final void writeBoolean(boolean v) throws IOException {
- this.dataOut.writeBoolean(v);
- this.bytesWritten += 1;
- }
- public final void writeByte(int v) throws IOException {
- this.dataOut.writeByte(v);
- this.bytesWritten += 1;
- }
- public final void writeShort(int v) throws IOException {
- this.dataOut.writeShort(v);
- this.bytesWritten += 2;
- }
- public final void writeInt(int v) throws IOException {
- this.dataOut.writeInt(v);
- this.bytesWritten += 4;
- }
- public final void writeLong(long v) throws IOException {
- this.dataOut.writeLong(v);
- this.bytesWritten += 8;
- }
- public final void writeUTF(String v) throws IOException {
- this.dataOut.writeUTF(v);
- this.bytesWritten += v.length() + 2; // this is the minimum. The max is v.size()*3 +2
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatSamplerStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatSamplerStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatSamplerStats.java
deleted file mode 100644
index c3d556f..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatSamplerStats.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * Statistics related to the statistic sampler.
- */
-public class StatSamplerStats {
- public final static String SAMPLE_COUNT = "sampleCount"; // int
- public final static String SAMPLE_TIME = "sampleTime"; // long
- public final static String DELAY_DURATION = "delayDuration"; // int
- public final static String STAT_RESOURCES = "statResources"; // int
- public final static String JVM_PAUSES = "jvmPauses"; // int
- public final static String SAMPLE_CALLBACKS = "sampleCallbacks"; // int
- public final static String SAMPLE_CALLBACK_ERRORS = "sampleCallbackErrors"; // int
- public final static String SAMPLE_CALLBACK_DURATION = "sampleCallbackDuration"; // long
-
- private final static StatisticsType samplerType;
- private final static int sampleCountId;
- private final static int sampleTimeId;
- private final static int delayDurationId;
- private final static int statResourcesId;
- private final static int jvmPausesId;
- private final static int sampleCallbacksId;
- private final static int sampleCallbackErrorsId;
- private final static int sampleCallbackDurationId;
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- samplerType = f.createType("StatSampler",
- "Stats on the statistic sampler.",
- new StatisticDescriptor[] {
- f.createIntCounter(SAMPLE_COUNT,
- "Total number of samples taken by this sampler.",
- "samples", false),
- f.createLongCounter(SAMPLE_TIME,
- "Total amount of time spent taking samples.",
- "milliseconds", false),
- f.createIntGauge(DELAY_DURATION,
- "Actual duration of sampling delay taken before taking this sample.",
- "milliseconds", false),
- f.createIntGauge(STAT_RESOURCES,
- "Current number of statistic resources being sampled by this sampler.",
- "resources", false),
- f.createIntCounter(JVM_PAUSES,
- "Total number of JVM pauses (which may or may not be full GC pauses) detected by this sampler. A JVM pause is defined as a system event which kept the statistics sampler thread from sampling for 3000 or more milliseconds. This threshold can be customized by setting the system property gemfire.statSamplerDelayThreshold (units are milliseconds).",
- "jvmPauses", false),
- f.createIntGauge(SAMPLE_CALLBACKS,
- "Current number of statistics that are sampled using callbacks.",
- "resources", false),
- f.createIntCounter(SAMPLE_CALLBACK_ERRORS,
- "Total number of exceptions thrown by callbacks when performing sampling",
- "errors", false),
- f.createLongCounter(SAMPLE_CALLBACK_DURATION,
- "Total amount of time invoking sampling callbacks",
- "milliseconds", false),
- });
- sampleCountId = samplerType.nameToId(SAMPLE_COUNT);
- sampleTimeId = samplerType.nameToId(SAMPLE_TIME);
- delayDurationId = samplerType.nameToId(DELAY_DURATION);
- statResourcesId = samplerType.nameToId(STAT_RESOURCES);
- jvmPausesId = samplerType.nameToId(JVM_PAUSES);
- sampleCallbacksId = samplerType.nameToId(SAMPLE_CALLBACKS);
- sampleCallbackErrorsId = samplerType.nameToId(SAMPLE_CALLBACK_ERRORS);
- sampleCallbackDurationId = samplerType.nameToId(SAMPLE_CALLBACK_DURATION);
- }
-
- private final Statistics samplerStats;
-
- public StatSamplerStats(StatisticsFactory f, long id) {
- this.samplerStats = f.createStatistics(samplerType, "statSampler", id);
- }
-
- public void tookSample(long nanosSpentWorking, int statResources, long nanosSpentSleeping) {
- this.samplerStats.incInt(sampleCountId, 1);
- this.samplerStats.incLong(sampleTimeId, nanosSpentWorking / 1000000);
- this.samplerStats.setInt(delayDurationId, (int)(nanosSpentSleeping / 1000000));
- this.samplerStats.setInt(statResourcesId, statResources);
- }
-
- public void incJvmPauses() {
- this.samplerStats.incInt(jvmPausesId, 1);
- }
-
- public void incSampleCallbackErrors(int delta) {
- this.samplerStats.incInt(sampleCallbackErrorsId, delta);
- }
-
- public void setSampleCallbacks(int count) {
- this.samplerStats.setInt(sampleCallbacksId, count);
- }
-
- public void incSampleCallbackDuration(long delta) {
- this.samplerStats.incLong(sampleCallbackDurationId, delta);
- }
-
- public int getSampleCount() {
- return this.samplerStats.getInt(SAMPLE_COUNT);
- }
-
- public long getSampleTime() {
- return this.samplerStats.getLong(SAMPLE_TIME);
- }
-
- public int getDelayDuration() {
- return this.samplerStats.getInt(DELAY_DURATION);
- }
-
- public int getStatResources() {
- return this.samplerStats.getInt(STAT_RESOURCES);
- }
-
- public int getJvmPauses() {
- return this.samplerStats.getInt(JVM_PAUSES);
- }
-
- public void close() {
- this.samplerStats.close();
- }
-
- public Statistics getStats(){
- return this.samplerStats;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder(getClass().getName());
- sb.append("@").append(System.identityHashCode(this)).append("{");
- sb.append("isClosed=").append(this.samplerStats.isClosed());
- sb.append(", ").append(SAMPLE_COUNT + "=").append(this.samplerStats.getInt(SAMPLE_COUNT));
- sb.append(", ").append(SAMPLE_TIME + "=").append(this.samplerStats.getLong(SAMPLE_TIME));
- sb.append(", ").append(DELAY_DURATION + "=").append(this.samplerStats.getInt(DELAY_DURATION));
- sb.append(", ").append(STAT_RESOURCES + "=").append(this.samplerStats.getInt(STAT_RESOURCES));
- sb.append(", ").append(JVM_PAUSES + "=").append(this.samplerStats.getInt(JVM_PAUSES));
- sb.append("}");
- return sb.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticDescriptorImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticDescriptorImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticDescriptorImpl.java
deleted file mode 100644
index 2f407ba..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticDescriptorImpl.java
+++ /dev/null
@@ -1,383 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-
-/**
- * Describes an individual statistic whose value is updated by an
- * application and may be archived by GemFire. These descriptions are
- * gathered together in a {@link StatisticsType}.
- *
- * @see Statistics
- *
- *
- * @since GemFire 3.0
- */
-public final class StatisticDescriptorImpl implements StatisticDescriptor {
-
- /** A constant for an <code>byte</code> type */
- static final byte BYTE = (byte) 3;
-
- /** A constant for an <code>short</code> type */
- static final byte SHORT = (byte) 4;
-
- /** A constant for an <code>int</code> type */
- static final byte INT = (byte) 5;
-
- /** A constant for an <code>long</code> type */
- static final byte LONG = (byte) 6;
-
- /** A constant for an <code>float</code> type */
- static final byte FLOAT = (byte) 7;
-
- /** A constant for an <code>double</code> type */
- static final byte DOUBLE = (byte) 8;
-
- //////////////////// Instance Fields ////////////////////
-
- /** An unitialized offset */
- private int INVALID_OFFSET = -1;
-
- /** The name of the statistic */
- private final String name;
-
- /** The type code of this statistic */
- private final byte typeCode;
-
- /** A description of the statistic */
- private final String description;
-
- /** The unit of the statistic */
- private final String unit;
-
- /** Is the statistic a counter? */
- private final boolean isCounter;
-
- /** Do larger values of the statistic indicate better performance? */
- private final boolean isLargerBetter;
-
- /** The physical offset used to access the data that stores the
- * value for this statistic in an instance of {@link Statistics}
- */
- private int id = INVALID_OFFSET;
-
- ////////////////////// Static Methods //////////////////////
-
- /**
- * Returns the name of the given type code
- *
- * @throws IllegalArgumentException
- * <code>code</code> is an unknown type
- */
- public final static String getTypeCodeName(int code) {
- switch (code) {
- case BYTE:
- return "byte";
- case SHORT:
- return "short";
- case FLOAT:
- return "float";
- case INT:
- return "int";
- case LONG:
- return "long";
- case DOUBLE:
- return "double";
- default:
- throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_UNKNOWN_TYPE_CODE_0.toLocalizedString(Integer.valueOf(code)));
- }
- }
-
- /**
- * Returns the number of bits needed to represent a value of the given type
- *
- * @throws IllegalArgumentException
- * <code>code</code> is an unknown type
- */
- public final static int getTypeCodeBits(int code) {
- switch (code) {
- case BYTE:
- return 8;
- case SHORT:
- return 16;
- case FLOAT:
- return 32;
- case INT:
- return 32;
- case LONG:
- return 64;
- case DOUBLE:
- return 64;
- default:
- throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_UNKNOWN_TYPE_CODE_0.toLocalizedString(Integer.valueOf(code)));
- }
- }
-
- /**
- * Returns the class of the given type code
- *
- * @throws IllegalArgumentException
- * <code>code</code> is an unknown type
- */
- public final static Class<?> getTypeCodeClass(byte code) {
- switch (code) {
- case BYTE:
- return byte.class;
- case SHORT:
- return short.class;
- case FLOAT:
- return float.class;
- case INT:
- return int.class;
- case LONG:
- return long.class;
- case DOUBLE:
- return double.class;
- default:
- throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_UNKNOWN_TYPE_CODE_0.toLocalizedString(Integer.valueOf(code)));
- }
- }
-
- public static StatisticDescriptor createIntCounter(String name, String description,
- String units, boolean isLargerBetter) {
- return new StatisticDescriptorImpl(name, INT, description, units, true, isLargerBetter);
- }
- public static StatisticDescriptor createLongCounter(String name, String description,
- String units, boolean isLargerBetter) {
- return new StatisticDescriptorImpl(name, LONG, description, units, true, isLargerBetter);
- }
- public static StatisticDescriptor createDoubleCounter(String name, String description,
- String units, boolean isLargerBetter) {
- return new StatisticDescriptorImpl(name, DOUBLE, description, units, true, isLargerBetter);
- }
- public static StatisticDescriptor createIntGauge(String name, String description,
- String units, boolean isLargerBetter) {
- return new StatisticDescriptorImpl(name, INT, description, units, false, isLargerBetter);
- }
- public static StatisticDescriptor createLongGauge(String name, String description,
- String units, boolean isLargerBetter) {
- return new StatisticDescriptorImpl(name, LONG, description, units, false, isLargerBetter);
- }
- public static StatisticDescriptor createDoubleGauge(String name, String description,
- String units, boolean isLargerBetter) {
- return new StatisticDescriptorImpl(name, DOUBLE, description, units, false, isLargerBetter);
- }
-
- /////////////////////// Constructors ///////////////////////
-
- /**
- * Creates a new description of a statistic.
- *
- * @param name
- * The name of the statistic (for example,
- * <code>"numDatabaseLookups"</code>)
- * @param typeCode
- * The type of the statistic. This must be either
- * <code>int.class</code>, <code>long.class</code>, or
- * <code>double.class</code>.
- * @param description
- * A description of the statistic (for example, <code>"The
- * number of database lookups"</code>
- * @param unit
- * The units that this statistic is measure in (for example,
- * <code>"milliseconds"</code>)
- * @param isCounter
- * Is this statistic a counter? That is, does its value
- * change monotonically (always increases or always
- * decreases)?
- * @param isLargerBetter
- * True if larger values indicate better performance.
- *
- * @throws IllegalArgumentException
- * <code>type</code> is not one of <code>int.class</code>,
- * <code>long.class</code>, or <code>double.class</code>.
- */
- private StatisticDescriptorImpl(String name, byte typeCode,
- String description, String unit,
- boolean isCounter,
- boolean isLargerBetter) {
- this.name = name;
- this.typeCode = typeCode;
- if (description == null) {
- this.description = "";
-
- } else {
- this.description = description;
- }
-
- if (unit == null) {
- this.unit = "";
-
- } else {
- this.unit = unit;
- }
- this.isCounter = isCounter;
- this.isLargerBetter = isLargerBetter;
- }
-
- //////////////////// StatisticDescriptor Methods ////////////////////
-
- public final String getName() {
- return this.name;
- }
-
- public final String getDescription() {
- return this.description;
- }
-
- public final Class<?> getType() {
- return getTypeCodeClass(this.typeCode);
- }
-
- public final int getStorageBits() {
- return getTypeCodeBits(this.typeCode);
- }
-
- public final boolean isCounter() {
- return this.isCounter;
- }
-
- public final boolean isLargerBetter() {
- return this.isLargerBetter;
- }
-
- public final String getUnit() {
- return this.unit;
- }
-
- public final int getId() {
-// if (this.id == INVALID_OFFSET) {
-// String s = "The id has not been initialized yet.";
-// throw new IllegalStateException(s);
-// }
-
- //Assert.assertTrue(this.id >= 0);
- return this.id;
- }
-
- public final Number getNumberForRawBits(long bits) {
- switch (this.typeCode) {
- case StatisticDescriptorImpl.INT:
- return (int)bits;
- case StatisticDescriptorImpl.LONG:
- return bits;
- case StatisticDescriptorImpl.DOUBLE:
- return Double.longBitsToDouble(bits);
- default:
- throw new RuntimeException(LocalizedStrings.StatisticsImpl_UNEXPECTED_STAT_DESCRIPTOR_TYPE_CODE_0.toLocalizedString(Byte.valueOf(this.typeCode)));
- }
- }
-
- //////////////////// Instance Methods ////////////////////
-
- /**
- * Returns the type code of this statistic
- */
- public final byte getTypeCode() {
- return this.typeCode;
- }
-
- /**
- * Sets the id of this descriptor
- */
- final void setId(int id) {
- //Assert.assertTrue(id >= 0);
- this.id = id;
- }
-
- //////////////////// Comparable Methods ////////////////////
- /**
- * <code>StatisticDescriptor</code>s are naturally ordered by their
- * name.
- *
- * @throws IllegalArgumentException
- * <code>o</code> is not a <code>StatisticDescriptor</code>
- *
- * @see #getName
- */
- public int compareTo(StatisticDescriptor o) {
- return this.getName().compareTo(o.getName());
- }
-
- public final int checkInt() {
- if (this.typeCode != INT) {
- throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_THE_STATISTIC_0_WITH_ID_1_IS_OF_TYPE_2_AND_IT_WAS_EXPECTED_TO_BE_AN_INT.toLocalizedString(new Object[] {getName(), Integer.valueOf(getId()), StatisticDescriptorImpl.getTypeCodeName(getTypeCode())}));
- }
- return this.id;
- }
-
- public final int checkLong() {
- if (this.typeCode != LONG) {
- StringBuffer sb = new StringBuffer();
- sb.append("The statistic " + getName() + " with id ");
- sb.append(getId());
- sb.append(" is of type ");
- sb.append(StatisticDescriptorImpl.getTypeCodeName(getTypeCode()));
-
- sb.append(" and it was expected to be a long");
- throw new IllegalArgumentException(sb.toString());
- }
- return this.id;
- }
-
- public final int checkDouble() {
- if (this.typeCode != DOUBLE) {
- throw new IllegalArgumentException(LocalizedStrings.StatisticDescriptorImpl_THE_STATISTIC_0_WITH_ID_1_IS_OF_TYPE_2_AND_IT_WAS_EXPECTED_TO_BE_A_DOUBLE.toLocalizedString(new Object[] {getName(), Integer.valueOf(getId()), StatisticDescriptorImpl.getTypeCodeName(getTypeCode())}));
- }
- return this.id;
- }
-
-
- @Override // GemStoneAddition
- public int hashCode() {
- return getName().hashCode();
- }
- @Override
- public boolean equals(Object o) {
- if (o == null) {
- return false;
- }
- if (!(o instanceof StatisticDescriptorImpl)) {
- return false;
- }
- StatisticDescriptorImpl other = (StatisticDescriptorImpl)o;
- if (getId() != other.getId()) {
- return false;
- }
- if (!getName().equals(other.getName())) {
- return false;
- }
- if (isCounter() != other.isCounter()) {
- return false;
- }
- if (isLargerBetter() != other.isLargerBetter()) {
- return false;
- }
- if (!getType().equals(other.getType())) {
- return false;
- }
- if (!getUnit().equals(other.getUnit())) {
- return false;
- }
- if (!getDescription().equals(other.getDescription())) {
- return false;
- }
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsImpl.java
deleted file mode 100644
index 04bfc01..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsImpl.java
+++ /dev/null
@@ -1,589 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-//import com.gemstone.gemfire.distributed.DistributedSystem;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.DoubleSupplier;
-import java.util.function.IntSupplier;
-import java.util.function.LongSupplier;
-import java.util.function.Supplier;
-
-import com.gemstone.gemfire.StatisticDescriptor;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.concurrent.Atomics;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.util.concurrent.CopyOnWriteHashMap;
-
-import org.apache.logging.log4j.Logger;
-
-// @todo darrel Add statistics instances to archive when they are created.
-/**
- * An object that maintains the values of various application-defined
- * statistics. The statistics themselves are described by an instance
- * of {@link StatisticsType}.
- *
- * <P>
- *
- * For optimal statistic access, each statistic may be referred to by
- * its {@link #nameToId id} in the statistics object.
- *
- * <P>
- *
- * @see <A href="package-summary.html#statistics">Package introduction</A>
- *
- *
- * @since GemFire 3.0
- */
-public abstract class StatisticsImpl implements Statistics {
- /** logger - not private for tests */
- static Logger logger = LogService.getLogger();
-
- /** The type of this statistics instance */
- private final StatisticsTypeImpl type;
-
- /** The display name of this statistics instance */
- private final String textId;
-
- /** Numeric information display with these statistics */
- private final long numericId;
-
- /** Non-zero if stats values come from operating system system calls */
- private final int osStatFlags;
-
- /** Are these statistics closed? */
- private boolean closed;
-
- /** Uniquely identifies this instance */
- private long uniqueId;
-
- /**
- * Suppliers of int sample values to be sampled every sample-interval
- */
- private final CopyOnWriteHashMap<Integer, IntSupplier> intSuppliers = new CopyOnWriteHashMap<>();
- /**
- * Suppliers of long sample values to be sampled every sample-interval
- */
- private final CopyOnWriteHashMap<Integer, LongSupplier> longSuppliers = new CopyOnWriteHashMap<>();
- /**
- * Suppliers of double sample values to be sampled every sample-interval
- */
- private final CopyOnWriteHashMap<Integer, DoubleSupplier> doubleSuppliers = new CopyOnWriteHashMap<>();
-
- /**
- * Suppliers that have previously failed. Tracked to avoid logging many messages about
- * a failing supplier
- */
- private final Set<Object> flakySuppliers = new HashSet<Object>();
-
- /////////////////////// Constructors ///////////////////////
-
- /** factory method to create a class that implements Statistics
- */
- public static Statistics createAtomicNoOS(StatisticsType type, String textId,
- long numericId, long uniqueId,
- StatisticsManager mgr) {
- return Atomics.createAtomicStatistics(type, textId, numericId, uniqueId, mgr);
- }
- /**
- * Creates a new statistics instance of the given type and unique id
- *
- * @param type
- * A description of the statistics
- * @param textId
- * Text that helps identifies this instance
- * @param numericId
- * A number that helps identify this instance
- * @param uniqueId
- * A number that uniquely identifies this instance
- * @param osStatFlags
- * Non-zero if stats require system calls to collect them; for internal use only
- */
- public StatisticsImpl(StatisticsType type, String textId,
- long numericId, long uniqueId, int osStatFlags) {
- this.type = (StatisticsTypeImpl)type;
- this.textId = textId;
- this.numericId = numericId;
- this.uniqueId = uniqueId;
- this.osStatFlags = osStatFlags;
- closed = false;
- }
-
- ////////////////////// Instance Methods //////////////////////
-
- public final boolean usesSystemCalls() {
- return this.osStatFlags != 0;
- }
-
- public final int getOsStatFlags() {
- return this.osStatFlags;
- }
-
- public final int nameToId(String name) {
- return this.type.nameToId(name);
- }
-
- public final StatisticDescriptor nameToDescriptor(String name) {
- return this.type.nameToDescriptor(name);
- }
-
- public void close() {
- this.closed = true;
- }
-
- public final boolean isClosed() {
- return this.closed;
- }
-
- public abstract boolean isAtomic();
-
- private final boolean isOpen() { // fix for bug 29973
- return !this.closed;
- }
-
- //////////////////////// attribute Methods ///////////////////////
-
- public final StatisticsType getType() {
- return this.type;
- }
- public final String getTextId() {
- return this.textId;
- }
- public final long getNumericId() {
- return this.numericId;
- }
-
- /**
- * Gets the unique id for this resource
- */
- public long getUniqueId() {
- return this.uniqueId;
- }
- /**
- * Sets a unique id for this resource.
- */
- public void setUniqueId(long uid) {
- this.uniqueId = uid;
- }
-
- //////////////////////// set() Methods ///////////////////////
-
- public final void setInt(String name, int value) {
- setInt(nameToDescriptor(name), value);
- }
-
- public final void setInt(StatisticDescriptor descriptor, int value) {
- setInt(getIntId(descriptor), value);
- }
-
- public final void setInt(int id, int value) {
- if (isOpen()) {
- _setInt(id, value);
- }
- }
-
- /**
- * Sets the value of a statistic of type <code>int</code> at the
- * given offset, but performs no type checking.
- */
- protected abstract void _setInt(int offset, int value);
-
- public final void setLong(String name, long value) {
- setLong(nameToDescriptor(name), value);
- }
-
- public final void setLong(StatisticDescriptor descriptor, long value) {
- setLong(getLongId(descriptor), value);
- }
-
- public final void setLong(int id, long value) {
- if (isOpen()) {
- _setLong(id, value);
- }
- }
-
- /**
- * Sets the value of a statistic of type <code>long</code> at the
- * given offset, but performs no type checking.
- */
- protected abstract void _setLong(int offset, long value);
-
- public final void setDouble(String name, double value) {
- setDouble(nameToDescriptor(name), value);
- }
-
- public final void setDouble(StatisticDescriptor descriptor, double value) {
- setDouble(getDoubleId(descriptor), value);
- }
-
- public final void setDouble(int id, double value) {
- if (isOpen()) {
- _setDouble(id, value);
- }
- }
-
- /**
- * Sets the value of a statistic of type <code>double</code> at the
- * given offset, but performs no type checking.
- */
- protected abstract void _setDouble(int offset, double value);
-
- /////////////////////// get() Methods ///////////////////////
-
- public final int getInt(String name) {
- return getInt(nameToDescriptor(name));
- }
-
- public final int getInt(StatisticDescriptor descriptor) {
- return getInt(getIntId(descriptor));
- }
-
- public final int getInt(int id) {
- if (isOpen()) {
- return _getInt(id);
- } else {
- return 0;
- }
- }
-
- /**
- * Returns the value of the statistic of type <code>int</code> at
- * the given offset, but performs no type checking.
- */
- protected abstract int _getInt(int offset);
-
-
- public final long getLong(String name) {
- return getLong(nameToDescriptor(name));
- }
-
- public final long getLong(StatisticDescriptor descriptor) {
- return getLong(getLongId(descriptor));
- }
-
- public final long getLong(int id) {
- if (isOpen()) {
- return _getLong(id);
- } else {
- return 0;
- }
- }
-
-
- /**
- * Returns the value of the statistic of type <code>long</code> at
- * the given offset, but performs no type checking.
- */
- protected abstract long _getLong(int offset);
-
- public final double getDouble(String name) {
- return getDouble(nameToDescriptor(name));
- }
-
- public final double getDouble(StatisticDescriptor descriptor) {
- return getDouble(getDoubleId(descriptor));
- }
-
- public final double getDouble(int id) {
- if (isOpen()) {
- return _getDouble(id);
- } else {
- return 0.0;
- }
- }
-
- /**
- * Returns the value of the statistic of type <code>double</code> at
- * the given offset, but performs no type checking.
- */
- protected abstract double _getDouble(int offset);
-
- public final Number get(StatisticDescriptor descriptor) {
- if (isOpen()) {
- return _get((StatisticDescriptorImpl)descriptor);
- } else {
- return Integer.valueOf(0);
- }
- }
-
- public final Number get(String name) {
- return get(nameToDescriptor(name));
- }
-
- public long getRawBits(StatisticDescriptor descriptor) {
- if (isOpen()) {
- return _getRawBits((StatisticDescriptorImpl)descriptor);
- } else {
- return 0;
- }
- }
-
- public long getRawBits(String name) {
- return getRawBits(nameToDescriptor(name));
- }
-
- //////////////////////// inc() Methods ////////////////////////
-
- public final void incInt(String name, int delta) {
- incInt(nameToDescriptor(name), delta);
- }
-
- public final void incInt(StatisticDescriptor descriptor, int delta) {
- incInt(getIntId(descriptor), delta);
- }
-
- public final void incInt(int id, int delta) {
- if (isOpen()) {
- _incInt(id, delta);
- }
- }
-
- /**
- * Increments the value of the statistic of type <code>int</code> at
- * the given offset by a given amount, but performs no type checking.
- */
- protected abstract void _incInt(int offset, int delta);
-
- public final void incLong(String name, long delta) {
- incLong(nameToDescriptor(name), delta);
- }
- public final void incLong(StatisticDescriptor descriptor, long delta) {
- incLong(getLongId(descriptor), delta);
- }
- public final void incLong(int id, long delta) {
- if (isOpen()) {
- _incLong(id, delta);
- }
- }
-
- /**
- * Increments the value of the statistic of type <code>long</code> at
- * the given offset by a given amount, but performs no type checking.
- */
- protected abstract void _incLong(int offset, long delta);
-
- public final void incDouble(String name, double delta) {
- incDouble(nameToDescriptor(name), delta);
- }
-
- public final void incDouble(StatisticDescriptor descriptor, double delta) {
- incDouble(getDoubleId(descriptor), delta);
- }
-
- public final void incDouble(int id, double delta) {
- if (isOpen()) {
- _incDouble(id, delta);
- }
- }
-
- /**
- * Increments the value of the statistic of type <code>double</code> at
- * the given offset by a given amount, but performs no type checking.
- */
- protected abstract void _incDouble(int offset, double delta);
-
- /**
- * For internal use only.
- * Tells the implementation to prepare the data in this instance
- * for sampling.
- * @since GemFire 5.1
- */
- public void prepareForSample() {
- // nothing needed in this impl.
- }
-
- /**
- * Invoke sample suppliers to retrieve the current value for
- * the suppler controlled sets and update the stats to reflect
- * the supplied values.
- * @return the number of callback errors that occurred while
- * sampling stats
- */
- public int invokeSuppliers() {
- int errors = 0;
- for(Map.Entry<Integer, IntSupplier> entry: intSuppliers.entrySet()) {
- try {
- _setInt(entry.getKey(), entry.getValue().getAsInt());
- } catch(Throwable t) {
- logSupplierError(t, entry.getKey(), entry.getValue());
- errors++;
- }
- }
- for(Map.Entry<Integer, LongSupplier> entry: longSuppliers.entrySet()) {
- try {
- _setLong(entry.getKey(), entry.getValue().getAsLong());
- } catch(Throwable t) {
- logSupplierError(t, entry.getKey(), entry.getValue());
- errors++;
- }
- }
- for(Map.Entry<Integer, DoubleSupplier> entry: doubleSuppliers.entrySet()) {
- try {
- _setDouble(entry.getKey(), entry.getValue().getAsDouble());
- } catch(Throwable t) {
- logSupplierError(t, entry.getKey(), entry.getValue());
- errors++;
- }
- }
-
- return errors;
- }
-
- private void logSupplierError(final Throwable t, int statId, Object supplier) {
- if(flakySuppliers.add(supplier)) {
- logger.warn("Error invoking supplier for stat {}, id {}", this.getTextId(), statId, t);
- }
- }
-
- /**
- * @return the number of statistics that are measured using supplier callbacks
- */
- public int getSupplierCount() {
- return intSuppliers.size() + doubleSuppliers.size() + longSuppliers.size();
- }
-
- @Override
- public IntSupplier setIntSupplier(final int id, final IntSupplier supplier) {
- if(id >= type.getIntStatCount()) {
- throw new IllegalArgumentException("Id " + id + " is not in range for stat" + type);
- }
- return intSuppliers.put(id, supplier);
- }
-
- @Override
- public IntSupplier setIntSupplier(final String name, final IntSupplier supplier) {
- return setIntSupplier(nameToId(name), supplier);
- }
-
- @Override
- public IntSupplier setIntSupplier(final StatisticDescriptor descriptor, final IntSupplier supplier) {
- return setIntSupplier(getIntId(descriptor), supplier);
- }
-
- @Override
- public LongSupplier setLongSupplier(final int id, final LongSupplier supplier) {
- if(id >= type.getLongStatCount()) {
- throw new IllegalArgumentException("Id " + id + " is not in range for stat" + type);
- }
- return longSuppliers.put(id, supplier);
- }
-
- @Override
- public LongSupplier setLongSupplier(final String name, final LongSupplier supplier) {
- return setLongSupplier(nameToId(name), supplier);
- }
-
- @Override
- public LongSupplier setLongSupplier(final StatisticDescriptor descriptor, final LongSupplier supplier) {
- return setLongSupplier(getLongId(descriptor), supplier);
- }
-
- @Override
- public DoubleSupplier setDoubleSupplier(final int id, final DoubleSupplier supplier) {
- if(id >= type.getDoubleStatCount()) {
- throw new IllegalArgumentException("Id " + id + " is not in range for stat" + type);
- }
- return doubleSuppliers.put(id, supplier);
- }
-
- @Override
- public DoubleSupplier setDoubleSupplier(final String name, final DoubleSupplier supplier) {
- return setDoubleSupplier(nameToId(name), supplier);
- }
-
- @Override
- public DoubleSupplier setDoubleSupplier(final StatisticDescriptor descriptor, final DoubleSupplier supplier) {
- return setDoubleSupplier(getDoubleId(descriptor), supplier);
- }
-
- @Override
- public int hashCode() {
- return (int)this.uniqueId;
- }
- @Override
- public boolean equals(Object o) {
- if (o == null) {
- return false;
- }
- if (!(o instanceof StatisticsImpl)) {
- return false;
- }
- StatisticsImpl other = (StatisticsImpl)o;
- return this.uniqueId == other.getUniqueId();
- }
-
- private final static int getIntId(StatisticDescriptor descriptor) {
- return ((StatisticDescriptorImpl)descriptor).checkInt();
- }
-
- private final static int getLongId(StatisticDescriptor descriptor) {
- return ((StatisticDescriptorImpl)descriptor).checkLong();
- }
-
- private final static int getDoubleId(StatisticDescriptor descriptor) {
- return ((StatisticDescriptorImpl)descriptor).checkDouble();
- }
-
- /**
- * Returns the value of the specified statistic descriptor.
- */
- private final Number _get(StatisticDescriptorImpl stat) {
- switch (stat.getTypeCode()) {
- case StatisticDescriptorImpl.INT:
- return Integer.valueOf(_getInt(stat.getId()));
- case StatisticDescriptorImpl.LONG:
- return Long.valueOf(_getLong(stat.getId()));
- case StatisticDescriptorImpl.DOUBLE:
- return Double.valueOf(_getDouble(stat.getId()));
- default:
- throw new RuntimeException(LocalizedStrings.StatisticsImpl_UNEXPECTED_STAT_DESCRIPTOR_TYPE_CODE_0.toLocalizedString(Byte.valueOf(stat.getTypeCode())));
- }
- }
- /**
- * Returns the bits that represent the raw value of the
- * specified statistic descriptor.
- */
- private final long _getRawBits(StatisticDescriptorImpl stat) {
- switch (stat.getTypeCode()) {
- case StatisticDescriptorImpl.INT:
- return _getInt(stat.getId());
- case StatisticDescriptorImpl.LONG:
- return _getLong(stat.getId());
- case StatisticDescriptorImpl.DOUBLE:
- return Double.doubleToRawLongBits(_getDouble(stat.getId()));
- default:
- throw new RuntimeException(LocalizedStrings.StatisticsImpl_UNEXPECTED_STAT_DESCRIPTOR_TYPE_CODE_0.toLocalizedString(Byte.valueOf(stat.getTypeCode())));
- }
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder(getClass().getName());
- sb.append("@").append(System.identityHashCode(this)).append("{");
- sb.append("uniqueId=").append(this.uniqueId);
- sb.append(", numericId=").append(this.numericId);
- sb.append(", textId=").append(this.textId);
- sb.append(", type=").append(this.type.getName());
- sb.append(", closed=").append(this.closed);
- sb.append("}");
- return sb.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsManager.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsManager.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsManager.java
deleted file mode 100644
index c33d163..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsManager.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import java.util.List;
-
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsFactory;
-
-/**
- * Defines the contract that a statistics factory must implement
- * for its Statistics instances. This is an internal implementation
- * specific interface.
- *
- *
- */
-public interface StatisticsManager extends StatisticsFactory {
- /**
- * Called when the Statistics instance <code>s</code> is closed.
- */
- public void destroyStatistics(Statistics s);
- /**
- * Returns a name that can be used to identify the manager
- */
- public String getName();
- /**
- * Returns a numeric id that can be used to identify the manager
- */
- public long getId();
- /**
- * Returns the start time of this manager.
- */
- public long getStartTime();
- /**
- * Returns a value that changes any time a Statistics instance is added
- * or removed from this manager.
- */
- public int getStatListModCount();
- /**
- * Returns a list of all the Statistics this manager is currently managing.
- */
- public List<Statistics> getStatsList();
-
- /**
- * Returns the current number of statistics instances.
- */
- public int getStatisticsCount();
-
- /**
- * Returns the statistics resource instance given its id.
- */
- public Statistics findStatistics(long id);
-
- /**
- * Returns true if the specified statistic resource still exists.
- */
- public boolean statisticsExists(long id);
-
- /**
- * Returns an array of all the current statistic resource instances.
- */
- public Statistics[] getStatistics();
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeFactoryImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeFactoryImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeFactoryImpl.java
deleted file mode 100644
index e4688d5..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeFactoryImpl.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-
-import java.io.*;
-import java.util.*;
-
-/**
- * The implementation of {@link StatisticsTypeFactory}.
- * Each VM can any have a single instance of this class which can
- * be accessed by calling {@link #singleton()}.
- *
- * @see <A href="package-summary.html#statistics">Package introduction</A>
- *
- *
- * @since GemFire 3.0
- *
- */
-public class StatisticsTypeFactoryImpl implements StatisticsTypeFactory {
- // static fields
- private final static StatisticsTypeFactoryImpl singleton = new StatisticsTypeFactoryImpl();
-
- // static methods
- /**
- * Returns the single instance of this class.
- */
- public final static StatisticsTypeFactory singleton() {
- return singleton;
- }
-
- protected final static void clear() {
- singleton.statTypes.clear();
- }
-
- // constructors
- private StatisticsTypeFactoryImpl() {
- }
-
- // instance fields
- private final HashMap statTypes = new HashMap();
-
- // instance methods
- /**
- * Adds an already created type. If the type has already been
- * added and is equal to the new one then the new one is dropped and the existing one returned.
- * @throws IllegalArgumentException if the type already exists and is not equal to the new type
- */
- public StatisticsType addType(StatisticsType t) {
- StatisticsType result = t;
- synchronized (this.statTypes) {
- StatisticsType currentValue = findType(result.getName());
- if (currentValue == null) {
- this.statTypes.put(result.getName(), result);
- } else if (result.equals(currentValue)) {
- result = currentValue;
- } else {
- throw new IllegalArgumentException(LocalizedStrings.StatisticsTypeFactoryImpl_STATISTICS_TYPE_NAMED_0_ALREADY_EXISTS.toLocalizedString(result.getName()));
- }
- }
- return result;
- }
- public StatisticsType createType(String name, String description,
- StatisticDescriptor[] stats) {
- return addType(new StatisticsTypeImpl(name, description, stats));
- }
- public StatisticsType findType(String name) {
- return (StatisticsType)this.statTypes.get(name);
- }
- public StatisticsType[] createTypesFromXml(Reader reader)
- throws IOException {
- return StatisticsTypeImpl.fromXml(reader, this);
- }
-
- public StatisticDescriptor createIntCounter(String name, String description,
- String units) {
- return StatisticDescriptorImpl.createIntCounter(name, description, units, true);
- }
- public StatisticDescriptor createLongCounter(String name, String description,
- String units) {
- return StatisticDescriptorImpl.createLongCounter(name, description, units, true);
- }
- public StatisticDescriptor createDoubleCounter(String name, String description,
- String units) {
- return StatisticDescriptorImpl.createDoubleCounter(name, description, units, true);
- }
- public StatisticDescriptor createIntGauge(String name, String description,
- String units) {
- return StatisticDescriptorImpl.createIntGauge(name, description, units, false);
- }
- public StatisticDescriptor createLongGauge(String name, String description,
- String units) {
- return StatisticDescriptorImpl.createLongGauge(name, description, units, false);
- }
- public StatisticDescriptor createDoubleGauge(String name, String description,
- String units) {
- return StatisticDescriptorImpl.createDoubleGauge(name, description, units, false);
- }
-
- public StatisticDescriptor createIntCounter(String name, String description,
- String units, boolean largerBetter) {
- return StatisticDescriptorImpl.createIntCounter(name, description, units, largerBetter);
- }
- public StatisticDescriptor createLongCounter(String name, String description,
- String units, boolean largerBetter) {
- return StatisticDescriptorImpl.createLongCounter(name, description, units, largerBetter);
- }
- public StatisticDescriptor createDoubleCounter(String name, String description,
- String units, boolean largerBetter) {
- return StatisticDescriptorImpl.createDoubleCounter(name, description, units, largerBetter);
- }
- public StatisticDescriptor createIntGauge(String name, String description,
- String units, boolean largerBetter) {
- return StatisticDescriptorImpl.createIntGauge(name, description, units, largerBetter);
- }
- public StatisticDescriptor createLongGauge(String name, String description,
- String units, boolean largerBetter) {
- return StatisticDescriptorImpl.createLongGauge(name, description, units, largerBetter);
- }
- public StatisticDescriptor createDoubleGauge(String name, String description,
- String units, boolean largerBetter) {
- return StatisticDescriptorImpl.createDoubleGauge(name, description, units, largerBetter);
- }
-}
[07/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/StatSamplerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/StatSamplerJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/StatSamplerJUnitTest.java
deleted file mode 100755
index e16eeaf..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/StatSamplerJUnitTest.java
+++ /dev/null
@@ -1,367 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.logging.log4j.Logger;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.contrib.java.lang.system.RestoreSystemProperties;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TemporaryFolder;
-import org.junit.rules.TestName;
-
-import com.gemstone.gemfire.CancelCriterion;
-import com.gemstone.gemfire.StatisticDescriptor;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.StatArchiveReader.StatValue;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.util.StopWatch;
-import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
-
-/**
- * @since GemFire 7.0
- */
-@Category(IntegrationTest.class)
-public class StatSamplerJUnitTest {
-
- private static final Logger logger = LogService.getLogger();
-
- private Map<String,String> statisticTypes;
- private Map<String,Map<String,Number>> allStatistics;
-
- @Rule
- public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
-
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
- @Rule
- public TestName testName = new TestName();
-
- @Before
- public void setUp() {
- this.statisticTypes = new HashMap<String,String>();
- this.allStatistics = new HashMap<String,Map<String,Number>>();
- }
-
- @After
- public void tearDown() {
- this.statisticTypes = null;
- this.allStatistics = null;
- StatisticsTypeFactoryImpl.clear();
- StatArchiveWriter.clearTraceFilter();
- }
-
- private String getName() {
- return getClass().getSimpleName() + "_" + testName.getMethodName();
- }
-
- @Test
- public void testStatSampler() throws Exception {
- StatArchiveWriter.setTraceFilter("st1_1", "ST1");
-
- File folder = temporaryFolder.newFolder();
- String archiveFileName = folder.getAbsolutePath() + File.separator + getName() + ".gfs";
-
- System.setProperty("stats.log-level", "config");
- System.setProperty("stats.disable", "false");
- System.setProperty("stats.name", getName());
- System.setProperty("stats.archive-file", archiveFileName);
- System.setProperty("stats.file-size-limit", "0");
- System.setProperty("stats.disk-space-limit", "0");
- System.setProperty("stats.sample-rate", "100");
-
- final CancelCriterion stopper = new CancelCriterion() {
- public String cancelInProgress() {
- return null;
- }
- public RuntimeException generateCancelledException(Throwable e) {
- return null;
- }
- };
- final LocalStatisticsFactory factory = new LocalStatisticsFactory(stopper);
- final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
- factory.createDoubleCounter("double_counter_1", "d1", "u1"),
- factory.createDoubleCounter("double_counter_2", "d2", "u2", true),
- factory.createDoubleGauge( "double_gauge_3", "d3", "u3"),
- factory.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
- factory.createIntCounter( "int_counter_5", "d5", "u5"),
- factory.createIntCounter( "int_counter_6", "d6", "u6", true),
- factory.createIntGauge( "int_gauge_7", "d7", "u7"),
- factory.createIntGauge( "int_gauge_8", "d8", "u8", false),
- factory.createLongCounter( "long_counter_9", "d9", "u9"),
- factory.createLongCounter( "long_counter_10", "d10", "u10", true),
- factory.createLongGauge( "long_gauge_11", "d11", "u11"),
- factory.createLongGauge( "long_gauge_12", "d12", "u12", false),
- factory.createLongGauge( "sampled_long", "d13", "u13", false),
- factory.createIntGauge( "sampled_int", "d14", "u14", false),
- factory.createDoubleGauge( "sampled_double", "d15", "u15", false)
- };
- final StatisticsType ST1 = factory.createType("ST1", "ST1", statsST1);
- final Statistics st1_1 = factory.createAtomicStatistics(ST1, "st1_1", 1);
- st1_1.setIntSupplier("sampled_int", () -> 5);
- getOrCreateExpectedValueMap(st1_1).put("sampled_int", 5);
- st1_1.setLongSupplier("sampled_long", () -> 6);
- getOrCreateExpectedValueMap(st1_1).put("sampled_long", 6);
- st1_1.setDoubleSupplier("sampled_double", () -> 7.0);
- getOrCreateExpectedValueMap(st1_1).put("sampled_double", 7.0);
-
- boolean done = false;
-
- Statistics[] samplerStatsInstances = factory.findStatisticsByTextId("statSampler");
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 4000; done = (samplerStatsInstances != null && samplerStatsInstances.length > 0)) {
- Thread.sleep(10);
- samplerStatsInstances = factory.findStatisticsByTextId("statSampler");
- }
-
- assertTrue("Waiting for statSampler stats", done);
-
- samplerStatsInstances = factory.findStatisticsByTextId("statSampler");
- assertNotNull(samplerStatsInstances);
- assertEquals(1, samplerStatsInstances.length);
- final Statistics samplerStats = samplerStatsInstances[0];
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_gauge_3", 3);
- incInt(st1_1, "int_counter_5", 5);
- incInt(st1_1, "int_gauge_7", 7);
- incLong(st1_1, "long_counter_9", 9);
- incLong(st1_1, "long_gauge_11", 11);
-
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_counter_2", 1);
- incDouble(st1_1, "double_gauge_3", 1);
- incDouble(st1_1, "double_gauge_4", 1);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 1);
-
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_counter_2", 1);
- incDouble(st1_1, "double_gauge_3", 1);
- incDouble(st1_1, "double_gauge_4", 1);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 1);
- incInt(st1_1, "int_gauge_7", 1);
- incInt(st1_1, "int_gauge_8", 1);
- incLong(st1_1, "long_counter_9", 1);
- incLong(st1_1, "long_counter_10", 1);
- incLong(st1_1, "long_gauge_11", 1);
- incLong(st1_1, "long_gauge_12", 1);
-
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_counter_2", 1);
- incDouble(st1_1, "double_gauge_3", -1);
- incDouble(st1_1, "double_gauge_4", 1);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 1);
- incInt(st1_1, "int_gauge_7", -1);
- incInt(st1_1, "int_gauge_8", 1);
- incLong(st1_1, "long_counter_9", 1);
- incLong(st1_1, "long_counter_10", 1);
- incLong(st1_1, "long_gauge_11", -1);
- incLong(st1_1, "long_gauge_12", 1);
-
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_counter_2", 1);
- incDouble(st1_1, "double_gauge_3", 1);
- incDouble(st1_1, "double_gauge_4", 1);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 1);
- incInt(st1_1, "int_gauge_7", 1);
- incInt(st1_1, "int_gauge_8", 1);
- incLong(st1_1, "long_counter_9", 1);
- incLong(st1_1, "long_counter_10", 1);
- incLong(st1_1, "long_gauge_11", 1);
- incLong(st1_1, "long_gauge_12", 1);
-
- waitForStatSample(samplerStats);
- waitForStatSample(samplerStats);
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_gauge_3", 3);
- incInt(st1_1, "int_counter_5", 5);
- incInt(st1_1, "int_gauge_7", 7);
- incLong(st1_1, "long_counter_9", 9);
- incLong(st1_1, "long_gauge_11", 11);
-
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_counter_2", 1);
- incDouble(st1_1, "double_gauge_3", 1);
- incDouble(st1_1, "double_gauge_4", 1);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 1);
-
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_counter_2", 1);
- incDouble(st1_1, "double_gauge_3", 1);
- incDouble(st1_1, "double_gauge_4", 1);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 1);
- incInt(st1_1, "int_gauge_7", 1);
- incInt(st1_1, "int_gauge_8", 1);
- incLong(st1_1, "long_counter_9", 1);
- incLong(st1_1, "long_counter_10", 1);
- incLong(st1_1, "long_gauge_11", 1);
- incLong(st1_1, "long_gauge_12", 1);
-
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_counter_2", 1);
- incDouble(st1_1, "double_gauge_3", -1);
- incDouble(st1_1, "double_gauge_4", 1);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 1);
- incInt(st1_1, "int_gauge_7", -1);
- incInt(st1_1, "int_gauge_8", 1);
- incLong(st1_1, "long_counter_9", 1);
- incLong(st1_1, "long_counter_10", 1);
- incLong(st1_1, "long_gauge_11", -1);
- incLong(st1_1, "long_gauge_12", 1);
-
- waitForStatSample(samplerStats);
-
- incDouble(st1_1, "double_counter_1", 1);
- incDouble(st1_1, "double_counter_2", 1);
- incDouble(st1_1, "double_gauge_3", 1);
- incDouble(st1_1, "double_gauge_4", 1);
- incInt(st1_1, "int_counter_5", 1);
- incInt(st1_1, "int_counter_6", 1);
- incInt(st1_1, "int_gauge_7", 1);
- incInt(st1_1, "int_gauge_8", 1);
- incLong(st1_1, "long_counter_9", 1);
- incLong(st1_1, "long_counter_10", 1);
- incLong(st1_1, "long_gauge_11", 1);
- incLong(st1_1, "long_gauge_12", 1);
-
- waitForStatSample(samplerStats);
-
- factory.close();
-
- final File archiveFile = new File(System.getProperty("stats.archive-file"));
- assertTrue(archiveFile.exists());
- final StatArchiveReader reader = new StatArchiveReader(
- new File[]{archiveFile}, null, false);
-
- List resources = reader.getResourceInstList();
- for (Iterator iter = resources.iterator(); iter.hasNext();) {
- StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
- String resourceName = ri.getName();
- assertNotNull(resourceName);
-
- if (!resourceName.equals("st1_1")) {
- logger.info("testStatSampler skipping {}", resourceName);
- continue;
- }
-
- String expectedStatsType = this.statisticTypes.get(resourceName);
- assertNotNull(expectedStatsType);
- assertEquals(expectedStatsType, ri.getType().getName());
-
- Map<String,Number> expectedStatValues = this.allStatistics.get(resourceName);
- assertNotNull(expectedStatValues);
-
- StatValue[] statValues = ri.getStatValues();
- for (int i = 0; i < statValues.length; i++) {
- String statName = ri.getType().getStats()[i].getName();
- assertNotNull(statName);
- assertNotNull(expectedStatValues.get(statName));
-
- assertEquals(statName, statValues[i].getDescriptor().getName());
-
- statValues[i].setFilter(StatValue.FILTER_NONE);
- //double[] rawSnapshots = statValues[i].getRawSnapshots();
- assertEquals("Value " + i + " for " + statName + " is wrong: " + expectedStatValues,
- expectedStatValues.get(statName).doubleValue(),
- statValues[i].getSnapshotsMostRecent(),
- 0);
- }
- }
- }
-
- private void waitForStatSample(final Statistics samplerStats) throws InterruptedException {
- int startSampleCount = samplerStats.getInt("sampleCount");
- boolean done = false;
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 3000; done = (samplerStats.getInt("sampleCount") > startSampleCount)) {
- Thread.sleep(10);
- }
- assertTrue("Waiting for statSampler sampleCount to increment", done);
- }
-
- private void incDouble(Statistics statistics, String stat, double value) {
- assertFalse(statistics.isClosed());
- Map<String, Number> statValues = getOrCreateExpectedValueMap(statistics);
- statistics.incDouble(stat, value);
- statValues.put(stat, statistics.getDouble(stat));
- if (this.statisticTypes.get(statistics.getTextId()) == null) {
- this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
- }
- }
-
- private void incInt(Statistics statistics, String stat, int value) {
- assertFalse(statistics.isClosed());
- Map<String, Number> statValues = getOrCreateExpectedValueMap(statistics);
- statistics.incInt(stat, value);
- statValues.put(stat, statistics.getInt(stat));
- if (this.statisticTypes.get(statistics.getTextId()) == null) {
- this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
- }
- }
-
- private Map<String, Number> getOrCreateExpectedValueMap(final Statistics statistics) {
- Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
- if (statValues == null) {
- statValues = new HashMap<String,Number>();
- this.allStatistics.put(statistics.getTextId(), statValues);
- }
- return statValues;
- }
-
- private void incLong(Statistics statistics, String stat, long value) {
- assertFalse(statistics.isClosed());
- Map<String, Number> statValues = getOrCreateExpectedValueMap(statistics);
- statistics.incLong(stat, value);
- statValues.put(stat, statistics.getLong(stat));
- if (this.statisticTypes.get(statistics.getTextId()) == null) {
- this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/StatSamplerTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/StatSamplerTestCase.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/StatSamplerTestCase.java
deleted file mode 100755
index 819a79c..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/StatSamplerTestCase.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.logging.log4j.Logger;
-
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.util.StopWatch;
-
-/**
- * Integration TestCase for StatSampler.
- *
- * @since GemFire 7.0
- */
-public abstract class StatSamplerTestCase {
- protected static final Logger logger = LogService.getLogger();
-
- protected abstract StatisticsManager getStatisticsManager();
-
- protected int getStatListModCount() {
- return getStatisticsManager().getStatListModCount();
- }
-
- protected List<Statistics> getStatsList() {
- return getStatisticsManager().getStatsList();
- }
-
- protected static void waitForFileToExist(final File file, final long millis, final long sleep) {
- boolean done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < millis; done = (file.exists())) {
- Thread.sleep(sleep);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertTrue("Waiting for file to exist: " + file, done);
- }
-
- protected static void waitForFileToDelete(final File file, final long millis, final long sleep) {
- boolean done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < millis; done = (!file.exists())) {
- Thread.sleep(sleep);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertTrue("Waiting for file to be deleted: " + file, done);
- }
-
- protected static void waitForExpectedStatValue(final Statistics statSamplerStats, final String statName, final int expectedStatValue, final long millis, final long sleep) {
- boolean done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < millis; done = (statSamplerStats.getInt(statName) >= expectedStatValue)) {
- Thread.sleep(sleep);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertTrue("Waiting for " + statName + " >= " + expectedStatValue, done);
- }
-
- protected static void waitForStatSample(final Statistics statSamplerStats, final int samples, final long millis, final long sleep) {
- waitForExpectedStatValue(statSamplerStats, "sampleCount", samples, millis, sleep);
- }
-
- protected static void assertStatValueDoesNotChange(final Statistics statSamplerStats, final String statName, final int expectedStatValue, final long millis, final long sleep) {
- boolean done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < millis; done = (statSamplerStats.getInt(statName) != expectedStatValue)) {
- Thread.sleep(sleep);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertFalse("Waiting to assert that " + statName + " does not change from " + expectedStatValue, done);
- }
-
- protected static class AllStatistics {
-
- private final HostStatSampler statSampler;
- private final Map<StatisticsType, Set<Statistics>> allStatistics;
-
- protected AllStatistics(HostStatSampler statSampler) throws InterruptedException {
- this.statSampler = statSampler;
- this.allStatistics = initAllStatistics();
- }
-
- private Map<StatisticsType, Set<Statistics>> initAllStatistics() throws InterruptedException {
- assertTrue(this.statSampler.waitForInitialization(5000));
-
- Map<StatisticsType, Set<Statistics>> statsTypeToStats = new HashMap<StatisticsType, Set<Statistics>>();
- Statistics[] stats = this.statSampler.getStatistics();
- for (int i = 0; i < stats.length; i++) {
- StatisticsType statsType = stats[i].getType();
- Set<Statistics> statsSet = statsTypeToStats.get(statsType);
- if (statsSet == null) {
- statsSet = new HashSet<Statistics>();
- statsSet.add(stats[i]);
- statsTypeToStats.put(statsType, statsSet);
- } else {
- statsSet.add(stats[i]);
- }
- }
- return statsTypeToStats;
- }
-
- protected boolean containsStatisticsType(StatisticsType type) {
- throw new UnsupportedOperationException("TODO");
- }
-
- protected boolean containsStatisticsType(String typeName) throws InterruptedException {
- for (StatisticsType statType : this.allStatistics.keySet()) {
- if (statType.getName().equals(typeName)) {
- return true;
- }
- }
- return false;
- }
-
- protected boolean containsStatistics(Statistics statistics) {
- throw new UnsupportedOperationException("TODO");
- }
-
- protected boolean containsStatistics(String instanceName) throws InterruptedException {
- for (StatisticsType statType : this.allStatistics.keySet()) {
- for (Statistics statistics : this.allStatistics.get(statType)) {
- if (statistics.getTextId().equals(instanceName)) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Statistics[0]: typeName=StatSampler instanceName=statSampler
- * Statistics[1]: typeName=VMStats instanceName=vmStats
- * Statistics[2]: typeName=VMMemoryUsageStats instanceName=vmHeapMemoryStats
- * Statistics[3]: typeName=VMMemoryUsageStats instanceName=vmNonHeapMemoryStats
- * Statistics[4]: typeName=VMMemoryPoolStats instanceName=Code Cache-Non-heap memory
- * Statistics[5]: typeName=VMMemoryPoolStats instanceName=PS Eden Space-Heap memory
- * Statistics[6]: typeName=VMMemoryPoolStats instanceName=PS Survivor Space-Heap memory
- * Statistics[7]: typeName=VMMemoryPoolStats instanceName=PS Old Gen-Heap memory
- * Statistics[8]: typeName=VMMemoryPoolStats instanceName=PS Perm Gen-Non-heap memory
- * Statistics[9]: typeName=VMGCStats instanceName=PS Scavenge
- * Statistics[10]: typeName=VMGCStats instanceName=PS MarkSweep
- * Statistics[11]: typeName=LinuxSystemStats instanceName=kuwait.gemstone.com
- * Statistics[12]: typeName=LinuxProcessStats instanceName=javaApp0-proc
- */
- protected void dumpStatistics() throws InterruptedException {
- Statistics[] stats = this.statSampler.getStatistics();
- for (int i = 0; i < stats.length; i++) {
- logger.info("Statistics[{}]: typeName={} instanceName={}", i, stats[i].getType().getName(), stats[i].getTextId());
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/lru/LRUClockJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/lru/LRUClockJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/lru/LRUClockJUnitTest.java
index 16b7ac5..7e24d0c 100755
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/lru/LRUClockJUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/cache/lru/LRUClockJUnitTest.java
@@ -39,7 +39,7 @@ import com.gemstone.gemfire.cache.EvictionAction;
import com.gemstone.gemfire.cache.EvictionAlgorithm;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.distributed.DistributedSystem;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.InternalRegionArguments;
import com.gemstone.gemfire.internal.cache.PlaceHolderDiskRegion;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/offheap/OffHeapStorageJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/offheap/OffHeapStorageJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/offheap/OffHeapStorageJUnitTest.java
index 93bef98..bf5a176 100755
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/offheap/OffHeapStorageJUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/offheap/OffHeapStorageJUnitTest.java
@@ -23,7 +23,7 @@ import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.InternalLocator;
-import com.gemstone.gemfire.internal.LocalStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.LocalStatisticsFactory;
import com.gemstone.gemfire.test.junit.categories.UnitTest;
import org.junit.Rule;
import org.junit.Test;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/CallbackSamplerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/CallbackSamplerJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/CallbackSamplerJUnitTest.java
deleted file mode 100644
index 47bfc58..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/CallbackSamplerJUnitTest.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal.statistics;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.*;
-
-import java.util.Arrays;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-
-import com.gemstone.gemfire.CancelCriterion;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.internal.StatSamplerStats;
-import com.gemstone.gemfire.internal.StatisticsImpl;
-import com.gemstone.gemfire.internal.StatisticsManager;
-import com.gemstone.gemfire.test.junit.categories.UnitTest;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.runner.RunWith;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.runners.MockitoJUnitRunner;
-
-@Category(UnitTest.class)
-@RunWith(MockitoJUnitRunner.class)
-public class CallbackSamplerJUnitTest {
- @Mock
- CancelCriterion cancelCriterion;
- @Mock
- StatSamplerStats statSamplerStats;
- @Mock
- StatisticsManager statisticsManager;
- @Mock
- ScheduledExecutorService executorService;
- private CallbackSampler sampler;
-
- @Before
- public void createSampler() {
- sampler = new CallbackSampler(cancelCriterion, statSamplerStats);
- }
-
- @Test
- public void taskShouldSampleStatistics() {
- Runnable sampleTask = invokeStartAndGetTask();
-
- StatisticsImpl stats1 = mock(StatisticsImpl.class);
- StatisticsImpl stats2 = mock(StatisticsImpl.class);
- when(stats1.invokeSuppliers()).thenReturn(3);
- when(stats2.invokeSuppliers()).thenReturn(2);
- when(stats1.getSupplierCount()).thenReturn(7);
- when(stats2.getSupplierCount()).thenReturn(8);
- when(statisticsManager.getStatsList()).thenReturn(Arrays.asList(stats1, stats2));
- sampleTask.run();
- verify(statSamplerStats).setSampleCallbacks(eq(15));
- verify(statSamplerStats).incSampleCallbackErrors(5);
- verify(statSamplerStats).incSampleCallbackDuration(anyLong());
- }
-
- @Test
- public void stopShouldStopExecutor() {
- sampler.start(executorService, statisticsManager, 1, TimeUnit.MILLISECONDS);
- sampler.stop();
- verify(executorService).shutdown();
- }
-
- @Test
- public void cancelCriterionShouldStopExecutor() {
- Runnable sampleTask = invokeStartAndGetTask();
- when(cancelCriterion.isCancelInProgress()).thenReturn(Boolean.TRUE);
- sampleTask.run();
- verify(executorService).shutdown();
- }
-
- private Runnable invokeStartAndGetTask() {
- sampler.start(executorService, statisticsManager, 1, TimeUnit.MILLISECONDS);
- ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
- verify(executorService).scheduleAtFixedRate(runnableCaptor.capture(), eq(1L), eq(1L), eq(TimeUnit.MILLISECONDS));
- return runnableCaptor.getValue();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/CallbackSamplerTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/CallbackSamplerTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/CallbackSamplerTest.java
new file mode 100644
index 0000000..fd442bb
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/CallbackSamplerTest.java
@@ -0,0 +1,98 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.mockito.Mockito.*;
+
+import java.util.Arrays;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.runners.MockitoJUnitRunner;
+
+import com.gemstone.gemfire.CancelCriterion;
+import com.gemstone.gemfire.test.junit.categories.UnitTest;
+
+/**
+ * Unit tests for {@link CallbackSampler}.
+ */
+@Category(UnitTest.class)
+@RunWith(MockitoJUnitRunner.class)
+public class CallbackSamplerTest {
+
+ @Mock
+ CancelCriterion cancelCriterion;
+ @Mock
+ StatSamplerStats statSamplerStats;
+ @Mock
+ StatisticsManager statisticsManager;
+ @Mock
+ ScheduledExecutorService executorService;
+
+ private CallbackSampler sampler;
+
+ @Before
+ public void createSampler() {
+ sampler = new CallbackSampler(cancelCriterion, statSamplerStats);
+ }
+
+ @Test
+ public void taskShouldSampleStatistics() {
+ Runnable sampleTask = invokeStartAndGetTask();
+
+ StatisticsImpl stats1 = mock(StatisticsImpl.class);
+ StatisticsImpl stats2 = mock(StatisticsImpl.class);
+ when(stats1.invokeSuppliers()).thenReturn(3);
+ when(stats2.invokeSuppliers()).thenReturn(2);
+ when(stats1.getSupplierCount()).thenReturn(7);
+ when(stats2.getSupplierCount()).thenReturn(8);
+ when(statisticsManager.getStatsList()).thenReturn(Arrays.asList(stats1, stats2));
+ sampleTask.run();
+ verify(statSamplerStats).setSampleCallbacks(eq(15));
+ verify(statSamplerStats).incSampleCallbackErrors(5);
+ verify(statSamplerStats).incSampleCallbackDuration(anyLong());
+ }
+
+ @Test
+ public void stopShouldStopExecutor() {
+ sampler.start(executorService, statisticsManager, 1, TimeUnit.MILLISECONDS);
+ sampler.stop();
+ verify(executorService).shutdown();
+ }
+
+ @Test
+ public void cancelCriterionShouldStopExecutor() {
+ Runnable sampleTask = invokeStartAndGetTask();
+ when(cancelCriterion.isCancelInProgress()).thenReturn(Boolean.TRUE);
+ sampleTask.run();
+ verify(executorService).shutdown();
+ }
+
+ private Runnable invokeStartAndGetTask() {
+ sampler.start(executorService, statisticsManager, 1, TimeUnit.MILLISECONDS);
+ ArgumentCaptor<Runnable> runnableCaptor = ArgumentCaptor.forClass(Runnable.class);
+ verify(executorService).scheduleAtFixedRate(runnableCaptor.capture(), eq(1L), eq(1L), eq(TimeUnit.MILLISECONDS));
+ return runnableCaptor.getValue();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/DistributedSystemStatisticsIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/DistributedSystemStatisticsIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/DistributedSystemStatisticsIntegrationTest.java
new file mode 100644
index 0000000..76763de
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/DistributedSystemStatisticsIntegrationTest.java
@@ -0,0 +1,271 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
+import static org.assertj.core.api.Assertions.*;
+
+import java.util.Properties;
+import java.util.Random;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsFactory;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.distributed.DistributedSystem;
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+
+/**
+ * Integration tests for {@link Statistics} as implemented by {@link DistributedSystem}.
+ */
+@Category(IntegrationTest.class)
+public class DistributedSystemStatisticsIntegrationTest {
+
+ private DistributedSystem system;
+
+ private String statName1;
+ private String statName2;
+ private String statName3;
+ private String[] statNames;
+
+ private Random random;
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUp() throws Exception {
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT, "0");
+ props.setProperty(LOCATORS, "");
+ props.setProperty(NAME, getUniqueName());
+
+ this.system = DistributedSystem.connect(props);
+
+ this.statName1 = "one";
+ this.statName2 = "two";
+ this.statName3 = "three";
+ this.statNames = new String[] { statName1, statName2, statName3 };
+
+ this.random = new Random();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ this.system.disconnect();
+ this.system = null;
+ }
+
+ /**
+ * Tests {@code int} statistics
+ */
+ @Test
+ public void testIntStatistics() {
+ Statistics stats = setUpIntStatistics(3);
+
+ for (int j = 0; j < this.statNames.length; j++) {
+ String statName = this.statNames[j];
+ for (int i = 0; i < 10; i++) {
+ stats.setInt(statName, i);
+ stats.incInt(statName, 1);
+ assertThat(stats.getInt(statName)).isEqualTo(i + 1);
+ }
+ }
+ }
+
+ /**
+ * Tests {@code long} statistics
+ */
+ @Test
+ public void testLongStatistics() {
+ Statistics stats = setUpLongStatistics(3);
+
+ // Set/get some random long values
+ for (int i = 0; i < 100; i++) {
+ for (int j = 0; j < this.statNames.length; j++) {
+ String statName = this.statNames[j];
+ long value = this.random.nextLong();
+ stats.setLong(statName, value);
+ assertThat(stats.getLong(statName)).isEqualTo(value);
+ }
+ }
+
+ // Increment by some random values
+ for (int i = 0; i < 100; i++) {
+ for (int j = 0; j < this.statNames.length; j++) {
+ String statName = this.statNames[j];
+ long inc = this.random.nextLong();
+ long before = stats.getLong(statName);
+ stats.incLong(statName, inc);
+ assertThat(stats.getLong(statName)).isEqualTo(before + inc);
+ }
+ }
+ }
+
+ /**
+ * Tests {@code double} statistics
+ */
+ @Test
+ public void testDoubleStatistics() {
+ Statistics stats = setUpDoubleStatistics(3);
+
+ // Set/get some random double values
+ for (int i = 0; i < 100; i++) {
+ for (int j = 0; j < this.statNames.length; j++) {
+ String statName = this.statNames[j];
+ double value = this.random.nextDouble();
+ stats.setDouble(statName, value);
+ assertThat(stats.getDouble(statName)).isEqualTo(value);
+ }
+ }
+
+ // Increment by some random values
+ for (int i = 0; i < 100; i++) {
+ for (int j = 0; j < this.statNames.length; j++) {
+ String statName = this.statNames[j];
+ double inc = this.random.nextDouble();
+ double before = stats.getDouble(statName);
+ stats.incDouble(statName, inc);
+ assertThat(stats.getDouble(statName)).isEqualTo(before + inc);
+ }
+ }
+ }
+
+ /**
+ * Tests that accessing an {@code int} stat throws the appropriate exceptions.
+ */
+ @Test
+ public void testAccessingIntStat() {
+ Statistics stats = setUpIntStatistics(1);
+
+ assertThat(stats.getInt(this.statName1)).isEqualTo(0);
+ assertThatThrownBy(() -> stats.getDouble(this.statName1)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.getLong(this.statName1)).isExactlyInstanceOf(IllegalArgumentException.class);
+
+ stats.setInt(this.statName1, 4);
+ assertThatThrownBy(() -> stats.setDouble(this.statName1, 4.0)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.setLong(this.statName1, 4L)).isExactlyInstanceOf(IllegalArgumentException.class);
+
+ stats.incInt(this.statName1, 4);
+ assertThatThrownBy(() -> stats.incDouble(this.statName1, 4.0)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.incLong(this.statName1, 4L)).isExactlyInstanceOf(IllegalArgumentException.class);
+ }
+
+ /**
+ * Tests that accessing a {@code long} stat throws the appropriate exceptions.
+ */
+ @Test
+ public void testAccessingLongStat() {
+ Statistics stats = setUpLongStatistics(1);
+
+ assertThat(stats.getLong(this.statName1)).isEqualTo(0L);
+ assertThatThrownBy(() -> stats.getDouble(this.statName1)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.getInt(this.statName1)).isExactlyInstanceOf(IllegalArgumentException.class);
+
+ stats.setLong(this.statName1, 4L);
+ assertThatThrownBy(() -> stats.setDouble(this.statName1, 4.0)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.setInt(this.statName1, 4)).isExactlyInstanceOf(IllegalArgumentException.class);
+
+ stats.incLong(this.statName1, 4L);
+ assertThatThrownBy(() -> stats.incDouble(this.statName1, 4.0)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.incInt(this.statName1, 4)).isExactlyInstanceOf(IllegalArgumentException.class);
+ }
+
+ /**
+ * Tests that accessing an {@code double} stat throws the appropriate exceptions.
+ */
+ @Test
+ public void testAccessingDoubleStat() {
+ Statistics stats = setUpDoubleStatistics(1);
+
+ assertThat(stats.getDouble(this.statName1)).isEqualTo(0.0);
+ assertThatThrownBy(() -> stats.getInt(this.statName1)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.getLong(this.statName1)).isExactlyInstanceOf(IllegalArgumentException.class);
+
+ stats.setDouble(this.statName1, 4.0);
+ assertThatThrownBy(() -> stats.setInt(this.statName1, 4)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.setLong(this.statName1, 4L)).isExactlyInstanceOf(IllegalArgumentException.class);
+
+ stats.incDouble(this.statName1, 4.0);
+ assertThatThrownBy(() -> stats.incInt(this.statName1, 4)).isExactlyInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> stats.incLong(this.statName1, 4L)).isExactlyInstanceOf(IllegalArgumentException.class);
+ }
+
+ private StatisticsFactory factory() {
+ return this.system;
+ }
+
+ private Statistics setUpIntStatistics(final int count) {
+ String[] descriptions = new String[] {"ONE", "TWO", "THREE"};
+ StatisticDescriptor[] descriptors = new StatisticDescriptor[count];
+ for (int i = 0; i < count; i++) {
+ descriptors[i] = factory().createIntGauge(this.statNames[i], descriptions[i], "x");
+ }
+
+ StatisticsType type = factory().createType(getUniqueName(), "", descriptors);
+ Statistics stats = factory().createStatistics(type, "Display");
+
+ for (int i = 0; i < count; i++) {
+ stats.setInt(this.statNames[i], 0);
+ }
+ return stats;
+ }
+
+ private Statistics setUpLongStatistics(final int count) {
+ String[] descriptions = new String[] {"ONE", "TWO", "THREE"};
+ StatisticDescriptor[] descriptors = new StatisticDescriptor[count];
+ for (int i = 0; i < count; i++) {
+ descriptors[i] = factory().createLongGauge(this.statNames[i], descriptions[i], "x");
+ }
+
+ StatisticsType type = factory().createType(getUniqueName(), "", descriptors);
+ Statistics stats = factory().createStatistics(type, "Display");
+
+ for (int i = 0; i < count; i++) {
+ stats.setLong(this.statNames[i], 0L);
+ }
+ return stats;
+ }
+
+ private Statistics setUpDoubleStatistics(final int count) {
+ String[] descriptions = new String[] {"ONE", "TWO", "THREE"};
+ StatisticDescriptor[] descriptors = new StatisticDescriptor[count];
+ for (int i = 0; i < count; i++) {
+ descriptors[i] = factory().createDoubleGauge(this.statNames[i], descriptions[i], "x");
+ }
+
+ StatisticsType type = factory().createType(getUniqueName(), "", descriptors);
+ Statistics stats = factory().createStatistics(type, "Display");
+
+ for (int i = 0; i < count; i++) {
+ stats.setDouble(this.statNames[i], 0.0);
+ }
+ return stats;
+ }
+
+ private String getUniqueName() {
+ return getClass().getSimpleName() + "_" + this.testName.getMethodName();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/DistributedSystemStatisticsTypeIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/DistributedSystemStatisticsTypeIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/DistributedSystemStatisticsTypeIntegrationTest.java
new file mode 100644
index 0000000..a87dd52
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/DistributedSystemStatisticsTypeIntegrationTest.java
@@ -0,0 +1,90 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
+import static org.assertj.core.api.Assertions.*;
+
+import java.util.Properties;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.StatisticsFactory;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.distributed.DistributedSystem;
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+
+/**
+ * Integration tests for {@link StatisticsType} as implemented by {@link DistributedSystem}.
+ */
+@Category(IntegrationTest.class)
+public class DistributedSystemStatisticsTypeIntegrationTest {
+
+ private DistributedSystem system;
+ private StatisticsType type;
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUp() throws Exception {
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT, "0");
+ props.setProperty(LOCATORS, "");
+ props.setProperty(NAME, getUniqueName());
+ this.system = DistributedSystem.connect(props);
+
+ StatisticDescriptor[] stats = {
+ factory().createIntGauge("test", "TEST", "ms")
+ };
+
+ this.type = factory().createType(getUniqueName(), "TEST", stats);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ this.system.disconnect();
+ this.system = null;
+ }
+
+ @Test
+ public void testNameToIdUnknownStatistic() {
+ assertThat(type.nameToId("test")).isEqualTo(0);
+ assertThatThrownBy(() -> type.nameToId("Fred")).isExactlyInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ public void testNameToDescriptorUnknownStatistic() {
+ assertThat(type.nameToDescriptor("test").getName()).isEqualTo("test");
+ assertThatThrownBy(() -> type.nameToDescriptor("Fred")).isExactlyInstanceOf(IllegalArgumentException.class);
+ }
+
+ private String getUniqueName() {
+ return getClass().getSimpleName() + "_" + this.testName.getMethodName();
+ }
+
+ private StatisticsFactory factory() {
+ return this.system;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/GemFireStatSamplerIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/GemFireStatSamplerIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/GemFireStatSamplerIntegrationTest.java
new file mode 100644
index 0000000..ff7c34d
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/GemFireStatSamplerIntegrationTest.java
@@ -0,0 +1,612 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
+import static org.junit.Assert.*;
+import static org.junit.Assume.*;
+
+import java.io.File;
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.logging.log4j.Logger;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.distributed.DistributedSystem;
+import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
+import com.gemstone.gemfire.internal.GemFireVersion;
+import com.gemstone.gemfire.internal.PureJavaMode;
+import com.gemstone.gemfire.internal.SocketCreator;
+import com.gemstone.gemfire.internal.cache.control.HeapMemoryMonitor;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler.LocalStatListenerImpl;
+import com.gemstone.gemfire.internal.statistics.platform.OsStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
+import com.gemstone.gemfire.internal.stats50.VMStats50;
+import com.gemstone.gemfire.internal.util.StopWatch;
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+
+/**
+ * Integration tests for {@link GemFireStatSampler}.
+ *
+ * @since GemFire 7.0
+ */
+@Category(IntegrationTest.class)
+public class GemFireStatSamplerIntegrationTest extends StatSamplerTestCase {
+
+ private static final Logger logger = LogService.getLogger();
+
+ private static final int STAT_SAMPLE_RATE = 1000;
+
+ private DistributedSystem system;
+ private File testDir;
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUp() throws Exception {
+ this.testDir = this.temporaryFolder.getRoot();
+ assertTrue(this.testDir.exists());
+ }
+
+ /**
+ * Removes the loner DistributedSystem at the end of each test.
+ */
+ @After
+ public void tearDown() throws Exception {
+ System.clearProperty(GemFireStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY);
+ disconnect();
+ }
+
+ /**
+ * Tests the majority of getters and the basic functionality of the sampler.
+ *
+ * This test is skipped when running on Windows 7 because ProcessStats is not created for this OS. See #45395.
+ */
+ @Test
+ public void testBasics() throws Exception {
+ final String osName = System.getProperty("os.name", "unknown");
+ assumeFalse(osName.equals("Windows 7"));
+
+ connect(createGemFireProperties());
+
+ GemFireStatSampler statSampler = getGemFireStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ assertEquals(0, statSampler.getArchiveFileSizeLimit());
+ assertEquals(0, statSampler.getArchiveDiskSpaceLimit());
+ assertEquals(STAT_SAMPLE_RATE, statSampler.getSampleRate());
+ assertEquals(true, statSampler.isSamplingEnabled());
+
+ int statsCount = statSampler.getStatisticsManager().getStatisticsCount();
+
+ assertEquals(statsCount, statSampler.getStatisticsModCount());
+ assertEquals(statsCount, statSampler.getStatisticsManager().getStatisticsCount());
+ assertEquals(statsCount, statSampler.getStatistics().length);
+
+ Assert.assertEquals(getStatisticsManager().getId(), statSampler.getSystemId());
+ assertTrue(statSampler.getSystemStartTime() < System.currentTimeMillis());
+ Assert.assertEquals(SocketCreator.getHostName(SocketCreator.getLocalHost()),
+ statSampler.getSystemDirectoryPath());
+
+ AllStatistics allStats = new AllStatistics(statSampler);
+
+ VMStatsContract vmStats = statSampler.getVMStats();
+ assertNotNull(vmStats);
+ assertTrue(vmStats instanceof VMStats50);
+ /* NOTE: VMStats50 is not an instance of Statistics but instead its
+ * instance contains 3 instances of Statistics:
+ * 1) vmStats
+ * 2) heapMemStats
+ * 3) nonHeapMemStats
+ */
+
+ Method getProcessStats = getGemFireStatSampler().getClass().getMethod("getProcessStats");
+ assertNotNull(getProcessStats);
+
+ ProcessStats processStats = statSampler.getProcessStats();
+ if (osName.equals("SunOS")) {
+ assertNotNull(processStats);
+ assertTrue(PureJavaMode.osStatsAreAvailable());
+ assertTrue(allStats.containsStatisticsType("SolarisProcessStats"));
+ assertTrue(allStats.containsStatisticsType("SolarisSystemStats"));
+ } else if (osName.startsWith("Windows")) {
+ // fails on Windows 7: 45395 "ProcessStats are not created on Windows 7"
+ assertNotNull("ProcessStats were not created on " + osName, processStats);
+ assertTrue(PureJavaMode.osStatsAreAvailable());
+ assertTrue(allStats.containsStatisticsType("WindowsProcessStats"));
+ assertTrue(allStats.containsStatisticsType("WindowsSystemStats"));
+ } else if (osName.startsWith("Linux")) {
+ assertNotNull(processStats);
+ assertTrue(PureJavaMode.osStatsAreAvailable());
+ assertTrue(allStats.containsStatisticsType("LinuxProcessStats"));
+ assertTrue(allStats.containsStatisticsType("LinuxSystemStats"));
+ } else if (osName.equals("Mac OS X")) {
+ assertNull(processStats);
+ assertFalse(PureJavaMode.osStatsAreAvailable());
+ assertFalse(allStats.containsStatisticsType("OSXProcessStats"));
+ assertFalse(allStats.containsStatisticsType("OSXSystemStats"));
+ } else {
+ assertNull(processStats);
+ }
+
+ String productDesc = statSampler.getProductDescription();
+ assertTrue(productDesc.contains(GemFireVersion.getGemFireVersion()));
+ assertTrue(productDesc.contains(GemFireVersion.getBuildId()));
+ assertTrue(productDesc.contains(GemFireVersion.getSourceDate()));
+ }
+
+ /**
+ * Tests that the configured archive file is created and exists.
+ */
+ @Test
+ public void testArchiveFileExists() throws Exception {
+ final String dir = this.testDir.getAbsolutePath();
+ final String archiveFileName = dir + File.separator + this.testName.getMethodName() + ".gfs";
+
+ final File archiveFile1 = new File(dir + File.separator + this.testName.getMethodName() + ".gfs");
+
+ Properties props = createGemFireProperties();
+ props.setProperty(STATISTIC_ARCHIVE_FILE, archiveFileName);
+ connect(props);
+
+ GemFireStatSampler statSampler = getGemFireStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ final File archiveFile = statSampler.getArchiveFileName();
+ assertNotNull(archiveFile);
+ assertEquals(archiveFile1, archiveFile);
+
+ waitForFileToExist(archiveFile, 5000, 10);
+
+ assertTrue("File name incorrect: archiveFile.getName()=" + archiveFile.getName() +
+ " archiveFile.getAbsolutePath()=" + archiveFile.getAbsolutePath() +
+ " getCanonicalPath()" + archiveFile.getCanonicalPath(),
+ archiveFileName.contains(archiveFile.getName()));
+ }
+
+ /**
+ * Tests the statistics sample rate within an acceptable margin of error.
+ */
+ @Test
+ public void testSampleRate() throws Exception {
+ connect(createGemFireProperties());
+
+ GemFireStatSampler statSampler = getGemFireStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ assertEquals(STAT_SAMPLE_RATE, statSampler.getSampleRate());
+
+ assertTrue(getStatisticsManager().getStatListModCount() > 0);
+
+ List<Statistics> statistics = getStatisticsManager().getStatsList();
+ assertNotNull(statistics);
+ assertTrue(statistics.size() > 0);
+
+ StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
+ Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
+ assertEquals(1, statsArray.length);
+
+ final Statistics statSamplerStats = statsArray[0];
+ final int initialSampleCount = statSamplerStats.getInt("sampleCount");
+ final int expectedSampleCount = initialSampleCount + 2;
+
+ waitForExpectedStatValue(statSamplerStats, "sampleCount", expectedSampleCount, 5000, 10);
+ }
+
+ /**
+ * Adds a LocalStatListener for an individual stat. Validates that it
+ * receives notifications. Removes the listener and validates that it
+ * was in fact removed and no longer receives notifications.
+ */
+ @Test
+ public void testLocalStatListener() throws Exception {
+ connect(createGemFireProperties());
+
+ GemFireStatSampler statSampler = getGemFireStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ Method getLocalListeners = getGemFireStatSampler().getClass().getMethod("getLocalListeners");
+ assertNotNull(getLocalListeners);
+
+ Method addLocalStatListener = getGemFireStatSampler().getClass().getMethod("addLocalStatListener", LocalStatListener.class, Statistics.class, String.class);
+ assertNotNull(addLocalStatListener);
+
+ Method removeLocalStatListener = getGemFireStatSampler().getClass().getMethod("removeLocalStatListener", LocalStatListener.class);
+ assertNotNull(removeLocalStatListener);
+
+ // validate that there are no listeners
+ assertTrue(statSampler.getLocalListeners().isEmpty());
+
+ // add a listener for sampleCount stat in StatSampler statistics
+ StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
+ Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
+ assertEquals(1, statsArray.length);
+
+ final Statistics statSamplerStats = statsArray[0];
+ final String statName = "sampleCount";
+ final AtomicInteger sampleCountValue = new AtomicInteger(0);
+ final AtomicInteger sampleCountChanged = new AtomicInteger(0);
+
+ LocalStatListener listener = new LocalStatListener() {
+ public void statValueChanged(double value) {
+ sampleCountValue.set((int)value);
+ sampleCountChanged.incrementAndGet();
+ }
+ };
+
+ statSampler.addLocalStatListener(listener, statSamplerStats, statName);
+ assertTrue(statSampler.getLocalListeners().size() == 1);
+
+ // there's a level of indirection here and some protected member fields
+ LocalStatListenerImpl lsli = (LocalStatListenerImpl)
+ statSampler.getLocalListeners().iterator().next();
+ assertEquals("sampleCount", lsli.stat.getName());
+
+ // wait for the listener to update 4 times
+ final int expectedChanges = 4;
+ boolean done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 5000; done = (sampleCountChanged.get() >= expectedChanges)) {
+ Thread.sleep(10);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertTrue("Waiting for sampleCountChanged >= " + expectedChanges, done);
+
+ // validate that the listener fired and updated the value
+ assertTrue(sampleCountValue.get() > 0);
+ assertTrue(sampleCountChanged.get() >= expectedChanges);
+
+ // remove the listener
+ statSampler.removeLocalStatListener(listener);
+ final int expectedSampleCountValue = sampleCountValue.get();
+ final int expectedSampleCountChanged = sampleCountChanged.get();
+
+ // validate that there are no listeners now
+ assertTrue(statSampler.getLocalListeners().isEmpty());
+
+ // wait for 2 stat samples to occur
+ waitForStatSample(statSamplerStats, expectedSampleCountValue, 5000, 10);
+
+ // validate that the listener did not fire
+ assertEquals(expectedSampleCountValue, sampleCountValue.get());
+ assertEquals(expectedSampleCountChanged, sampleCountChanged.get());
+ }
+
+ /**
+ * Invokes stop() and then validates that the sampler did in fact stop.
+ */
+ @Test
+ public void testStop() throws Exception {
+ connect(createGemFireProperties());
+
+ GemFireStatSampler statSampler = getGemFireStatSampler();
+ assertTrue(statSampler.waitForInitialization(5000));
+
+ // validate the stat sampler is running
+ StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
+ Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
+ assertEquals(1, statsArray.length);
+
+ final Statistics statSamplerStats = statsArray[0];
+ final int initialSampleCount = statSamplerStats.getInt("sampleCount");
+ final int expectedSampleCount = initialSampleCount + 2;
+
+ waitForStatSample(statSamplerStats, expectedSampleCount, 20000, 10);
+
+ // stop the stat sampler
+ statSampler.stop();
+
+ // validate the stat sampler has stopped
+ final int stoppedSampleCount = statSamplerStats.getInt("sampleCount");
+
+ // the following should timeout rather than complete
+ assertStatValueDoesNotChange(statSamplerStats, "sampleCount", stoppedSampleCount, 5000, 10);
+
+ assertEquals(stoppedSampleCount, statSamplerStats.getInt("sampleCount"));
+ }
+
+ /**
+ * Verifies that archive rolling works correctly when archive-file-size-limit
+ * is specified.
+ */
+ @Test
+ public void testArchiveRolling() throws Exception {
+ final String dirName = this.testDir.getAbsolutePath() + File.separator + this.testName;
+ new File(dirName).mkdirs();
+ final String archiveFileName = dirName + File.separator + this.testName + ".gfs";
+
+ final File archiveFile = new File(archiveFileName);
+ final File archiveFile1 = new File(dirName + File.separator + this.testName + "-01-01.gfs");
+ final File archiveFile2 = new File(dirName + File.separator + this.testName + "-01-02.gfs");
+ final File archiveFile3 = new File(dirName + File.separator + this.testName + "-01-03.gfs");
+
+ // set the system property to use KB instead of MB for file size
+ System.setProperty(HostStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY, "true");
+ Properties props = createGemFireProperties();
+ props.setProperty(ARCHIVE_FILE_SIZE_LIMIT, "1");
+ props.setProperty(ARCHIVE_DISK_SPACE_LIMIT, "0");
+ props.setProperty(STATISTIC_ARCHIVE_FILE, archiveFileName);
+ connect(props);
+
+ assertTrue(getGemFireStatSampler().waitForInitialization(5000));
+
+ boolean done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 4000; done = (getSampleCollector() != null && getSampleCollector().getStatArchiveHandler() != null)) {
+ Thread.sleep(10);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertTrue("Waiting for getSampleCollector().getStatArchiveHandler() to not be null", done);
+
+ StatArchiveHandler statArchiveHandler = getSampleCollector().getStatArchiveHandler();
+ StatArchiveHandlerConfig config = statArchiveHandler.getStatArchiveHandlerConfig();
+ assertEquals(1 * 1024, config.getArchiveFileSizeLimit());
+
+ waitForFileToExist(archiveFile, 4000, 10);
+ waitForFileToExist(archiveFile1, 4000, 10);
+ waitForFileToExist(archiveFile2, 4000, 10);
+ waitForFileToExist(archiveFile3, 4000, 10);
+ }
+
+ /**
+ * Verifies that archive removal works correctly when archive-disk-space-limit
+ * is specified.
+ */
+ @Test
+ public void testArchiveRemoval() throws Exception {
+ final String dirName = this.testDir.getAbsolutePath();// + File.separator + this.testName;
+ new File(dirName).mkdirs();
+ final String archiveFileName = dirName + File.separator + this.testName + ".gfs";
+
+ final File archiveFile = new File(archiveFileName);
+ final File archiveFile1 = new File(dirName + File.separator + this.testName + "-01-01.gfs");
+ final File archiveFile2 = new File(dirName + File.separator + this.testName + "-01-02.gfs");
+ final File archiveFile3 = new File(dirName + File.separator + this.testName + "-01-03.gfs");
+ final File archiveFile4 = new File(dirName + File.separator + this.testName + "-01-04.gfs");
+
+ final int sampleRate = 1000;
+
+ // set the system property to use KB instead of MB for file size
+ System.setProperty(HostStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY, "true");
+ Properties props = createGemFireProperties();
+ props.setProperty(STATISTIC_ARCHIVE_FILE, archiveFileName);
+ props.setProperty(ARCHIVE_FILE_SIZE_LIMIT, "1");
+ props.setProperty(ARCHIVE_DISK_SPACE_LIMIT, "12");
+ props.setProperty(STATISTIC_SAMPLE_RATE, String.valueOf(sampleRate));
+ connect(props);
+
+ assertTrue(getGemFireStatSampler().waitForInitialization(5000));
+
+ boolean exists1 = false;
+ boolean exists2 = false;
+ boolean exists3 = false;
+ boolean exists4 = false;
+ boolean exists = false;
+ boolean done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 10*sampleRate;) {
+ exists1 = exists1 || archiveFile1.exists();
+ exists2 = exists2 || archiveFile2.exists();
+ exists3 = exists3 || archiveFile3.exists();
+ exists4 = exists4 || archiveFile4.exists();
+ exists = exists || archiveFile.exists();
+ done = exists1 && exists2 && exists3 && exists4 && exists;
+ if (!done) {
+ Thread.sleep(10);
+ }
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertTrue("Waiting for archive files to exist:"
+ + " exists1=" + exists1
+ + " exists2=" + exists2
+ + " exists3=" + exists3
+ + " exists4=" + exists4
+ + " exists=" + exists, done);
+
+ waitForFileToDelete(archiveFile1, 10*sampleRate, 10);
+ }
+
+ @Test
+ public void testLocalStatListenerRegistration() throws Exception {
+ connect(createGemFireProperties());
+
+ final GemFireStatSampler statSampler = getGemFireStatSampler();
+ statSampler.waitForInitialization(5000);
+
+ final AtomicBoolean flag = new AtomicBoolean(false);
+ final LocalStatListener listener = new LocalStatListener(){
+ public void statValueChanged(double value) {
+ flag.set(true);
+ }
+ };
+
+ final String tenuredPoolName = HeapMemoryMonitor.getTenuredMemoryPoolMXBean().getName();
+ logger.info("TenuredPoolName: {}", tenuredPoolName);
+
+ final List<Statistics> list = ((StatisticsManager)this.system).getStatsList();
+ assertFalse(list.isEmpty());
+
+ boolean done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 5000;) {
+ Thread.sleep(10);
+ int i=0;
+ synchronized (list) {
+ for (Object obj : list) {
+ ++i;
+ logger.info("List:{}:{}", i, obj);
+ if (obj instanceof StatisticsImpl) {
+ StatisticsImpl si = (StatisticsImpl)obj;
+ logger.info("stat:{}", si.getTextId());
+ if (si.getTextId().contains(tenuredPoolName)) {
+ statSampler.addLocalStatListener(listener, si, "currentUsedMemory");
+ done = true;
+ }
+ }
+ }
+ }
+ //done = false;
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertTrue("Waiting for " + tenuredPoolName + " statistics to be added to create listener for", done);
+
+ assertTrue("expected at least one stat listener, found " +
+ statSampler.getLocalListeners().size(),
+ statSampler.getLocalListeners().size() > 0);
+
+ long maxTenuredMemory = HeapMemoryMonitor.getTenuredMemoryPoolMXBean()
+ .getUsage().getMax();
+
+ //byte[] bytes = new byte[1024 * 1024 * 10];
+ byte[] bytes = new byte[(int)(maxTenuredMemory*0.01)];
+ Arrays.fill(bytes, Byte.MAX_VALUE);
+
+ done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 5000; done = (flag.get())) {
+ Thread.sleep(10);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertTrue("Waiting for listener to set flag to true", done);
+ }
+
+ @Override
+ protected StatisticsManager getStatisticsManager() {
+ return (InternalDistributedSystem)this.system;
+ }
+
+ protected OsStatisticsFactory getOsStatisticsFactory() {
+ return (InternalDistributedSystem)this.system;
+ }
+
+ private GemFireStatSampler getGemFireStatSampler() {
+ return ((InternalDistributedSystem)this.system).getStatSampler();
+ }
+
+ private SampleCollector getSampleCollector() {
+ return getGemFireStatSampler().getSampleCollector();
+ }
+
+ private Properties createGemFireProperties() {
+ Properties props = new Properties();
+ props.setProperty(STATISTIC_SAMPLING_ENABLED, "true"); // TODO: test true/false
+ props.setProperty(ENABLE_TIME_STATISTICS, "true"); // TODO: test true/false
+ props.setProperty(STATISTIC_SAMPLE_RATE, String.valueOf(STAT_SAMPLE_RATE));
+ props.setProperty(ARCHIVE_FILE_SIZE_LIMIT, "0");
+ props.setProperty(ARCHIVE_DISK_SPACE_LIMIT, "0");
+ props.setProperty(MCAST_PORT, "0");
+ props.setProperty(LOCATORS, "");
+ return props;
+ }
+
+ /**
+ * Creates a fresh loner DistributedSystem for each test. Note
+ * that the DistributedSystem is the StatisticsManager/Factory/etc.
+ */
+ @SuppressWarnings("deprecation")
+ private void connect(Properties props) {
+ this.system = DistributedSystem.connect(props);
+ }
+
+ @SuppressWarnings("deprecation")
+ private void disconnect() {
+ if (this.system != null) {
+ this.system.disconnect();
+ this.system = null;
+ }
+ }
+
+// public static class AsyncInvoker {
+// public static AsyncInvocation invokeAsync(Runnable r) {
+// return invokeAsync(r, "run", new Object[0]);
+// }
+// public static AsyncInvocation invokeAsync(Callable c) {
+// return invokeAsync(c, "call", new Object[0]);
+// }
+// public static AsyncInvocation invokeAsync(
+// final Object o, final String methodName, final Object[] args) {
+// AsyncInvocation ai =
+// new AsyncInvocation(o, methodName, new Runnable() {
+// public void run() {
+// MethExecutorResult result =
+// MethExecutor.executeObject(o, methodName, args);
+// if (result.exceptionOccurred()) {
+// throw new AsyncInvocationException(result.getException());
+// }
+// AsyncInvocation.setReturnValue(result.getResult());
+// }
+// });
+// ai.start();
+// return ai;
+// }
+//
+// public static class AsyncInvocationException extends RuntimeException {
+// private static final long serialVersionUID = -5522299018650622945L;
+// /**
+// * Creates a new <code>AsyncInvocationException</code>.
+// */
+// public AsyncInvocationException(String message) {
+// super(message);
+// }
+//
+// /**
+// * Creates a new <code>AsyncInvocationException</code> that was
+// * caused by a given exception
+// */
+// public AsyncInvocationException(String message, Throwable thr) {
+// super(message, thr);
+// }
+//
+// /**
+// * Creates a new <code>AsyncInvocationException</code> that was
+// * caused by a given exception
+// */
+// public AsyncInvocationException(Throwable thr) {
+// super(thr.getMessage(), thr);
+// }
+// }
+// }
+}
[15/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifierStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifierStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifierStats.java
index afc4235..36c22b6 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifierStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifierStats.java
@@ -21,8 +21,7 @@ import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
/**
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientProxyStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientProxyStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientProxyStats.java
index cf69d90..7812a3a 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientProxyStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientProxyStats.java
@@ -22,7 +22,7 @@ import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
/**
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientUpdater.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientUpdater.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientUpdater.java
index 391c3e6..26efd4d 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientUpdater.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientUpdater.java
@@ -45,6 +45,7 @@ import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
import com.gemstone.gemfire.internal.offheap.annotations.Released;
import com.gemstone.gemfire.internal.sequencelog.EntryLogger;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.security.AuthenticationFailedException;
import com.gemstone.gemfire.security.AuthenticationRequiredException;
import com.gemstone.gemfire.security.GemFireSecurityException;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java
index 626e075..360a87c 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheServerStats.java
@@ -14,14 +14,8 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
-/**
- * Bridge Server statistic definitions
- */
package com.gemstone.gemfire.internal.cache.tier.sockets;
-import java.net.InetAddress;
-
import com.gemstone.gemfire.StatisticDescriptor;
import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
@@ -29,10 +23,11 @@ import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.cache.server.ServerLoad;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.PoolStatHelper;
-import com.gemstone.gemfire.internal.DummyStatisticsFactory;
import com.gemstone.gemfire.internal.SocketCreator;
-import com.gemstone.gemfire.internal.util.ArrayUtils;
+/**
+ * Bridge Server statistic definitions
+ */
public class CacheServerStats implements MessageStats {
private static final String typeName = "CacheServerStats";
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/wan/GatewaySenderStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/wan/GatewaySenderStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/wan/GatewaySenderStats.java
index 15a6dee..1044456 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/wan/GatewaySenderStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/wan/GatewaySenderStats.java
@@ -22,7 +22,7 @@ import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.CachePerfStats;
public class GatewaySenderStats {
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/concurrent/Atomics.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/concurrent/Atomics.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/concurrent/Atomics.java
index 8940a69..9475059 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/concurrent/Atomics.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/concurrent/Atomics.java
@@ -20,9 +20,9 @@ package com.gemstone.gemfire.internal.concurrent;
import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import com.gemstone.gemfire.internal.LocalStatisticsImpl;
-import com.gemstone.gemfire.internal.StatisticsManager;
-import com.gemstone.gemfire.internal.StatisticsTypeImpl;
+import com.gemstone.gemfire.internal.statistics.LocalStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsManager;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeImpl;
import com.gemstone.gemfire.internal.stats50.Atomic50StatisticsImpl;
import java.util.concurrent.atomic.AtomicLong;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/offheap/OffHeapStorage.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/offheap/OffHeapStorage.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/offheap/OffHeapStorage.java
index bc7fb6a..449e05a 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/offheap/OffHeapStorage.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/offheap/OffHeapStorage.java
@@ -24,7 +24,7 @@ import com.gemstone.gemfire.distributed.internal.DistributionStats;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.InternalLocator;
import com.gemstone.gemfire.internal.ClassPathLoader;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import java.lang.reflect.Method;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/AbstractStatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/AbstractStatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/AbstractStatisticsFactory.java
new file mode 100755
index 0000000..fb07d45
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/AbstractStatisticsFactory.java
@@ -0,0 +1,327 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsFactory;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.StatisticsTypeFactory;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * An abstract standalone implementation of {@link StatisticsFactory}.
+ * It can be used in contexts that do not have the GemFire product
+ * or in vm's that do not have a distributed system nor a gemfire connection.
+ *
+ * @since GemFire 7.0
+ */
+public abstract class AbstractStatisticsFactory
+ implements StatisticsFactory, StatisticsManager {
+
+ private final long id;
+ private final String name;
+ private final CopyOnWriteArrayList<Statistics> statsList;
+ private int statsListModCount = 0;
+ private long statsListUniqueId = 1;
+ private final Object statsListUniqueIdLock;
+ private final StatisticsTypeFactory tf;
+ private final long startTime;
+
+ public AbstractStatisticsFactory(long id, String name, long startTime) {
+ this.id = id;
+ this.name = name;
+ this.startTime = startTime;
+
+ this.statsList = new CopyOnWriteArrayList<Statistics>();
+ this.statsListUniqueIdLock = new Object();
+ this.tf = StatisticsTypeFactoryImpl.singleton();
+ }
+
+ public void close() {
+ }
+
+ @Override
+ public final String getName() {
+ return this.name;
+ }
+
+ @Override
+ public final long getId() {
+ return this.id;
+ }
+
+ @Override
+ public final long getStartTime() {
+ return this.startTime;
+ }
+
+ @Override
+ public final int getStatListModCount() {
+ return this.statsListModCount;
+ }
+
+ @Override
+ public final List<Statistics> getStatsList() {
+ return this.statsList;
+ }
+
+ @Override
+ public final int getStatisticsCount() {
+ int result = 0;
+ List<Statistics> statsList = this.statsList;
+ if (statsList != null) {
+ result = statsList.size();
+ }
+ return result;
+ }
+
+ @Override
+ public final Statistics findStatistics(long id) {
+ List<Statistics> statsList = this.statsList;
+ synchronized (statsList) {
+ for (Statistics s : statsList) {
+ if (s.getUniqueId() == id) {
+ return s;
+ }
+ }
+ }
+ throw new RuntimeException(LocalizedStrings.PureStatSampler_COULD_NOT_FIND_STATISTICS_INSTANCE.toLocalizedString());
+ }
+
+ @Override
+ public final boolean statisticsExists(long id) {
+ List<Statistics> statsList = this.statsList;
+ for (Statistics s : statsList) {
+ if (s.getUniqueId() == id) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Override
+ public final Statistics[] getStatistics() {
+ List<Statistics> statsList = this.statsList;
+ return (Statistics[])statsList.toArray(new Statistics[statsList.size()]);
+ }
+
+ // StatisticsFactory methods
+
+ @Override
+ public final Statistics createStatistics(StatisticsType type) {
+ return createOsStatistics(type, null, 0, 0);
+ }
+
+ @Override
+ public final Statistics createStatistics(StatisticsType type, String textId) {
+ return createOsStatistics(type, textId, 0, 0);
+ }
+
+ @Override
+ public final Statistics createStatistics(StatisticsType type, String textId, long numericId) {
+ return createOsStatistics(type, textId, 0, 0);
+ }
+
+ protected Statistics createOsStatistics(StatisticsType type, String textId, long numericId, int osStatFlags) {
+ long myUniqueId;
+ synchronized (statsListUniqueIdLock) {
+ myUniqueId = statsListUniqueId++; // fix for bug 30597
+ }
+ Statistics result = new LocalStatisticsImpl(type, textId, numericId, myUniqueId, false, osStatFlags, this);
+ synchronized (statsList) {
+ statsList.add(result);
+ statsListModCount++;
+ }
+ return result;
+ }
+
+ @Override
+ public final Statistics[] findStatisticsByType(StatisticsType type) {
+ List<Statistics> hits = new ArrayList<Statistics>();
+ Iterator<Statistics> it = statsList.iterator();
+ while (it.hasNext()) {
+ Statistics s = (Statistics)it.next();
+ if (type == s.getType()) {
+ hits.add(s);
+ }
+ }
+ Statistics[] result = new Statistics[hits.size()];
+ return (Statistics[])hits.toArray(result);
+ }
+
+ @Override
+ public final Statistics[] findStatisticsByTextId(String textId) {
+ List<Statistics> hits = new ArrayList<Statistics>();
+ Iterator<Statistics> it = statsList.iterator();
+ while (it.hasNext()) {
+ Statistics s = (Statistics)it.next();
+ if (s.getTextId().equals(textId)) {
+ hits.add(s);
+ }
+ }
+ Statistics[] result = new Statistics[hits.size()];
+ return (Statistics[])hits.toArray(result);
+ }
+
+ @Override
+ public final Statistics[] findStatisticsByNumericId(long numericId) {
+ List<Statistics> hits = new ArrayList<Statistics>();
+ Iterator<Statistics> it = statsList.iterator();
+ while (it.hasNext()) {
+ Statistics s = (Statistics)it.next();
+ if (numericId == s.getNumericId()) {
+ hits.add(s);
+ }
+ }
+ Statistics[] result = new Statistics[hits.size()];
+ return (Statistics[])hits.toArray(result);
+ }
+
+ public final Statistics findStatisticsByUniqueId(long uniqueId) {
+ Iterator<Statistics> it = statsList.iterator();
+ while (it.hasNext()) {
+ Statistics s = (Statistics)it.next();
+ if (uniqueId == s.getUniqueId()) {
+ return s;
+ }
+ }
+ return null;
+ }
+
+ /** for internal use only. Its called by {@link LocalStatisticsImpl#close}. */
+ @Override
+ public final void destroyStatistics(Statistics stats) {
+ synchronized (statsList) {
+ if (statsList.remove(stats)) {
+ statsListModCount++;
+ }
+ }
+ }
+
+ @Override
+ public final Statistics createAtomicStatistics(StatisticsType type) {
+ return createAtomicStatistics(type, null, 0);
+ }
+
+ @Override
+ public final Statistics createAtomicStatistics(StatisticsType type, String textId) {
+ return createAtomicStatistics(type, textId, 0);
+ }
+
+ @Override
+ public Statistics createAtomicStatistics(StatisticsType type, String textId, long numericId) {
+ long myUniqueId;
+ synchronized (statsListUniqueIdLock) {
+ myUniqueId = statsListUniqueId++; // fix for bug 30597
+ }
+ Statistics result = StatisticsImpl.createAtomicNoOS(type, textId, numericId, myUniqueId, this);
+ synchronized (statsList) {
+ statsList.add(result);
+ statsListModCount++;
+ }
+ return result;
+ }
+
+ // StatisticsTypeFactory methods
+
+ /**
+ * Creates or finds a StatisticType for the given shared class.
+ */
+ @Override
+ public final StatisticsType createType(String name, String description, StatisticDescriptor[] stats) {
+ return tf.createType(name, description, stats);
+ }
+
+ @Override
+ public final StatisticsType findType(String name) {
+ return tf.findType(name);
+ }
+
+ @Override
+ public final StatisticsType[] createTypesFromXml(Reader reader)
+ throws IOException {
+ return tf.createTypesFromXml(reader);
+ }
+
+ @Override
+ public final StatisticDescriptor createIntCounter(String name, String description, String units) {
+ return tf.createIntCounter(name, description, units);
+ }
+
+ @Override
+ public final StatisticDescriptor createLongCounter(String name, String description, String units) {
+ return tf.createLongCounter(name, description, units);
+ }
+
+ @Override
+ public final StatisticDescriptor createDoubleCounter(String name, String description, String units) {
+ return tf.createDoubleCounter(name, description, units);
+ }
+
+ @Override
+ public final StatisticDescriptor createIntGauge(String name, String description, String units) {
+ return tf.createIntGauge(name, description, units);
+ }
+
+ @Override
+ public final StatisticDescriptor createLongGauge(String name, String description, String units) {
+ return tf.createLongGauge(name, description, units);
+ }
+
+ @Override
+ public final StatisticDescriptor createDoubleGauge(String name, String description, String units) {
+ return tf.createDoubleGauge(name, description, units);
+ }
+
+ @Override
+ public final StatisticDescriptor createIntCounter(String name, String description, String units, boolean largerBetter) {
+ return tf.createIntCounter(name, description, units, largerBetter);
+ }
+
+ @Override
+ public final StatisticDescriptor createLongCounter(String name, String description, String units, boolean largerBetter) {
+ return tf.createLongCounter(name, description, units, largerBetter);
+ }
+
+ @Override
+ public final StatisticDescriptor createDoubleCounter(String name, String description, String units, boolean largerBetter) {
+ return tf.createDoubleCounter(name, description, units, largerBetter);
+ }
+
+ @Override
+ public final StatisticDescriptor createIntGauge(String name, String description, String units, boolean largerBetter) {
+ return tf.createIntGauge(name, description, units, largerBetter);
+ }
+
+ @Override
+ public final StatisticDescriptor createLongGauge(String name, String description, String units, boolean largerBetter) {
+ return tf.createLongGauge(name, description, units, largerBetter);
+ }
+
+ @Override
+ public final StatisticDescriptor createDoubleGauge(String name, String description, String units, boolean largerBetter) {
+ return tf.createDoubleGauge(name, description, units, largerBetter);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ArchiveSplitter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ArchiveSplitter.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ArchiveSplitter.java
new file mode 100644
index 0000000..14aadf1
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/ArchiveSplitter.java
@@ -0,0 +1,522 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+
+import java.io.*;
+//import java.text.*;
+//import java.util.*;
+import java.util.zip.*;
+
+/**
+ * ArchiveSplitter provides APIs to read statistic snapshots from an archive
+ * file.
+ */
+public class ArchiveSplitter implements StatArchiveFormat {
+ private final File archiveName;
+ private InputStream is;
+ private MyFilterInputStream myIs;
+ private DataInputStream dataIn;
+ private DataOutputStream dataOut;
+ private OutputStream output;
+ private final static int BUFFER_SIZE = 1024*1024;
+ private long splitDuration; // in millis
+ private byte[][] resourceTypes = new byte[256][];
+ private byte[][] resourceInstanceTypeCodes = new byte[256][];
+ private byte[][] resourceInstanceTokens = new byte[256][];
+ private long[][] resourceInstanceBits = new long[256][];
+ private static final long DEFAULT_SPLIT_DURATION = 24*60*60*1000; // one day
+ private long currentDuration = 0; // in millis
+ private int splitCount = 0;
+ private byte[][] globalTokens = new byte[256][];
+ private int globalTokenCount = 0;
+
+ // header info
+ private byte archiveVersion;
+ private long startTimeStamp;
+ private long systemId;
+ private long systemStartTimeStamp;
+ private int timeZoneOffset;
+ private String timeZoneName;
+ private String systemDirectory;
+ private String productVersion;
+ private String os;
+ private String machine;
+
+
+ public ArchiveSplitter(File archiveName) throws IOException {
+ this(archiveName, DEFAULT_SPLIT_DURATION);
+ }
+ public ArchiveSplitter(File archiveName, long splitDuration) throws IOException {
+ this.archiveName = archiveName;
+ this.splitDuration = splitDuration;
+ this.is = new FileInputStream(archiveName);
+ boolean compressed = archiveName.getPath().endsWith(".gz");
+ if (compressed) {
+ this.myIs = new MyFilterInputStream(new BufferedInputStream(new GZIPInputStream(this.is, BUFFER_SIZE), BUFFER_SIZE));
+ } else {
+ this.myIs = new MyFilterInputStream(new BufferedInputStream(this.is, BUFFER_SIZE));
+ }
+ this.dataIn = new DataInputStream(this.myIs);
+ }
+ private void readHeaderToken() throws IOException {
+ byte archiveVersion = dataIn.readByte();
+ if (archiveVersion <= 1) {
+ throw new GemFireIOException(LocalizedStrings.ArchiveSplitter_ARCHIVE_VERSION_0_IS_NO_LONGER_SUPPORTED.toLocalizedString(new Byte(archiveVersion)), null);
+ }
+ if (archiveVersion > ARCHIVE_VERSION) {
+ throw new GemFireIOException(LocalizedStrings.ArchiveSplitter_UNSUPPORTED_ARCHIVE_VERSION_0_THE_SUPPORTED_VERSION_IS_1.toLocalizedString(new Object[] {new Byte(archiveVersion), new Byte(ARCHIVE_VERSION)}), null);
+ }
+
+ this.archiveVersion = archiveVersion;
+ this.startTimeStamp = dataIn.readLong();
+ this.systemId = dataIn.readLong();
+ this.systemStartTimeStamp = dataIn.readLong();
+ this.timeZoneOffset = dataIn.readInt();
+ this.timeZoneName = dataIn.readUTF();
+ this.systemDirectory = dataIn.readUTF();
+ this.productVersion = dataIn.readUTF();
+ this.os = dataIn.readUTF();
+ this.machine = dataIn.readUTF();
+ }
+ private void skipBytes(int count) throws IOException {
+ int skipped = dataIn.skipBytes(count);
+ while (skipped != count) {
+ count -= skipped;
+ skipped = dataIn.skipBytes(count);
+ }
+ }
+ private void skipBoolean() throws IOException {
+ //dataIn.readBoolean();
+ skipBytes(1);
+ }
+// private void skipByte() throws IOException {
+// //dataIn.readByte();
+// skipBytes(1);
+// }
+// private void skipUByte() throws IOException {
+// //dataIn.readUnsignedByte();
+// skipBytes(1);
+// }
+// private void skipShort() throws IOException {
+// //dataIn.readShort();
+// skipBytes(2);
+// }
+// private void skipUShort() throws IOException {
+// //dataIn.readUnsignedShort();
+// skipBytes(2);
+// }
+// private void skipInt() throws IOException {
+// //dataIn.readInt();
+// skipBytes(4);
+// }
+ private void skipLong() throws IOException {
+ //dataIn.readLong();
+ skipBytes(8);
+ }
+ private void skipUTF() throws IOException {
+ //dataIn.readUTF();
+ skipBytes(dataIn.readUnsignedShort());
+ }
+ private void addGlobalToken(byte[] token) {
+ if (globalTokenCount >= globalTokens.length) {
+ byte[][] tmp = new byte[globalTokenCount+128][];
+ System.arraycopy(globalTokens, 0, tmp, 0, globalTokens.length);
+ globalTokens = tmp;
+ }
+ globalTokens[globalTokenCount] = token;
+ globalTokenCount += 1;
+ }
+ private void readResourceTypeToken() throws IOException {
+ int resourceTypeId = dataIn.readInt();
+ skipUTF(); //String resourceTypeName = dataIn.readUTF();
+ skipUTF(); //String resourceTypeDesc = dataIn.readUTF();
+ int statCount = dataIn.readUnsignedShort();
+ byte[] typeCodes = new byte[statCount];
+
+ for (int i=0; i < statCount; i++) {
+ skipUTF(); //String statName = dataIn.readUTF();
+ typeCodes[i] = dataIn.readByte();
+ skipBoolean(); //boolean isCounter = dataIn.readBoolean();
+ if (this.archiveVersion >= 4) {
+ skipBoolean(); //boolean largerBetter = dataIn.readBoolean();
+ }
+ skipUTF(); //String units = dataIn.readUTF();
+ skipUTF(); //String desc = dataIn.readUTF();
+ }
+ if (resourceTypeId >= resourceTypes.length) {
+ byte[][] tmp = new byte[resourceTypeId+128][];
+ System.arraycopy(resourceTypes, 0, tmp, 0, resourceTypes.length);
+ resourceTypes = tmp;
+ }
+ resourceTypes[resourceTypeId] = typeCodes;
+
+ addGlobalToken(this.myIs.getBytes());
+ }
+ private void readResourceInstanceCreateToken(boolean initialize) throws IOException {
+ int resourceInstId = dataIn.readInt();
+ skipUTF(); //String name = dataIn.readUTF();
+ skipLong(); //long id = dataIn.readLong();
+ int resourceTypeId = dataIn.readInt();
+
+ if (resourceInstId >= resourceInstanceBits.length) {
+ long[][] tmpBits = new long[resourceInstId+128][];
+ System.arraycopy(resourceInstanceBits, 0,
+ tmpBits, 0, resourceInstanceBits.length);
+ resourceInstanceBits = tmpBits;
+
+ byte[][] tmpTypeCodes = new byte[resourceInstId+128][];
+ System.arraycopy(resourceInstanceTypeCodes, 0,
+ tmpTypeCodes, 0, resourceInstanceTypeCodes.length);
+ resourceInstanceTypeCodes = tmpTypeCodes;
+
+ byte[][] tmpTokens = new byte[resourceInstId+128][];
+ System.arraycopy(resourceInstanceTokens, 0,
+ tmpTokens, 0, resourceInstanceTokens.length);
+ resourceInstanceTokens = tmpTokens;
+ }
+ byte[] instTypeCodes = resourceTypes[resourceTypeId];
+ resourceInstanceTypeCodes[resourceInstId] = instTypeCodes;
+ resourceInstanceTokens[resourceInstId] = this.myIs.getBytes();
+ resourceInstanceTokens[resourceInstId][0] = RESOURCE_INSTANCE_INITIALIZE_TOKEN;
+ long[] instBits = new long[instTypeCodes.length];
+ resourceInstanceBits[resourceInstId] = instBits;
+ if (initialize) {
+ for (int i=0; i < instBits.length; i++) {
+ switch (instTypeCodes[i]) {
+ case BOOLEAN_CODE:
+ case BYTE_CODE:
+ case CHAR_CODE:
+ instBits[i] = dataIn.readByte();
+ break;
+ case WCHAR_CODE:
+ instBits[i] = dataIn.readUnsignedShort();
+ break;
+ case SHORT_CODE:
+ instBits[i] = dataIn.readShort();
+ break;
+ case INT_CODE:
+ case FLOAT_CODE:
+ case LONG_CODE:
+ case DOUBLE_CODE:
+ instBits[i] = readCompactValue();
+ break;
+ default:
+ throw new IOException(LocalizedStrings.ArchiveSplitter_UNEXPECTED_TYPECODE_VALUE_0.toLocalizedString(new Byte(instTypeCodes[i])));
+ }
+ }
+ }
+ }
+ private void readResourceInstanceDeleteToken() throws IOException {
+ int id = dataIn.readInt();
+ resourceInstanceTypeCodes[id] = null;
+ resourceInstanceBits[id] = null;
+ resourceInstanceTokens[id] = null;
+ }
+ private int readResourceInstId() throws IOException {
+ int token = dataIn.readUnsignedByte();
+ if (token <= MAX_BYTE_RESOURCE_INST_ID) {
+ return token;
+ } else if (token == ILLEGAL_RESOURCE_INST_ID_TOKEN) {
+ return ILLEGAL_RESOURCE_INST_ID;
+ } else if (token == SHORT_RESOURCE_INST_ID_TOKEN) {
+ return dataIn.readUnsignedShort();
+ } else { /* token == INT_RESOURCE_INST_ID_TOKEN */
+ return dataIn.readInt();
+ }
+ }
+ private void readTimeDelta() throws IOException {
+ int millisSinceLastSample = dataIn.readUnsignedShort();
+ if (millisSinceLastSample == INT_TIMESTAMP_TOKEN) {
+ millisSinceLastSample = dataIn.readInt();
+ }
+ this.currentDuration += millisSinceLastSample;
+ this.startTimeStamp += millisSinceLastSample;
+ }
+ private long readCompactValue() throws IOException {
+ long v = dataIn.readByte();
+ if (v < MIN_1BYTE_COMPACT_VALUE) {
+ if (v == COMPACT_VALUE_2_TOKEN) {
+ v = dataIn.readShort();
+ } else {
+ int bytesToRead = ((byte)v - COMPACT_VALUE_2_TOKEN) + 2;
+ v = dataIn.readByte(); // note the first byte will be a signed byte.
+ bytesToRead--;
+ while (bytesToRead > 0) {
+ v <<= 8;
+ v |= dataIn.readUnsignedByte();
+ bytesToRead--;
+ }
+ }
+ }
+ return v;
+ }
+ private void readSampleToken() throws IOException {
+ readTimeDelta();
+ int resourceInstId = readResourceInstId();
+ while (resourceInstId != ILLEGAL_RESOURCE_INST_ID) {
+ byte[] typeCodes = resourceInstanceTypeCodes[resourceInstId];
+ long[] bits = resourceInstanceBits[resourceInstId];
+ int statOffset = dataIn.readUnsignedByte();
+ while (statOffset != ILLEGAL_STAT_OFFSET) {
+ long statDeltaBits;
+ switch (typeCodes[statOffset]) {
+ case BOOLEAN_CODE:
+ case BYTE_CODE:
+ case CHAR_CODE:
+ statDeltaBits = dataIn.readByte();
+ break;
+ case WCHAR_CODE:
+ statDeltaBits = dataIn.readUnsignedShort();
+ break;
+ case SHORT_CODE:
+ statDeltaBits = dataIn.readShort();
+ break;
+ case INT_CODE:
+ case FLOAT_CODE:
+ case LONG_CODE:
+ case DOUBLE_CODE:
+ statDeltaBits = readCompactValue();
+ break;
+ default:
+ throw new IOException(LocalizedStrings.ArchiveSplitter_UNEXPECTED_TYPECODE_VALUE_0.toLocalizedString(new Byte(typeCodes[statOffset])));
+ }
+ bits[statOffset] += statDeltaBits;
+ statOffset = dataIn.readUnsignedByte();
+ }
+ resourceInstId = readResourceInstId();
+ }
+ }
+ /**
+ * Returns true if token read, false if eof.
+ */
+ private boolean readToken() throws IOException {
+ byte token;
+ try {
+ token = this.dataIn.readByte();
+ switch (token) {
+ case HEADER_TOKEN:
+ readHeaderToken();
+ this.myIs.putBytes(this.dataOut);
+ break;
+ case RESOURCE_TYPE_TOKEN:
+ readResourceTypeToken();
+ this.myIs.putBytes(this.dataOut);
+ break;
+ case RESOURCE_INSTANCE_CREATE_TOKEN:
+ case RESOURCE_INSTANCE_INITIALIZE_TOKEN:
+ readResourceInstanceCreateToken(token == RESOURCE_INSTANCE_INITIALIZE_TOKEN);
+ this.myIs.putBytes(this.dataOut);
+ break;
+ case RESOURCE_INSTANCE_DELETE_TOKEN:
+ readResourceInstanceDeleteToken();
+ this.myIs.putBytes(this.dataOut);
+ break;
+ case SAMPLE_TOKEN:
+ readSampleToken();
+ this.myIs.putBytes(this.dataOut);
+ break;
+ default:
+ throw new IOException(LocalizedStrings.ArchiveSplitter_UNEXPECTED_TOKEN_BYTE_VALUE_0.toLocalizedString(new Byte(token)));
+ }
+ return true;
+ } catch (EOFException ignore) {
+ return false;
+ }
+ }
+
+ private File getOutputName() {
+ String inName = archiveName.getPath();
+ StringBuffer buf = new StringBuffer(inName.length()+4);
+ int idx = inName.lastIndexOf('.');
+ if (idx == -1) {
+ buf.append(inName);
+ } else {
+ buf.append(inName.substring(0, idx));
+ }
+ buf.append('-')
+ .append(this.splitCount);
+ if (idx != -1) {
+ buf.append(inName.substring(idx));
+ }
+ return new File(buf.toString());
+ }
+
+ private void startSplit() throws IOException {
+ this.currentDuration = 0;
+ this.splitCount++;
+ if (archiveName.getPath().endsWith(".gz")) {
+ this.output = new GZIPOutputStream(new FileOutputStream(getOutputName()), BUFFER_SIZE);
+ } else {
+ this.output = new BufferedOutputStream(new FileOutputStream(getOutputName()), BUFFER_SIZE);
+ }
+ this.dataOut = new DataOutputStream(this.output);
+
+
+ if (this.splitCount > 1) {
+ this.dataOut.writeByte(HEADER_TOKEN);
+ this.dataOut.writeByte(ARCHIVE_VERSION);
+ this.dataOut.writeLong(this.startTimeStamp);
+ this.dataOut.writeLong(this.systemId);
+ this.dataOut.writeLong(this.systemStartTimeStamp);
+ this.dataOut.writeInt(this.timeZoneOffset);
+ this.dataOut.writeUTF(this.timeZoneName);
+ this.dataOut.writeUTF(this.systemDirectory);
+ this.dataOut.writeUTF(this.productVersion);
+ this.dataOut.writeUTF(this.os);
+ this.dataOut.writeUTF(this.machine);
+ }
+
+ for (int i=0; i < globalTokenCount; i++) {
+ this.dataOut.write(globalTokens[i]);
+ }
+ for (int i=0; i < resourceInstanceTokens.length; i++) {
+ if (resourceInstanceTokens[i] != null) {
+ this.dataOut.write(resourceInstanceTokens[i]);
+ byte[] instTypeCodes = resourceInstanceTypeCodes[i];
+ long[] instBits = resourceInstanceBits[i];
+ for (int j=0; j < instBits.length; j++) {
+ StatArchiveWriter.writeStatValue(instTypeCodes[j], instBits[j], this.dataOut);
+ }
+ }
+ }
+ }
+
+ private void endSplit() {
+ try {
+ this.dataOut.flush();
+ } catch (IOException ex) {
+ }
+ try {
+ this.output.close();
+ } catch (IOException ex) {
+ System.err.println("[warning] could not close " + getOutputName());
+ }
+ }
+
+ public void split() throws IOException {
+ boolean done = false;
+ do {
+ done = true;
+ startSplit();
+ while (readToken()) {
+ if (this.currentDuration >= this.splitDuration) {
+ done = false;
+ break;
+ }
+ }
+ endSplit();
+ } while (!done);
+ }
+
+ private static class MyFilterInputStream extends FilterInputStream {
+ private byte[] readBytes = new byte[32000];
+ private int idx = 0;
+ public MyFilterInputStream(InputStream in) {
+ super(in);
+ }
+
+ /**
+ * Returns all the bytes, read or skipped, since the last reset.
+ */
+ public byte[] getBytes() {
+ byte[] result = new byte[idx];
+ System.arraycopy(readBytes, 0, result, 0, result.length);
+ return result;
+ }
+
+ /**
+ * Writes all the bytes, read or skipped, since the last reset
+ * to the specified output stream.
+ * Does a mark and reset after the write.
+ */
+ public void putBytes(DataOutputStream dataOut) throws IOException {
+ dataOut.write(readBytes, 0, idx);
+ idx = 0;
+ }
+
+ @Override
+ public void close() throws IOException {
+ readBytes = null;
+ super.close();
+ }
+
+ @Override
+ public void reset() throws IOException {
+ idx = 0;
+ super.reset();
+ }
+
+ @Override
+ public long skip(long n) throws IOException {
+ makeRoom((int)n);
+ int result = super.read(readBytes, idx, (int)n);
+ if (result == -1) {
+ return 0;
+ } else {
+ idx += result;
+ return result;
+ }
+ }
+
+ private void makeRoom(int n) {
+ if (idx+n > readBytes.length) {
+ byte[] tmp = new byte[readBytes.length + n + 1024];
+ System.arraycopy(readBytes, 0, tmp, 0, readBytes.length);
+ readBytes = tmp;
+ }
+ }
+
+ @Override
+ public int read() throws IOException {
+ int result = super.read();
+ if (result != -1) {
+ makeRoom(1);
+ readBytes[idx] = (byte)result;
+ idx += 1;
+ }
+ return result;
+ }
+
+ @Override
+ public int read(byte[] b) throws IOException {
+ return read(b, 0, b.length);
+ }
+ @Override
+ public int read(byte[] b, int off, int len) throws IOException {
+ int result = super.read(b, off, len);
+ if (result != -1) {
+ makeRoom(result);
+ System.arraycopy(b, off, readBytes, idx, result);
+ idx += result;
+ }
+ return result;
+ }
+ }
+
+ public static void main(String args[]) throws IOException {
+ if (args.length != 1) {
+ System.err.println(LocalizedStrings.ArchiveSplitter_USAGE.toLocalizedString() + ": com.gemstone.gemfire.internal.statistics.ArchiveSplitter <archive.gfs>");
+ System.exit(1);
+ }
+ ArchiveSplitter as = new ArchiveSplitter(new File(args[0]));
+ as.split();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/CallbackSampler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/CallbackSampler.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/CallbackSampler.java
index 4bc3009..4b16a28 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/CallbackSampler.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/CallbackSampler.java
@@ -23,9 +23,6 @@ import java.util.concurrent.TimeUnit;
import com.gemstone.gemfire.CancelCriterion;
import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.SystemFailure;
-import com.gemstone.gemfire.internal.StatSamplerStats;
-import com.gemstone.gemfire.internal.StatisticsImpl;
-import com.gemstone.gemfire.internal.StatisticsManager;
import com.gemstone.gemfire.internal.logging.LogService;
import org.apache.logging.log4j.Logger;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/DummyStatisticsFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/DummyStatisticsFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/DummyStatisticsFactory.java
new file mode 100644
index 0000000..350e381
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/DummyStatisticsFactory.java
@@ -0,0 +1,135 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+
+import java.io.*;
+
+/**
+ * A StatisticsFactory that creates disconnected statistics
+ */
+public class DummyStatisticsFactory implements StatisticsFactory {
+
+ private final static StatisticsTypeFactoryImpl tf = (StatisticsTypeFactoryImpl) StatisticsTypeFactoryImpl.singleton();
+
+ /** Creates a new instance of DummyStatisticsFactory */
+ public DummyStatisticsFactory() {
+ }
+
+ // StatisticsFactory methods
+ public Statistics createStatistics(StatisticsType type) {
+ return createStatistics(type, null, 1);
+ }
+ public Statistics createStatistics(StatisticsType type, String textId) {
+ return createStatistics(type, textId, 1);
+ }
+ public Statistics createStatistics(StatisticsType type, String textId, long numericId) {
+ Statistics result = new LocalStatisticsImpl(type, textId, numericId, 1, false, 0, null);
+ return result;
+ }
+
+// /** for internal use only. Its called by {@link LocalStatisticsImpl#close}. */
+// public void destroyStatistics(Statistics stats) {
+// if (statsList.remove(stats)) {
+// statsListModCount++;
+// }
+// }
+//
+ public Statistics createAtomicStatistics(StatisticsType type) {
+ return createAtomicStatistics(type, null, 1);
+ }
+ public Statistics createAtomicStatistics(StatisticsType type, String textId) {
+ return createAtomicStatistics(type, textId, 1);
+ }
+ public Statistics createAtomicStatistics(StatisticsType type, String textId, long numericId) {
+ Statistics result = new LocalStatisticsImpl(type, textId, numericId, 1, true, 0, null);
+ return result;
+ }
+ public Statistics[] findStatisticsByType(StatisticsType type) {
+ return new Statistics[0];
+ }
+ public Statistics[] findStatisticsByTextId(String textId) {
+ return new Statistics[0];
+ }
+ public Statistics[] findStatisticsByNumericId(long numericId) {
+ return new Statistics[0];
+ }
+
+ public StatisticsType createType(String name, String description,
+ StatisticDescriptor[] stats) {
+ return tf.createType(name, description, stats);
+ }
+ public StatisticsType findType(String name) {
+ return tf.findType(name);
+ }
+ public StatisticsType[] createTypesFromXml(Reader reader)
+ throws IOException {
+ return tf.createTypesFromXml(reader);
+ }
+
+ public StatisticDescriptor createIntCounter(String name, String description,
+ String units) {
+ return tf.createIntCounter(name, description, units);
+ }
+ public StatisticDescriptor createLongCounter(String name, String description,
+ String units) {
+ return tf.createLongCounter(name, description, units);
+ }
+ public StatisticDescriptor createDoubleCounter(String name, String description,
+ String units) {
+ return tf.createDoubleCounter(name, description, units);
+ }
+ public StatisticDescriptor createIntGauge(String name, String description,
+ String units) {
+ return tf.createIntGauge(name, description, units);
+ }
+ public StatisticDescriptor createLongGauge(String name, String description,
+ String units) {
+ return tf.createLongGauge(name, description, units);
+ }
+ public StatisticDescriptor createDoubleGauge(String name, String description,
+ String units) {
+ return tf.createDoubleGauge(name, description, units);
+ }
+ public StatisticDescriptor createIntCounter(String name, String description,
+ String units, boolean largerBetter) {
+ return tf.createIntCounter(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createLongCounter(String name, String description,
+ String units, boolean largerBetter) {
+ return tf.createLongCounter(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createDoubleCounter(String name, String description,
+ String units, boolean largerBetter) {
+ return tf.createDoubleCounter(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createIntGauge(String name, String description,
+ String units, boolean largerBetter) {
+ return tf.createIntGauge(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createLongGauge(String name, String description,
+ String units, boolean largerBetter) {
+ return tf.createLongGauge(name, description, units, largerBetter);
+ }
+ public StatisticDescriptor createDoubleGauge(String name, String description,
+ String units, boolean largerBetter) {
+ return tf.createDoubleGauge(name, description, units, largerBetter);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/DummyStatisticsImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/DummyStatisticsImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/DummyStatisticsImpl.java
new file mode 100644
index 0000000..b5c5ec1
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/DummyStatisticsImpl.java
@@ -0,0 +1,242 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import java.util.function.DoubleSupplier;
+import java.util.function.IntSupplier;
+import java.util.function.LongSupplier;
+
+import com.gemstone.gemfire.*;
+
+/**
+ * An implementation of {@link Statistics} that does nothing.
+ * Setting the "gemfire.statsDisabled" to true causes it to be used.
+ *
+ * @see <A href="package-summary.html#statistics">Package introduction</A>
+ *
+ *
+ * @since GemFire 3.0
+ *
+ */
+public class DummyStatisticsImpl implements Statistics {
+
+ private final StatisticsType type;
+ private final String textId;
+ private final long numericId;
+
+ /////////////////////// Constructors ///////////////////////
+
+ /**
+ * Creates a new statistics instance of the given type
+ *
+ * @param type
+ * A description of the statistics
+ */
+ public DummyStatisticsImpl(StatisticsType type, String textId, long numericId) {
+ this.type = type;
+ this.textId = textId;
+ this.numericId = numericId;
+ }
+
+ public final void close() {
+ }
+
+ //////////////////////// accessor Methods ///////////////////////
+
+ public final int nameToId(String name) {
+ return this.type.nameToId(name);
+ }
+
+ public final StatisticDescriptor nameToDescriptor(String name) {
+ return this.type.nameToDescriptor(name);
+ }
+
+ public final long getUniqueId() {
+ return 0;
+ }
+
+ public final StatisticsType getType() {
+ return this.type;
+ }
+
+ public final String getTextId() {
+ return this.textId;
+ }
+ public final long getNumericId() {
+ return this.numericId;
+ }
+ public final boolean isAtomic() {
+ return true;
+ }
+ public final boolean isClosed() {
+ return false;
+ }
+
+ //////////////////////// set() Methods ///////////////////////
+
+ public final void setInt(int id, int value) {
+ }
+
+ public final void setInt(StatisticDescriptor descriptor, int value) {
+ }
+
+ public final void setInt(String name, int value) {
+ }
+
+ public final void setLong(int id, long value) {
+ }
+
+ public final void setLong(StatisticDescriptor descriptor, long value) {
+ }
+
+ public final void setLong(String name, long value) {
+ }
+
+ public final void setDouble(int id, double value) {
+ }
+
+ public final void setDouble(StatisticDescriptor descriptor, double value) {
+ }
+
+ public final void setDouble(String name, double value) {
+ }
+
+ /////////////////////// get() Methods ///////////////////////
+
+ public final int getInt(int id) {
+ return 0;
+ }
+
+ public final int getInt(StatisticDescriptor descriptor) {
+ return 0;
+ }
+
+ public final int getInt(String name) {
+ return 0;
+ }
+
+ public final long getLong(int id) {
+ return 0;
+ }
+
+ public final long getLong(StatisticDescriptor descriptor) {
+ return 0;
+ }
+
+ public final long getLong(String name) {
+ return 0;
+ }
+
+ public final double getDouble(int id) {
+ return 0.0;
+ }
+
+ public final double getDouble(StatisticDescriptor descriptor) {
+ return 0.0;
+ }
+
+ public final double getDouble(String name) {
+ return 0.0;
+ }
+
+ private static final Number dummyNumber = Integer.valueOf(0);
+
+ public final Number get(StatisticDescriptor descriptor) {
+ return dummyNumber;
+ }
+
+ public final Number get(String name) {
+ return dummyNumber;
+ }
+
+ public final long getRawBits(StatisticDescriptor descriptor) {
+ return 0;
+ }
+
+ public final long getRawBits(String name) {
+ return 0;
+ }
+
+ //////////////////////// inc() Methods ////////////////////////
+
+ public final void incInt(int id, int delta) {
+ }
+
+ public final void incInt(StatisticDescriptor descriptor, int delta) {
+ }
+
+ public final void incInt(String name, int delta) {
+ }
+
+ public final void incLong(int id, long delta) {
+ }
+
+ public final void incLong(StatisticDescriptor descriptor, long delta) {
+ }
+
+ public final void incLong(String name, long delta) {
+ }
+
+ public final void incDouble(int id, double delta) {
+ }
+
+ public final void incDouble(StatisticDescriptor descriptor, double delta) {
+ }
+
+ public final void incDouble(String name, double delta) {
+ }
+
+ @Override
+ public IntSupplier setIntSupplier(final int id, final IntSupplier supplier) {
+ return null;
+ }
+
+ @Override
+ public IntSupplier setIntSupplier(final String name, final IntSupplier supplier) {
+ return null;
+ }
+
+ @Override
+ public IntSupplier setIntSupplier(final StatisticDescriptor descriptor, final IntSupplier supplier) {
+ return null;
+ }
+
+ @Override public LongSupplier setLongSupplier(final int id, final LongSupplier supplier) {
+ return null;
+ }
+
+ @Override public LongSupplier setLongSupplier(final String name, final LongSupplier supplier) {
+ return null;
+ }
+
+ @Override public LongSupplier setLongSupplier(final StatisticDescriptor descriptor, final LongSupplier supplier) {
+ return null;
+ }
+
+ @Override public DoubleSupplier setDoubleSupplier(final int id, final DoubleSupplier supplier) {
+ return null;
+ }
+
+ @Override public DoubleSupplier setDoubleSupplier(final String name, final DoubleSupplier supplier) {
+ return null;
+ }
+
+ @Override
+ public DoubleSupplier setDoubleSupplier(final StatisticDescriptor descriptor, final DoubleSupplier supplier) {
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/GemFireStatSampler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/GemFireStatSampler.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/GemFireStatSampler.java
new file mode 100644
index 0000000..c723b0c
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/GemFireStatSampler.java
@@ -0,0 +1,507 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
+import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
+import com.gemstone.gemfire.internal.GemFireVersion;
+import com.gemstone.gemfire.internal.OSProcess;
+import com.gemstone.gemfire.internal.PureJavaMode;
+import com.gemstone.gemfire.internal.admin.ListenerIdMap;
+import com.gemstone.gemfire.internal.admin.remote.StatListenerMessage;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
+import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
+import com.gemstone.gemfire.internal.statistics.platform.OsStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.apache.logging.log4j.Logger;
+
+/**
+ * GemFireStatSampler adds listeners and rolling archives to HostStatSampler.
+ * <p>
+ * The StatisticsManager is implemented by DistributedSystem.
+ *
+ */
+public final class GemFireStatSampler extends HostStatSampler {
+
+ private static final Logger logger = LogService.getLogger();
+
+ private final ListenerIdMap listeners = new ListenerIdMap();
+
+ // TODO: change the listener maps to be copy-on-write
+
+ private final Map<LocalStatListenerImpl, Boolean> localListeners =
+ new ConcurrentHashMap<LocalStatListenerImpl, Boolean>();
+
+ private final Map<InternalDistributedMember, List<RemoteStatListenerImpl>> recipientToListeners =
+ new HashMap<InternalDistributedMember, List<RemoteStatListenerImpl>>();
+
+ private final InternalDistributedSystem con;
+
+ private int nextListenerId = 1;
+ private ProcessStats processStats = null;
+
+ ////////////////////// Constructors //////////////////////
+
+ public GemFireStatSampler(InternalDistributedSystem con) {
+ super(con.getCancelCriterion(), new StatSamplerStats(con, con.getId()));
+ this.con = con;
+ }
+
+ /**
+ * Returns the <code>ProcessStats</code> for this Java VM. Note
+ * that <code>null</code> will be returned if operating statistics
+ * are disabled.
+ *
+ * @since GemFire 3.5
+ */
+ public final ProcessStats getProcessStats() {
+ return this.processStats;
+ }
+
+ @Override
+ public String getProductDescription() {
+ return "GemFire " + GemFireVersion.getGemFireVersion()
+ + " #" + GemFireVersion.getBuildId()
+ + " as of " + GemFireVersion.getSourceDate();
+ }
+
+ public int addListener(InternalDistributedMember recipient, long resourceId, String statName) {
+ int result = getNextListenerId();
+ synchronized (listeners) {
+ while (listeners.get(result) != null) {
+ // previous one was still being used
+ result = getNextListenerId();
+ }
+ RemoteStatListenerImpl sl = RemoteStatListenerImpl.create(result, recipient,
+ resourceId, statName, this);
+ listeners.put(result, sl);
+ List<RemoteStatListenerImpl> l = recipientToListeners.get(recipient);
+ if (l == null) {
+ l = new ArrayList<RemoteStatListenerImpl>();
+ recipientToListeners.put(recipient, l);
+ }
+ l.add(sl);
+ }
+ return result;
+ }
+
+ public boolean removeListener(int listenerId) {
+ synchronized (listeners) {
+ RemoteStatListenerImpl sl = (RemoteStatListenerImpl)listeners.remove(listenerId);
+ if (sl != null) {
+ List<RemoteStatListenerImpl> l = recipientToListeners.get(sl.getRecipient());
+ l.remove(sl);
+ }
+ return sl != null;
+ }
+ }
+
+ public void removeListenersByRecipient(InternalDistributedMember recipient) {
+ synchronized (listeners) {
+ List<RemoteStatListenerImpl> l = recipientToListeners.get(recipient);
+ if (l != null && l.size() != 0) {
+ for (RemoteStatListenerImpl sl : l) {
+ listeners.remove(sl.getListenerId());
+ }
+ recipientToListeners.remove(recipient);
+ }
+ }
+ }
+
+ public void addLocalStatListener(LocalStatListener l, Statistics stats, String statName) {
+ LocalStatListenerImpl sl = null;
+ synchronized (LocalStatListenerImpl.class) {
+ sl = LocalStatListenerImpl.create(l, stats, statName);
+ }
+ this.localListeners.put(sl, Boolean.TRUE);
+ }
+
+ public boolean removeLocalStatListener(LocalStatListener listener) {
+ Iterator<Map.Entry<LocalStatListenerImpl, Boolean>> it =
+ this.localListeners.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry<LocalStatListenerImpl, Boolean> entry = it.next();
+ if (listener.equals(entry.getKey().getListener())) {
+ it.remove();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public Set<LocalStatListenerImpl> getLocalListeners() {
+ return this.localListeners.keySet();
+ }
+
+ @Override
+ public final File getArchiveFileName() {
+ return this.con.getConfig().getStatisticArchiveFile();
+ }
+
+ @Override
+ public final long getArchiveFileSizeLimit() {
+ if (fileSizeLimitInKB()) {
+ // use KB instead of MB to speed up rolling for testing
+ return ((long)this.con.getConfig().getArchiveFileSizeLimit()) * (1024);
+ } else {
+ return ((long)this.con.getConfig().getArchiveFileSizeLimit()) * (1024*1024);
+ }
+ }
+
+ @Override
+ public final long getArchiveDiskSpaceLimit() {
+ if (fileSizeLimitInKB()) {
+ // use KB instead of MB to speed up removal for testing
+ return ((long)this.con.getConfig().getArchiveDiskSpaceLimit()) * (1024);
+ } else {
+ return ((long)this.con.getConfig().getArchiveDiskSpaceLimit()) * (1024*1024);
+ }
+ }
+
+ @Override
+ protected void checkListeners() {
+ checkLocalListeners();
+ synchronized (listeners) {
+ if (listeners.size() == 0) {
+ return;
+ }
+ long timeStamp = System.currentTimeMillis();
+ Iterator<Map.Entry<InternalDistributedMember, List<RemoteStatListenerImpl>>> it1 =
+ recipientToListeners.entrySet().iterator();
+ while (it1.hasNext()) {
+ if (stopRequested()) return;
+ Map.Entry<InternalDistributedMember, List<RemoteStatListenerImpl>> me =
+ it1.next();
+ List<RemoteStatListenerImpl> l = me.getValue();
+ if (l.size() > 0) {
+ InternalDistributedMember recipient = (InternalDistributedMember)me.getKey();
+ StatListenerMessage msg =
+ StatListenerMessage.create(timeStamp, l.size());
+ msg.setRecipient(recipient);
+ for (RemoteStatListenerImpl statListener : l) {
+ if (getStatisticsManager().statisticsExists(statListener.getStatId())) {
+ statListener.checkForChange(msg);
+ } else {
+ // its stale; indicate this with a negative listener id
+ // fix for bug 29405
+ msg.addChange(-statListener.getListenerId(), 0);
+ }
+ }
+ this.con.getDistributionManager().putOutgoing(msg);
+ }
+ }
+ }
+ }
+
+ @Override
+ protected final int getSampleRate() {
+ return this.con.getConfig().getStatisticSampleRate();
+ }
+
+ @Override
+ public final boolean isSamplingEnabled() {
+ return this.con.getConfig().getStatisticSamplingEnabled();
+ }
+
+ @Override
+ protected final StatisticsManager getStatisticsManager() {
+ return this.con;
+ }
+
+ @Override
+ protected final OsStatisticsFactory getOsStatisticsFactory() {
+ return this.con;
+ }
+
+ @Override
+ protected final long getSpecialStatsId() {
+ long statId = OSProcess.getId();
+ if (statId == 0 || statId == -1) {
+ statId = getStatisticsManager().getId();
+ }
+ return statId;
+ }
+
+ @Override
+ protected final void initProcessStats(long id) {
+ if (PureJavaMode.osStatsAreAvailable()) {
+ if (osStatsDisabled()) {
+ logger.info(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.GemFireStatSampler_OS_STATISTIC_COLLECTION_DISABLED_BY_OSSTATSDISABLED_SYSTEM_PROPERTY));
+ } else {
+ int retVal = HostStatHelper.initOSStats();
+ if ( retVal != 0 ) {
+ logger.error(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.GemFireStatSampler_OS_STATISTICS_FAILED_TO_INITIALIZE_PROPERLY_SOME_STATS_MAY_BE_MISSING_SEE_BUGNOTE_37160));
+ }
+ HostStatHelper.newSystem(getOsStatisticsFactory());
+ String statName = getStatisticsManager().getName();
+ if (statName == null || statName.length() == 0) {
+ statName = "javaApp" + getStatisticsManager().getId();
+ }
+ Statistics stats = HostStatHelper.newProcess(getOsStatisticsFactory(), id, statName + "-proc");
+ this.processStats = HostStatHelper.newProcessStats(stats);
+ }
+ }
+ }
+
+ @Override
+ protected final void sampleProcessStats(boolean prepareOnly) {
+ if (prepareOnly || osStatsDisabled() || !PureJavaMode.osStatsAreAvailable()) {
+ return;
+ }
+ List<Statistics> l = getStatisticsManager().getStatsList();
+ if (l == null) {
+ return;
+ }
+ if (stopRequested()) return;
+ HostStatHelper.readyRefreshOSStats();
+ Iterator<Statistics> it = l.iterator();
+ while (it.hasNext()) {
+ if (stopRequested()) return;
+ StatisticsImpl s = (StatisticsImpl)it.next();
+ if (s.usesSystemCalls()) {
+ HostStatHelper.refresh((LocalStatisticsImpl)s);
+ }
+ }
+ }
+
+ @Override
+ protected final void closeProcessStats() {
+ if (PureJavaMode.osStatsAreAvailable()) {
+ if (!osStatsDisabled()) {
+ if (this.processStats != null) {
+ this.processStats.close();
+ }
+ HostStatHelper.closeOSStats();
+ }
+ }
+ }
+
+ private void checkLocalListeners() {
+ for (LocalStatListenerImpl st : this.localListeners.keySet()) {
+ if (getStatisticsManager().statisticsExists(st.getStatId())) {
+ st.checkForChange();
+ }
+ }
+ }
+
+ private int getNextListenerId() {
+ int result = nextListenerId++;
+ if (nextListenerId < 0) {
+ nextListenerId = 1;
+ }
+ return result;
+ }
+
+ protected static abstract class StatListenerImpl {
+ protected Statistics stats;
+ protected StatisticDescriptorImpl stat;
+ protected boolean oldValueInitialized = false;
+ protected long oldValue;
+
+ public long getStatId() {
+ if (this.stats.isClosed()) {
+ return -1;
+ } else {
+ return this.stats.getUniqueId();
+ }
+ }
+
+ protected abstract double getBitsAsDouble(long bits);
+ }
+
+ protected static abstract class LocalStatListenerImpl extends StatListenerImpl {
+ private LocalStatListener listener;
+
+ public LocalStatListener getListener() {
+ return this.listener;
+ }
+
+ static LocalStatListenerImpl create(LocalStatListener l, Statistics stats, String statName) {
+ LocalStatListenerImpl result = null;
+ StatisticDescriptorImpl stat = (StatisticDescriptorImpl)stats.nameToDescriptor(statName);
+ switch (stat.getTypeCode()) {
+ case StatisticDescriptorImpl.BYTE:
+ case StatisticDescriptorImpl.SHORT:
+ case StatisticDescriptorImpl.INT:
+ case StatisticDescriptorImpl.LONG:
+ result = new LocalLongStatListenerImpl();
+ break;
+ case StatisticDescriptorImpl.FLOAT:
+ result = new LocalFloatStatListenerImpl();
+ break;
+ case StatisticDescriptorImpl.DOUBLE:
+ result = new LocalDoubleStatListenerImpl();
+ break;
+ default:
+ throw new RuntimeException("Illegal field type " + stats.getType() + " for statistic");
+ }
+ result.stats = stats;
+ result.stat = stat;
+ result.listener = l;
+ return result;
+ }
+
+ /**
+ * Checks to see if the value of the stat has changed. If it has then
+ * the local listener is fired
+ */
+ public void checkForChange() {
+ long currentValue = stats.getRawBits(stat);
+ if (oldValueInitialized) {
+ if (currentValue == oldValue) {
+ return;
+ }
+ } else {
+ oldValueInitialized = true;
+ }
+ oldValue = currentValue;
+ listener.statValueChanged(getBitsAsDouble(currentValue));
+ }
+ }
+
+ protected static class LocalLongStatListenerImpl extends LocalStatListenerImpl {
+ @Override
+ protected double getBitsAsDouble(long bits) {
+ return bits;
+ }
+ }
+
+ protected static class LocalFloatStatListenerImpl extends LocalStatListenerImpl {
+ @Override
+ protected double getBitsAsDouble(long bits) {
+ return Float.intBitsToFloat((int)bits);
+ }
+ }
+
+ protected static class LocalDoubleStatListenerImpl extends LocalStatListenerImpl {
+ @Override
+ protected double getBitsAsDouble(long bits) {
+ return Double.longBitsToDouble(bits);
+ }
+ }
+
+ /**
+ * Used to register a StatListener.
+ */
+ protected static abstract class RemoteStatListenerImpl extends StatListenerImpl{
+ private int listenerId;
+ private InternalDistributedMember recipient;
+
+ @Override
+ public final int hashCode() {
+ return listenerId;
+ }
+
+ @Override
+ public final boolean equals(Object o) {
+ if (o == null) {
+ return false;
+ }
+ if (o instanceof RemoteStatListenerImpl) {
+ return listenerId == ((RemoteStatListenerImpl)o).listenerId;
+ } else {
+ return false;
+ }
+ }
+
+ public int getListenerId() {
+ return this.listenerId;
+ }
+
+ public InternalDistributedMember getRecipient() {
+ return this.recipient;
+ }
+
+ static RemoteStatListenerImpl create(int listenerId, InternalDistributedMember recipient, long resourceId, String statName, HostStatSampler sampler) {
+ RemoteStatListenerImpl result = null;
+ Statistics stats = sampler.getStatisticsManager().findStatistics(resourceId);
+ StatisticDescriptorImpl stat = (StatisticDescriptorImpl)stats.nameToDescriptor(statName);
+ switch (stat.getTypeCode()) {
+ case StatisticDescriptorImpl.BYTE:
+ case StatisticDescriptorImpl.SHORT:
+ case StatisticDescriptorImpl.INT:
+ case StatisticDescriptorImpl.LONG:
+ result = new LongStatListenerImpl();
+ break;
+ case StatisticDescriptorImpl.FLOAT:
+ result = new FloatStatListenerImpl();
+ break;
+ case StatisticDescriptorImpl.DOUBLE:
+ result = new DoubleStatListenerImpl();
+ break;
+ default:
+ throw new RuntimeException(LocalizedStrings.GemFireStatSampler_ILLEGAL_FIELD_TYPE_0_FOR_STATISTIC.toLocalizedString(stats.getType()));
+ }
+ result.stats = stats;
+ result.stat = stat;
+ result.listenerId = listenerId;
+ result.recipient = recipient;
+ return result;
+ }
+
+ /**
+ * Checks to see if the value of the stat has changed. If it has then it
+ * adds that change to the specified message.
+ */
+ public void checkForChange(StatListenerMessage msg) {
+ long currentValue = stats.getRawBits(stat);
+ if (oldValueInitialized) {
+ if (currentValue == oldValue) {
+ return;
+ }
+ } else {
+ oldValueInitialized = true;
+ }
+ oldValue = currentValue;
+ msg.addChange(listenerId, getBitsAsDouble(currentValue));
+ }
+ }
+
+ protected static class LongStatListenerImpl extends RemoteStatListenerImpl {
+ @Override
+ protected double getBitsAsDouble(long bits) {
+ return bits;
+ }
+ }
+
+ protected static class FloatStatListenerImpl extends RemoteStatListenerImpl {
+ @Override
+ protected double getBitsAsDouble(long bits) {
+ return Float.intBitsToFloat((int)bits);
+ }
+ }
+
+ protected static class DoubleStatListenerImpl extends RemoteStatListenerImpl {
+ @Override
+ protected double getBitsAsDouble(long bits) {
+ return Double.longBitsToDouble(bits);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/HostStatHelper.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/HostStatHelper.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/HostStatHelper.java
new file mode 100644
index 0000000..b52eaae
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/HostStatHelper.java
@@ -0,0 +1,303 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.*;
+//import com.gemstone.gemfire.util.*;
+import com.gemstone.gemfire.internal.PureJavaMode;
+import com.gemstone.gemfire.internal.SocketCreator;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.statistics.platform.LinuxProcFsStatistics;
+import com.gemstone.gemfire.internal.statistics.platform.LinuxProcessStats;
+import com.gemstone.gemfire.internal.statistics.platform.LinuxSystemStats;
+import com.gemstone.gemfire.internal.statistics.platform.OSXProcessStats;
+import com.gemstone.gemfire.internal.statistics.platform.OSXSystemStats;
+import com.gemstone.gemfire.internal.statistics.platform.OsStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
+import com.gemstone.gemfire.internal.statistics.platform.SolarisProcessStats;
+import com.gemstone.gemfire.internal.statistics.platform.SolarisSystemStats;
+import com.gemstone.gemfire.internal.statistics.platform.WindowsProcessStats;
+import com.gemstone.gemfire.internal.statistics.platform.WindowsSystemStats;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+/**
+ * Provides native methods which fetch operating system statistics.
+ */
+public class HostStatHelper {
+ static final int SOLARIS_CODE = 1; // Sparc Solaris
+ static final int WINDOWS_CODE = 2;
+ static final int LINUX_CODE = 3; // x86 Linux
+ static final int OSX_CODE = 4; // Mac OS X
+
+ static final int PROCESS_STAT_FLAG = 1;
+ static final int SYSTEM_STAT_FLAG = 2;
+
+ static final int osCode;
+
+ static {
+ String osName = System.getProperty("os.name", "unknown");
+ if (! PureJavaMode.osStatsAreAvailable()) {
+ throw new RuntimeException(LocalizedStrings.HostStatHelper_HOSTSTATHELPER_NOT_ALLOWED_IN_PURE_JAVA_MODE.toLocalizedString());
+ } else if (osName.equals("SunOS")) {
+ osCode = SOLARIS_CODE;
+ } else if (osName.startsWith("Windows")) {
+ osCode = WINDOWS_CODE;
+ } else if (osName.startsWith("Linux")) {
+ osCode = LINUX_CODE;
+ } else if (osName.equals("Mac OS X")) {
+ osCode = OSX_CODE;
+ } else {
+ throw new InternalGemFireException(LocalizedStrings.HostStatHelper_UNSUPPORTED_OS_0_SUPPORTED_OSS_ARE_SUNOSSPARC_SOLARIS_LINUXX86_AND_WINDOWS.toLocalizedString(osName));
+ }
+ }
+ public static boolean isWindows() {
+ return osCode == WINDOWS_CODE;
+ }
+ public static boolean isUnix() {
+ return osCode != WINDOWS_CODE;
+ }
+ public static boolean isSolaris() {
+ return osCode == SOLARIS_CODE;
+ }
+ public static boolean isLinux() {
+ return osCode == LINUX_CODE;
+ }
+ public static boolean isOSX() {
+ return osCode == OSX_CODE;
+ }
+
+ private HostStatHelper() {
+ // instances are not allowed
+ }
+
+ static int initOSStats() {
+ if(isLinux()) {
+ return LinuxProcFsStatistics.init();
+ } else {
+ return HostStatHelper.init();
+ }
+ }
+
+ static void closeOSStats() {
+ if(isLinux()) {
+ LinuxProcFsStatistics.close();
+ } else {
+ HostStatHelper.close();
+ }
+ }
+
+ static void readyRefreshOSStats() {
+ if(isLinux()) {
+ LinuxProcFsStatistics.readyRefresh();
+ } else {
+ HostStatHelper.readyRefresh();
+ }
+ }
+
+ /**
+ * Allocates and initializes any resources required to sample
+ * operating system statistics.
+ * returns 0 if initialization succeeded
+ */
+ private static native int init();
+ /**
+ * Frees up resources used by this class. Once close is called this
+ * class can no longer be used.
+ */
+ private static native void close();
+ /**
+ * Should be called before any calls to the refresh methods.
+ * On some platforms if this is not called then the refesh methods
+ * will just keep returning the same old data.
+ */
+ private static native void readyRefresh();
+ /**
+ * Refreshes the specified process stats instance by fetching
+ * the current OS values for the given stats and storing them in the instance.
+ */
+ private static void refreshProcess(LocalStatisticsImpl s) {
+ int pid = (int)s.getNumericId();
+ if(isLinux()) {
+ LinuxProcFsStatistics.refreshProcess(pid, s._getIntStorage(), s._getLongStorage(), s._getDoubleStorage());
+ } else {
+ refreshProcess(pid, s._getIntStorage(), s._getLongStorage(), s._getDoubleStorage());
+ }
+ }
+ private static native void refreshProcess(int pid, int[] ints, long[] longs, double[] doubles);
+ /**
+ * Refreshes the specified system stats instance by fetching
+ * the current OS values for the local machine and storing them in
+ * the instance.
+ */
+ private static void refreshSystem(LocalStatisticsImpl s) {
+ if(isLinux()) {
+ LinuxProcFsStatistics.refreshSystem(s._getIntStorage(), s._getLongStorage(), s._getDoubleStorage());
+ } else {
+ refreshSystem(s._getIntStorage(), s._getLongStorage(), s._getDoubleStorage());
+ }
+ }
+ private static native void refreshSystem(int[] ints, long[] longs, double[] doubles);
+
+ /**
+ * The call should have already checked to make sure
+ * usesSystemCalls returns true.
+ */
+ public static void refresh(LocalStatisticsImpl stats) {
+ int flags = stats.getOsStatFlags();
+ if ((flags & PROCESS_STAT_FLAG) != 0) {
+ HostStatHelper.refreshProcess(stats);
+ } else if ((flags & SYSTEM_STAT_FLAG) != 0) {
+ HostStatHelper.refreshSystem(stats);
+ } else {
+ throw new RuntimeException(LocalizedStrings.HostStatHelper_UNEXPECTED_OS_STATS_FLAGS_0.toLocalizedString(Integer.valueOf(flags)));
+ }
+ }
+
+ /**
+ * Creates and returns a {@link Statistics} with
+ * the given pid and name. The resource's stats will contain a snapshot
+ * of the current statistic values for the specified process.
+ */
+ public static Statistics newProcess(OsStatisticsFactory f, long pid, String name) {
+ Statistics stats;
+ switch (osCode) {
+ case SOLARIS_CODE:
+ stats = f.createOsStatistics(SolarisProcessStats.getType(),
+ name, pid, PROCESS_STAT_FLAG);
+ break;
+ case LINUX_CODE:
+ stats = f.createOsStatistics(LinuxProcessStats.getType(),
+ name, pid, PROCESS_STAT_FLAG);
+ break;
+ case OSX_CODE:
+ stats = f.createOsStatistics(OSXProcessStats.getType(),
+ name, pid, PROCESS_STAT_FLAG);
+ break;
+ case WINDOWS_CODE:
+ stats = f.createOsStatistics(WindowsProcessStats.getType(),
+ name, pid, PROCESS_STAT_FLAG);
+ break;
+ default:
+ throw new InternalGemFireException(LocalizedStrings.HostStatHelper_UNHANDLED_OSCODE_0_HOSTSTATHELPERNEWPROCESS.toLocalizedString(Integer.valueOf(osCode)));
+ }
+ // Note we don't call refreshProcess since we only want the manager to do that
+ return stats;
+ }
+
+ /**
+ * Creates a new <code>ProcessStats</code> instance that wraps the
+ * given <code>Statistics</code>.
+ *
+ * @see #newProcess
+ * @since GemFire 3.5
+ */
+ static ProcessStats newProcessStats(Statistics stats) {
+ switch (osCode) {
+ case SOLARIS_CODE:
+ return SolarisProcessStats.createProcessStats(stats);
+
+ case LINUX_CODE:
+ return LinuxProcessStats.createProcessStats(stats);
+
+ case WINDOWS_CODE:
+ return WindowsProcessStats.createProcessStats(stats);
+
+ case OSX_CODE:
+ return OSXProcessStats.createProcessStats(stats);
+
+ default:
+ throw new InternalGemFireException(LocalizedStrings.HostStatHelper_UNHANDLED_OSCODE_0_HOSTSTATHELPERNEWPROCESSSTATS.toLocalizedString(Integer.valueOf(osCode)));
+ }
+ }
+
+ /**
+ * Creates and returns a {@link Statistics} with the current
+ * machine's stats. The resource's stats will contain a snapshot
+ * of the current statistic values for the local machine.
+ */
+ static void newSystem(OsStatisticsFactory f) {
+ Statistics stats;
+ switch (osCode) {
+ case SOLARIS_CODE:
+ stats = f.createOsStatistics(SolarisSystemStats.getType(),
+ getHostSystemName(),
+ getHostSystemId(),
+ SYSTEM_STAT_FLAG);
+ break;
+ case LINUX_CODE:
+ stats = f.createOsStatistics(LinuxSystemStats.getType(),
+ getHostSystemName(),
+ getHostSystemId(),
+ SYSTEM_STAT_FLAG);
+ break;
+ case WINDOWS_CODE:
+ stats = f.createOsStatistics(WindowsSystemStats.getType(),
+ getHostSystemName(),
+ getHostSystemId(),
+ SYSTEM_STAT_FLAG);
+ break;
+ case OSX_CODE:
+ stats = f.createOsStatistics(OSXSystemStats.getType(),
+ getHostSystemName(),
+ getHostSystemId(),
+ SYSTEM_STAT_FLAG);
+ break;
+ default:
+ throw new InternalGemFireException(LocalizedStrings.HostStatHelper_UNHANDLED_OSCODE_0_HOSTSTATHELPERNEWSYSTEM.toLocalizedString(Integer.valueOf(osCode)));
+ }
+ if (stats instanceof LocalStatisticsImpl) {
+ refreshSystem((LocalStatisticsImpl)stats);
+ } // otherwise its a Dummy implementation so do nothing
+ }
+
+ /**
+ * @return this machine's fully qualified hostname
+ * or "unknownHostName" if one cannot be found.
+ */
+ private static String getHostSystemName() {
+ String hostname = "unknownHostName";
+ try {
+ InetAddress addr = SocketCreator.getLocalHost();
+ hostname = addr.getCanonicalHostName();
+ } catch (UnknownHostException uhe) {
+ }
+ return hostname;
+ }
+
+ /**
+ * Generate a systemid based off of the ip address of the host.
+ * This duplicates the common implementation of
+ * <code>long gethostid(void) </code>.
+ * Punt on the ipv6 case and just use the same algorithm.
+ * @return a psuedo unique id based on the ip address
+ */
+ private static long getHostSystemId() {
+ long id = 0L;
+ try {
+ InetAddress host = SocketCreator.getLocalHost();
+ byte[] addr = host.getAddress();
+ id = (addr[1] & 0xFFL) << 24 |
+ (addr[0] & 0xFFL) << 16 |
+ (addr[3] & 0xFFL) << 8 |
+ (addr[2] & 0xFFL) << 0;
+ } catch (UnknownHostException uhe) {
+ }
+ return id;
+ }
+}
[09/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/WindowsSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/WindowsSystemStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/WindowsSystemStats.java
new file mode 100644
index 0000000..b0a128f
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/platform/WindowsSystemStats.java
@@ -0,0 +1,269 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics.platform;
+
+import com.gemstone.gemfire.*;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+
+/**
+ * <P>This class provides the interface for statistics about the
+ * Windows machine a GemFire system is running on.
+ */
+public class WindowsSystemStats
+{
+ private final static int committedMemoryInUseINT = 0;
+ private final static int eventsINT = 1;
+ private final static int interruptsINT = 2;
+ private final static int mutexesINT = 3;
+ private final static int processesINT = 4;
+ private final static int processorQueueLengthINT = 5;
+ private final static int registryQuotaInUseINT = 6;
+ private final static int sharedMemorySectionsINT = 7;
+ private final static int semaphoresINT = 8;
+ private final static int threadsINT = 9;
+ private final static int dgramsReceivedINT = 10;
+ private final static int dgramsNoPortINT = 11;
+ private final static int dgramsReceivedErrorsINT = 12;
+ private final static int dgramsSentINT = 13;
+ private final static int loopbackPacketsINT = 14;
+ private final static int loopbackBytesINT = 15;
+ private final static int netPacketsReceivedINT = 16;
+ private final static int netBytesReceivedINT = 17;
+ private final static int netPacketsSentINT = 18;
+ private final static int netBytesSentINT = 19;
+
+
+ private final static int availableMemoryLONG = 0;
+ private final static int cacheFaultsLONG = 1;
+ private final static int cacheSizeLONG = 2;
+ private final static int cacheSizePeakLONG = 3;
+ private final static int committedMemoryLONG = 4;
+ private final static int committedMemoryLimitLONG = 5;
+ private final static int contextSwitchesLONG = 6;
+ private final static int demandZeroFaultsLONG = 7;
+ private final static int pageFaultsLONG = 8;
+ private final static int pageReadsLONG = 9;
+ private final static int pagesLONG = 10;
+ private final static int pageWritesLONG = 11;
+ private final static int pagesInputLONG = 12;
+ private final static int pagesOutputLONG = 13;
+ private final static int systemCallsLONG = 14;
+
+ private final static int cpuActiveDOUBLE = 0;
+ private final static int cpuIdleDOUBLE = 1;
+ private final static int cpuInterruptDOUBLE = 2;
+ private final static int cpuSystemDOUBLE = 3;
+ private final static int cpuUserDOUBLE = 4;
+
+ private final static StatisticsType myType;
+
+ private static void checkOffset(String name, int offset) {
+ int id = myType.nameToId(name);
+ Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
+ }
+
+ static {
+ StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
+ myType = f.createType("WindowsSystemStats",
+ "Statistics on a Microsoft Windows machine.",
+ new StatisticDescriptor[] {
+ f.createIntGauge("committedMemoryInUse",
+ "This represents the percentage of available virtual memory in use. This is an instantaneous value, not an average.",
+ "%"),
+ f.createIntGauge("events",
+ "The number of events in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. An event is used when two or more threads wish to synchronize execution.",
+ "items"),
+ f.createIntCounter("interrupts",
+ "The total number of harware interrupts on the computer. Some devices that may generate interrupts are the system timer, the mouse, data communication lines, network interface cards and other peripheral devices. This counter provides an indication of how busy these devices are on a computer-wide basis.",
+ "operations", false),
+ f.createIntGauge("mutexes",
+ "The number of mutexes in the computer at the time of data collection. This is an instantaneous count, not an average over the time interval. Mutexes are used by threads to assure only one thread is executing some section of code.",
+ "items"),
+ f.createIntGauge("processes",
+ "The number of processes in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Each process represents the running of a program.",
+ "processes"),
+ f.createIntGauge("processorQueueLength",
+ "The instantaneous length of the processor queue in units of threads. All processors use a single queue in which threads wait for processor cycles. This length does not include the threads that are currently executing. A sustained processor queue length greater than two generally indicates processor congestion. This is an instantaneous count, not an average over the time interval",
+ "threads"),
+ f.createIntGauge("registryQuotaInUse",
+ "The percentage of the Total Registry Quota Allowed currently in use by the system.",
+ "%"),
+ f.createIntGauge("sharedMemorySections",
+ "The number of sections in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. A section is a portion of virtual memory created by a process for storing data. A process may share sections with other processes.",
+ "items"),
+ f.createIntGauge("semaphores",
+ "The number of semaphores in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Threads use semaphores to obtain exclusive access to data structures that they share with other threads.",
+ "items"),
+ f.createIntGauge("threads",
+ "The number of threads in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. A thread is the basic executable entity that can execute instructions in a processor.",
+ "threads"),
+ f.createIntCounter(
+ "dgramsReceived",
+ "The number of datagrams received on the VM's machine.",
+ "datagrams/sec"),
+ f.createIntCounter(
+ "dgramsNoPort",
+ "The number of incoming datagrams that were discarded due to invalid headers",
+ "datagrams/sec"),
+ f.createIntCounter(
+ "dgramsReceivedErrors",
+ "The number of received UDP datagrams that could not be delivered for reasons other than the lack of an application at the destination port",
+ "datagrams"),
+ f.createIntCounter(
+ "dgramsSent",
+ "The number of datagrams sent on the VM's machine",
+ "datagrams/sec"),
+
+ f.createIntCounter(
+ "loopbackPackets",
+ "The number of packets sent/received on the loopback interface",
+ "packets"),
+ f.createIntCounter(
+ "loopbackBytes",
+ "The number of bytes sent/received on the loopback interface",
+ "bytes"),
+ f.createIntCounter("netPacketsReceived",
+ "The number of network packets received (total excluding loopback)",
+ "packets"),
+ f.createIntCounter("netBytesReceived",
+ "The number of network bytes received (total excluding loopback)",
+ "bytes"),
+ f.createIntCounter("netPacketsSent",
+ "The number of network packets sent (total excluding loopback)",
+ "packets"),
+ f.createIntCounter("netBytesSent",
+ "The number of network bytes sent (total excluding loopback)",
+ "bytes"),
+
+ f.createLongGauge("availableMemory",
+ "The size, in bytes, of the virtual memory currently on the Zeroed, Free, and Standby lists. Zeroed and Free memory is ready for use, with Zeroed memory cleared to zeros. Standby memory is memory removed from a process's Working Set but still available. Notice that this is an instantaneous count, not an average over the time interval.",
+ "bytes", true),
+ f.createLongCounter("cacheFaults",
+ "Incremented whenever the Cache manager does not find a file's page in the immediate Cache and must ask the memory manager to locate the page elsewhere in memory or on the disk so that it can be loaded into the immediate Cache.",
+ "operations", false),
+ f.createLongGauge("cacheSize",
+ "Measures the number of bytes currently in use by the system Cache. The system Cache is used to buffer data retrieved from disk or LAN. The system Cache uses memory not in use by active processes in the computer.",
+ "bytes"),
+ f.createLongGauge("cacheSizePeak",
+ "Measures the maximum number of bytes used by the system Cache. The system Cache is used to buffer data retrieved from disk or LAN. The system Cache uses memory not in use by active processes in the computer.",
+ "bytes"),
+ f.createLongGauge("committedMemory",
+ "The size of virtual memory, in bytes, that has been Committed (as opposed to simply reserved). Committed memory must have backing (i.e., disk) storage available, or must be assured never to need disk storage (because main memory is large enough to hold it.) Notice that this is an instantaneous count, not an average over the time interval.",
+ "bytes"),
+ f.createLongGauge("committedMemoryLimit",
+ "The size, in bytes, of virtual memory that can be committed without having to extend the paging file(s). If the paging file(s) can be extended, this is a soft limit. Note that this value will change if the paging file is extended.",
+ "bytes"),
+ f.createLongCounter("contextSwitches",
+ "The number of times this thread has lost the cpu to another thread. Thread switches can occur either inside of a single process or across processes. A thread switch may be caused either by one thread asking another for information, or by a thread being preempted by another, higher priority thread becoming ready to run. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of User and Privileged modes. These subsystem processes provide additional protection. Therefore, some work done by Windows on behalf of an application may appear in other subsystem processes in addition to the Privileged Time in the application. Switching to the subsystem process causes one Context Switch in the application thread. Switching back causes another Context Switch in the subsystem thread.",
+ "operations", false),
+ f.createLongCounter("demandZeroFaults",
+ "The total number of page faults for pages that must be filled with zeros before the fault is satisfied. If the Zeroed list is not empty, the fault can be resolved by removing a page from the Zeroed list.",
+ "operations", false),
+ f.createLongCounter("pageFaults",
+ "The total number of Page Faults by the threads executing in this process. A page fault occurs when a thread refers to a virtual memory page that is not in its working set in main memory. This will not cause the page to be fetched from disk if it is on the standby list and hence already in main memory, or if it is in use by another process with whom the page is shared.",
+ "operations", false),
+ f.createLongCounter("pageReads",
+ "The number of page read operations done by the process since it was last started. These operations involve actual disk reads and not reads from the shared page cache",
+ "operations", false),
+ f.createLongCounter("pages",
+ "The total number of pages read from the disk or written to the disk to resolve memory references to pages that were not in memory at the time of the reference. This is the sum of pagesInput and the pagesOutput. This counter includes paging traffic on behalf of the system Cache to access file data for applications. This value also includes the pages to/from non-cached mapped memory files. This is the primary counter to observe if you are concerned about excessive memory pressure (that is, thrashing), and the excessive paging that may result.",
+ "pages", false),
+ f.createLongCounter("pageWrites",
+ "The number of pages written by the process since it was last started. These page writes are actual disk writes and not just writes into the shared page cache. Unless a large data load is in process, the number should be low for all processes except the Stone's AIO page server process.",
+ "operations", false),
+ f.createLongCounter("pagesInput",
+ "The total number of pages read from the disk to resolve memory references to pages that were not in memory at the time of the reference. This counter includes paging traffic on behalf of the system Cache to access file data for applications. This is an important counter to observe if you are concerned about excessive memory pressure (that is, thrashing), and the excessive paging that may result",
+ "pages", false),
+ f.createLongCounter("pagesOutput",
+ "A count of the total number of pages that are written to disk because the pages have been modified in main memory",
+ "pages", false),
+ f.createLongCounter("systemCalls",
+ "The total number of calls to Windows system service routines on the computer. These routines perform all of the basic scheduling and synchronization of activities on the computer, and provide access to non-graphical devices, memory management, and name space management.",
+ "operations"),
+
+
+
+ f.createDoubleGauge("cpuActive",
+ "The percentage of time spent doing useful work by all processors. On a multi-processor system, if all processors are always busy this is 100%.",
+ "%"),
+ f.createDoubleGauge("cpuIdle",
+ "The percentage of time the machine's processors spent idle.",
+ "%", true),
+ f.createDoubleGauge("cpuInterrupt",
+ "The percentage of time spent receiving and servicing interrupts on all the processors on the machine. This value is an indirect indicator of the activity of devices that generate interrupts, such as the system clock, the mouse, disk drivers, data communication lines, network interface cards and other peripheral devices. These devices normally interrupt the processor when they have completed a task or require attention. Normal thread execution is suspended during interrupts. Most system clocks interrupt the processor every 10 milliseconds, creating a background of interrupt activity. ",
+ "%"),
+ f.createDoubleGauge("cpuSystem",
+ "The percentage of time spent in privileged mode by all processors. On a multi-processor system, if all processors are always in privileged mode this is 100%. When a Windows system service is called, the service will often run in privileged mode in order to gain access to system-private data. Such data is protected from access by threads executing in user mode. Calls to the system may be explicit, or they may be implicit such as when a page fault or an interrupt occurs. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of user and privileged modes. These subsystem processes provide additional protection. Therefore, some work done by Windows on behalf of an application may appear in other subsystem processes in addition to the cpuSystem in the application process.",
+ "%"),
+ f.createDoubleGauge("cpuUser",
+ "The percentage of time spent executing code in user mode on all the processor's on the machine.",
+ "%")
+ });
+ checkOffset("committedMemoryInUse", committedMemoryInUseINT);
+ checkOffset("events", eventsINT);
+ checkOffset("interrupts", interruptsINT);
+ checkOffset("mutexes", mutexesINT);
+ checkOffset("processes", processesINT);
+ checkOffset("processorQueueLength", processorQueueLengthINT);
+ checkOffset("registryQuotaInUse", registryQuotaInUseINT);
+ checkOffset("sharedMemorySections", sharedMemorySectionsINT);
+ checkOffset("semaphores", semaphoresINT);
+ checkOffset("threads", threadsINT);
+ checkOffset("dgramsReceived", dgramsReceivedINT);
+ checkOffset("dgramsNoPort", dgramsNoPortINT);
+ checkOffset("dgramsReceivedErrors", dgramsReceivedErrorsINT);
+ checkOffset("dgramsSent", dgramsSentINT);
+
+ checkOffset("loopbackPackets", loopbackPacketsINT);
+ checkOffset("loopbackBytes", loopbackBytesINT);
+ checkOffset("netPacketsReceived", netPacketsReceivedINT);
+ checkOffset("netBytesReceived", netBytesReceivedINT);
+ checkOffset("netPacketsSent", netPacketsSentINT);
+ checkOffset("netBytesSent", netBytesSentINT);
+
+ checkOffset("availableMemory", availableMemoryLONG);
+ checkOffset("cacheFaults", cacheFaultsLONG);
+ checkOffset("cacheSize", cacheSizeLONG);
+ checkOffset("cacheSizePeak", cacheSizePeakLONG);
+ checkOffset("committedMemory", committedMemoryLONG);
+ checkOffset("committedMemoryLimit", committedMemoryLimitLONG);
+ checkOffset("contextSwitches", contextSwitchesLONG);
+ checkOffset("demandZeroFaults", demandZeroFaultsLONG);
+ checkOffset("pageFaults", pageFaultsLONG);
+ checkOffset("pageReads", pageReadsLONG);
+ checkOffset("pages", pagesLONG);
+ checkOffset("pageWrites", pageWritesLONG);
+ checkOffset("pagesInput", pagesInputLONG);
+ checkOffset("pagesOutput", pagesOutputLONG);
+ checkOffset("systemCalls", systemCallsLONG);
+
+ checkOffset("cpuActive", cpuActiveDOUBLE);
+ checkOffset("cpuIdle", cpuIdleDOUBLE);
+ checkOffset("cpuInterrupt", cpuInterruptDOUBLE);
+ checkOffset("cpuSystem", cpuSystemDOUBLE);
+ checkOffset("cpuUser", cpuUserDOUBLE);
+ }
+
+ private WindowsSystemStats() {
+ // no instances allowed
+ }
+ public static StatisticsType getType() {
+ return myType;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/Atomic50StatisticsImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/Atomic50StatisticsImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/Atomic50StatisticsImpl.java
index f374394..cff9142 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/Atomic50StatisticsImpl.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/Atomic50StatisticsImpl.java
@@ -19,6 +19,10 @@ package com.gemstone.gemfire.internal.stats50;
import com.gemstone.gemfire.*;
import com.gemstone.gemfire.internal.*;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.statistics.StatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsManager;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeImpl;
+
import java.util.concurrent.atomic.AtomicIntegerArray; // don't use backport here!
import java.util.concurrent.atomic.AtomicLongArray; // don't use backport here!
import java.util.concurrent.ConcurrentLinkedQueue; // don't use backport here!
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/VMStats50.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/VMStats50.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/VMStats50.java
index 6f2eea6..e5b55f4 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/VMStats50.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/stats50/VMStats50.java
@@ -43,8 +43,8 @@ import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.SystemFailure;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.internal.ClassPathLoader;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
-import com.gemstone.gemfire.internal.VMStatsContract;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.VMStatsContract;
import com.gemstone.gemfire.internal.logging.LogService;
/**
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/management/internal/beans/MemberMBeanBridge.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/management/internal/beans/MemberMBeanBridge.java b/geode-core/src/main/java/com/gemstone/gemfire/management/internal/beans/MemberMBeanBridge.java
index 89cc4f0..08260d3 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/management/internal/beans/MemberMBeanBridge.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/management/internal/beans/MemberMBeanBridge.java
@@ -47,6 +47,14 @@ import com.gemstone.gemfire.internal.offheap.MemoryAllocator;
import com.gemstone.gemfire.internal.offheap.OffHeapMemoryStats;
import com.gemstone.gemfire.internal.process.PidUnavailableException;
import com.gemstone.gemfire.internal.process.ProcessUtils;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
+import com.gemstone.gemfire.internal.statistics.HostStatHelper;
+import com.gemstone.gemfire.internal.statistics.platform.LinuxSystemStats;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
+import com.gemstone.gemfire.internal.statistics.platform.SolarisSystemStats;
+import com.gemstone.gemfire.internal.statistics.StatSamplerStats;
+import com.gemstone.gemfire.internal.statistics.VMStatsContract;
+import com.gemstone.gemfire.internal.statistics.platform.WindowsSystemStats;
import com.gemstone.gemfire.internal.stats50.VMStats50;
import com.gemstone.gemfire.internal.tcp.ConnectionTable;
import com.gemstone.gemfire.management.*;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/GemFireTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/GemFireTestCase.java b/geode-core/src/test/java/com/gemstone/gemfire/GemFireTestCase.java
deleted file mode 100644
index 337f971..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/GemFireTestCase.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * 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 com.gemstone.gemfire;
-
-import com.gemstone.gemfire.distributed.DistributedSystem;
-import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.rules.TestName;
-
-import java.util.Properties;
-
-import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
-import static org.junit.Assert.assertTrue;
-
-/**
- * This is an abstract superclass for classes that test GemFire. It
- * has setUp() and tearDown() methods that create and initialize a
- * GemFire connection.
- *
- *
- */
-public abstract class GemFireTestCase {
-
- @Rule
- public TestName testName = new TestName();
-
- @Before
- public void setUp() throws Exception {
- Properties p = new Properties();
- // make it a loner
- p.setProperty(MCAST_PORT, "0");
- p.setProperty(LOCATORS, "");
- p.setProperty(NAME, getName());
- DistributedSystem.connect(p);
- }
-
- @After
- public void tearDown() throws Exception {
- DistributedSystem ds = InternalDistributedSystem.getAnyInstance();
- if (ds != null) {
- ds.disconnect();
- }
- }
-
- protected String getName() {
- return testName.getMethodName();
- }
-
- /**
- * Strip the package off and gives just the class name.
- * Needed because of Windows file name limits.
- */
- private String getShortClassName() {
- return getClass().getSimpleName();
- }
-
- /**
- * Returns a unique name for this test method. It is based on the
- * name of the class as well as the name of the method.
- */
- protected String getUniqueName() {
- return getShortClassName() + "_" + getName();
- }
-
- /**
- * Assert an Invariant condition on an object.
- * @param inv the Invariant to assert. If null, this method just returns
- * @param obj the Object to assert the Invariant on.
- */
- protected void assertInvariant(Invariant inv, Object obj) {
- if (inv == null) return;
- InvariantResult result = inv.verify(obj);
- assertTrue(result.message, result.valid);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/Invariant.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/Invariant.java b/geode-core/src/test/java/com/gemstone/gemfire/Invariant.java
deleted file mode 100644
index 1c712d2..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/Invariant.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * 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 com.gemstone.gemfire;
-
-/**
- * Interface used for testing an invariant
- *
- */
-public interface Invariant {
- /**
- * @return error message, or null if verification passes
- */
- public InvariantResult verify(Object obj);
-}
-
-
-
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/InvariantResult.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/InvariantResult.java b/geode-core/src/test/java/com/gemstone/gemfire/InvariantResult.java
deleted file mode 100644
index 272e026..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/InvariantResult.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * 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 com.gemstone.gemfire;
-
-/**
-* Used as result of verifying an Invariant
-* @see Invariant
-*
-*/
-public class InvariantResult {
- public String message;
- public boolean valid;
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/LocalStatisticsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/LocalStatisticsJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/LocalStatisticsJUnitTest.java
deleted file mode 100644
index ab5b8e1..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/LocalStatisticsJUnitTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * 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 com.gemstone.gemfire;
-
-import com.gemstone.gemfire.distributed.DistributedSystem;
-import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
-import org.junit.experimental.categories.Category;
-
-import java.util.Properties;
-
-import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
-
-/**
- * Tests the functionality of JOM {@link Statistics}.
- */
-@Category(IntegrationTest.class)
-public class LocalStatisticsJUnitTest extends StatisticsTestCase {
-
- /**
- * Returns a distributed system configured to not use shared
- * memory.
- */
- protected DistributedSystem getSystem() {
- if (this.system == null) {
- Properties props = new Properties();
- props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
- props.setProperty(STATISTIC_ARCHIVE_FILE, "StatisticsTestCase-localTest.gfs");
- props.setProperty(MCAST_PORT, "0");
- props.setProperty(LOCATORS, "");
- props.setProperty(NAME, getName());
- this.system = DistributedSystem.connect(props);
- }
-
- return this.system;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/StatisticsTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/StatisticsTestCase.java b/geode-core/src/test/java/com/gemstone/gemfire/StatisticsTestCase.java
deleted file mode 100644
index 03b5e16..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/StatisticsTestCase.java
+++ /dev/null
@@ -1,388 +0,0 @@
-/*
- * 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 com.gemstone.gemfire;
-
-import static org.junit.Assert.*;
-
-import com.gemstone.gemfire.distributed.DistributedSystem;
-
-import java.util.*;
-
-import org.junit.Test;
-
-/**
- * Tests the functionality of {@link Statistics}. Uses a
- * subclass to tests JOM-only statistics.
- */
-public abstract class StatisticsTestCase extends GemFireTestCase {
-
- /** The distributed system used in this test */
- protected DistributedSystem system;
-
- private StatisticsFactory factory() {
- return system;
- }
-
- /**
- * Creates the distributed system
- * @throws Exception
- */
- @Override
- public void setUp() throws Exception {
- this.system = getSystem();
- }
-
- /**
- * Closes the distributed system
- * @throws Exception
- */
- @Override
- public void tearDown() throws Exception {
- this.system.disconnect();
- this.system = null;
- }
-
- /**
- * Returns the distributed system used when creating statistics. It
- * determines whether or not shared memory is used.
- */
- protected abstract DistributedSystem getSystem();
-
- //////// Test methods
-
- /**
- * Tests <code>int</code> statistics
- */
- @Test
- public void testIntStatistics() {
- String statName1 = "one";
- String statName2 = "two";
- String statName3 = "three";
- String[] statNames = { statName1, statName2, statName3 };
-
- StatisticsType type =
- factory().createType(this.getUniqueName(), "", new
- StatisticDescriptor[] {
- factory().createIntGauge(statName1, "ONE", "x"),
- factory().createIntGauge(statName2, "TWO", "x"),
- factory().createIntGauge(statName3, "THREE", "x")
- });
-
- Statistics stats = factory().createAtomicStatistics(type, "Display");
- stats.setInt(statName1, 0);
- stats.setInt(statName2, 0);
- stats.setInt(statName3, 0);
-
- for (int j = 0; j < statNames.length; j++) {
- String statName = statNames[j];
- for (int i = 0; i < 10; i++) {
- stats.setInt(statName, i);
- stats.incInt(statName, 1);
- assertEquals(i + 1, stats.getInt(statName));
- }
- }
- }
-
- /**
- * Tests <code>long</code> statistics
- */
- @Test
- public void testLongStatistics() {
- String statName1 = "one";
- String statName2 = "two";
- String statName3 = "three";
- String[] statNames = { statName1, statName2, statName3 };
-
- StatisticsType type =
- factory().createType(this.getUniqueName(), "", new
- StatisticDescriptor[] {
- factory().createLongGauge(statName1, "ONE", "x"),
- factory().createLongGauge(statName2, "TWO", "x"),
- factory().createLongGauge(statName3, "THREE", "x")
- });
-
- Statistics stats = factory().createAtomicStatistics(type, "Display");
- stats.setLong(statName1, 0L);
- stats.setLong(statName2, 0L);
- stats.setLong(statName3, 0L);
-
- Random random = new Random();
-
- // Set/get some random long values
- for (int i = 0; i < 100; i++) {
- for (int j = 0; j < statNames.length; j++) {
- String statName = statNames[j];
- long value = random.nextLong();
- stats.setLong(statName, value);
- assertEquals(value, stats.getLong(statName));
- }
- }
-
- // Increment by some random values
- for (int i = 0; i < 100; i++) {
- for (int j = 0; j < statNames.length; j++) {
- String statName = statNames[j];
- long inc = random.nextLong();
- long before = stats.getLong(statName);
- stats.incLong(statName, inc);
- assertEquals(before + inc, stats.getLong(statName));
- }
- }
- }
-
- /**
- * Tests <code>double</code> statistics
- */
- @Test
- public void testDoubleStatistics() {
- String statName1 = "one";
- String statName2 = "two";
- String statName3 = "three";
- String[] statNames = { statName1, statName2, statName3 };
-
- StatisticsType type =
- factory().createType(this.getUniqueName(), "", new
- StatisticDescriptor[] {
- factory().createDoubleGauge(statName1, "ONE", "x"),
- factory().createDoubleGauge(statName2, "TWO", "x"),
- factory().createDoubleGauge(statName3, "THREE", "x")
- });
-
- Statistics stats = factory().createAtomicStatistics(type, "Display");
- stats.setDouble(statName1, 0.0);
- stats.setDouble(statName2, 0.0);
- stats.setDouble(statName3, 0.0);
-
- Random random = new Random();
-
- // Set/get some random double values
- for (int i = 0; i < 100; i++) {
- for (int j = 0; j < statNames.length; j++) {
- String statName = statNames[j];
- double value = random.nextDouble();
- stats.setDouble(statName, value);
- assertEquals(value, stats.getDouble(statName), 0.0);
- }
- }
-
- // Increment by some random values
- for (int i = 0; i < 100; i++) {
- for (int j = 0; j < statNames.length; j++) {
- String statName = statNames[j];
- double inc = random.nextDouble();
- double before = stats.getDouble(statName);
- stats.incDouble(statName, inc);
- assertEquals(before + inc, stats.getDouble(statName), 0.0);
- }
- }
- }
-
- /**
- * Tests that accessing an <code>int</code> stat throws the
- * appropriate exceptions.
- */
- @Test
- public void testAccessingIntStat() {
- String statName1 = "one";
-
- StatisticsType type =
- factory().createType(this.getUniqueName(), "", new
- StatisticDescriptor[] {
- factory().createIntGauge(statName1, "ONE", "x"),
- });
-
- Statistics stats = factory().createAtomicStatistics(type, "Display");
-
- stats.getInt(statName1);
- try {
- stats.getDouble(statName1);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.getLong(statName1);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
-
- stats.setInt(statName1, 4);
- try {
- stats.setDouble(statName1, 4.0);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.setLong(statName1, 4L);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
-
- stats.incInt(statName1, 4);
- try {
- stats.incDouble(statName1, 4.0);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.incLong(statName1, 4L);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- }
-
- /**
- * Tests that accessing a <code>long</code> stat throws the
- * appropriate exceptions.
- */
- @Test
- public void testAccessingLongStat() {
- String statName1 = "one";
-
- StatisticsType type =
- factory().createType(this.getUniqueName(), "", new
- StatisticDescriptor[] {
- factory().createLongGauge(statName1, "ONE", "x"),
- });
-
- Statistics stats = factory().createAtomicStatistics(type, "Display");
-
- stats.getLong(statName1);
- try {
- stats.getDouble(statName1);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.getInt(statName1);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
-
- stats.setLong(statName1, 4L);
- try {
- stats.setDouble(statName1, 4.0);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.setInt(statName1, 4);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
-
- stats.incLong(statName1, 4L);
- try {
- stats.incDouble(statName1, 4.0);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.incInt(statName1, 4);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- }
-
- /**
- * Tests that accessing an <code>double</code> stat throws the
- * appropriate exceptions.
- */
- @Test
- public void testAccessingDoubleStat() {
- String statName1 = "one";
-
- StatisticsType type =
- factory().createType(this.getUniqueName(), "", new
- StatisticDescriptor[] {
- factory().createDoubleGauge(statName1, "ONE", "x"),
- });
-
- Statistics stats = factory().createStatistics(type, "Display");
-
- stats.getDouble(statName1);
- try {
- stats.getInt(statName1);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.getLong(statName1);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
-
- stats.setDouble(statName1, 4.0);
- try {
- stats.setInt(statName1, 4);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.setLong(statName1, 4L);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
-
- stats.incDouble(statName1, 4.0);
- try {
- stats.incInt(statName1, 4);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- try {
- stats.incLong(statName1, 4L);
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/StatisticsTypeJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/StatisticsTypeJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/StatisticsTypeJUnitTest.java
deleted file mode 100644
index 1d221a2..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/StatisticsTypeJUnitTest.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * 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 com.gemstone.gemfire;
-
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
-
-/**
- * Tests the functionality of the {@link StatisticsType} class.
- *
- *
- */
-@Category(IntegrationTest.class)
-public class StatisticsTypeJUnitTest extends GemFireTestCase {
-
- private StatisticsFactory factory() {
- return InternalDistributedSystem.getAnyInstance();
- }
-
- /**
- * Get the offset of an unknown statistic
- */
- @Test
- public void testNameToIdUnknownStatistic() {
- StatisticDescriptor[] stats = {
- factory().createIntGauge("test", "TEST", "ms")
- };
-
- StatisticsType type = factory().createType("testNameToIdUnknownStatistic", "TEST", stats);
- assertEquals(0, type.nameToId("test"));
- try {
- type.nameToId("Fred");
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- }
-
- @Test
- public void testNameToDescriptorUnknownStatistic() {
- StatisticDescriptor[] stats = {
- factory().createIntGauge("test", "TEST", "ms")
- };
-
- StatisticsType type = factory().createType("testNameToDescriptorUnknownStatistic", "TEST", stats);
- assertEquals("test", type.nameToDescriptor("test").getName());
- try {
- type.nameToDescriptor("Fred");
- fail("Should have thrown an IllegalArgumentException");
-
- } catch (IllegalArgumentException ex) {
- // pass...
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluatorJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluatorJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluatorJUnitTest.java
index 6791dcc..8863059 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluatorJUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/admin/internal/MemberHealthEvaluatorJUnitTest.java
@@ -28,8 +28,8 @@ import org.junit.experimental.categories.Category;
import com.gemstone.gemfire.admin.GemFireHealth;
import com.gemstone.gemfire.admin.GemFireHealthConfig;
-import com.gemstone.gemfire.internal.GemFireStatSampler;
-import com.gemstone.gemfire.internal.ProcessStats;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
+import com.gemstone.gemfire.internal.statistics.platform.ProcessStats;
import com.gemstone.gemfire.internal.PureJavaMode;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/cache/management/MemoryThresholdsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/cache/management/MemoryThresholdsDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/cache/management/MemoryThresholdsDUnitTest.java
index baad698..c3a490f 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/cache/management/MemoryThresholdsDUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/cache/management/MemoryThresholdsDUnitTest.java
@@ -67,9 +67,9 @@ import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
import com.gemstone.gemfire.internal.AvailablePortHelper;
-import com.gemstone.gemfire.internal.GemFireStatSampler;
-import com.gemstone.gemfire.internal.LocalStatListener;
-import com.gemstone.gemfire.internal.StatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
+import com.gemstone.gemfire.internal.statistics.LocalStatListener;
+import com.gemstone.gemfire.internal.statistics.StatisticsImpl;
import com.gemstone.gemfire.internal.cache.DistributedRegion;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.PartitionedRegion;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/codeAnalysis/decode/CompiledClass.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/codeAnalysis/decode/CompiledClass.java b/geode-core/src/test/java/com/gemstone/gemfire/codeAnalysis/decode/CompiledClass.java
index 9e03956..43175f6 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/codeAnalysis/decode/CompiledClass.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/codeAnalysis/decode/CompiledClass.java
@@ -177,7 +177,7 @@ public class CompiledClass implements Comparable {
// in junit
String name = fullyQualifiedName().replace('/', '.');
if (name.startsWith("com.gemstone.gemfire.internal.shared.NativeCallsJNAImpl")
- || name.startsWith("com.gemstone.gemfire.internal.HostStatHelper")) {
+ || name.startsWith("com.gemstone.gemfire.internal.statistics.HostStatHelper")) {
return false;
}
try {
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/DataSerializableJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/DataSerializableJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/DataSerializableJUnitTest.java
index 273d3c6..13ab363 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/DataSerializableJUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/DataSerializableJUnitTest.java
@@ -64,6 +64,7 @@ import com.gemstone.gemfire.DataSerializable;
import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.Instantiator;
import com.gemstone.gemfire.SystemFailure;
+import com.gemstone.gemfire.internal.statistics.StatArchiveWriter;
import com.gemstone.gemfire.internal.tcp.ByteBufferInputStream;
import com.gemstone.gemfire.test.junit.categories.UnitTest;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/GemFireStatSamplerJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/GemFireStatSamplerJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/GemFireStatSamplerJUnitTest.java
deleted file mode 100644
index ef07633..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/GemFireStatSamplerJUnitTest.java
+++ /dev/null
@@ -1,612 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.distributed.DistributedSystem;
-import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import com.gemstone.gemfire.internal.GemFireStatSampler.LocalStatListenerImpl;
-import com.gemstone.gemfire.internal.cache.control.HeapMemoryMonitor;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.statistics.SampleCollector;
-import com.gemstone.gemfire.internal.statistics.StatArchiveHandler;
-import com.gemstone.gemfire.internal.statistics.StatArchiveHandlerConfig;
-import com.gemstone.gemfire.internal.stats50.VMStats50;
-import com.gemstone.gemfire.internal.util.StopWatch;
-import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
-import org.apache.logging.log4j.Logger;
-import org.junit.*;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TestName;
-
-import java.io.File;
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
-import static org.junit.Assert.*;
-import static org.junit.Assume.assumeFalse;
-
-/**
- * Integration tests for GemFireStatSampler.
- *
- * @since GemFire 7.0
- */
-@Category(IntegrationTest.class)
-public class GemFireStatSamplerJUnitTest extends StatSamplerTestCase {
-
- private static final Logger logger = LogService.getLogger();
-
- private static final int STAT_SAMPLE_RATE = 1000;
-
- @Rule
- public TestName testName = new TestName();
-
- private DistributedSystem system;
- private File testDir = new File(getClass().getSimpleName());
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- final String dirName = GemFireStatSamplerJUnitTest.class.getSimpleName();
- final File dir = new File(dirName);
- if (dir.exists()) {
- FileUtil.delete(dir);
- }
- }
-
- @Before
- public void setUp() throws Exception {
- if (!this.testDir.exists()) {
- this.testDir.mkdir();
- }
- assertTrue(this.testDir.exists());
- }
-
- /**
- * Removes the loner DistributedSystem at the end of each test.
- */
- @After
- public void tearDown() throws Exception {
- System.clearProperty(GemFireStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY);
- disconnect();
- }
-
- /**
- * Tests the majority of getters and the basic functionality of the sampler.
- *
- * This test is skipped when running on Windows 7 because ProcessStats is not created for this OS. See #45395.
- */
- @Test
- public void testBasics() throws Exception {
- final String osName = System.getProperty("os.name", "unknown");
- assumeFalse(osName.equals("Windows 7"));
-
- connect(createGemFireProperties());
-
- GemFireStatSampler statSampler = getGemFireStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- assertEquals(0, statSampler.getArchiveFileSizeLimit());
- assertEquals(0, statSampler.getArchiveDiskSpaceLimit());
- assertEquals(STAT_SAMPLE_RATE, statSampler.getSampleRate());
- assertEquals(true, statSampler.isSamplingEnabled());
-
- int statsCount = statSampler.getStatisticsManager().getStatisticsCount();
-
- assertEquals(statsCount, statSampler.getStatisticsModCount());
- assertEquals(statsCount, statSampler.getStatisticsManager().getStatisticsCount());
- assertEquals(statsCount, statSampler.getStatistics().length);
-
- assertEquals(getStatisticsManager().getId(), statSampler.getSystemId());
- assertTrue(statSampler.getSystemStartTime() < System.currentTimeMillis());
- assertEquals(SocketCreator.getHostName(SocketCreator.getLocalHost()),
- statSampler.getSystemDirectoryPath());
-
- AllStatistics allStats = new AllStatistics(statSampler);
-
- VMStatsContract vmStats = statSampler.getVMStats();
- assertNotNull(vmStats);
- assertTrue(vmStats instanceof VMStats50);
- /* NOTE: VMStats50 is not an instance of Statistics but instead its
- * instance contains 3 instances of Statistics:
- * 1) vmStats
- * 2) heapMemStats
- * 3) nonHeapMemStats
- */
-
- Method getProcessStats = getGemFireStatSampler().getClass().getMethod("getProcessStats");
- assertNotNull(getProcessStats);
-
- ProcessStats processStats = statSampler.getProcessStats();
- if (osName.equals("SunOS")) {
- assertNotNull(processStats);
- assertTrue(PureJavaMode.osStatsAreAvailable());
- assertTrue(allStats.containsStatisticsType("SolarisProcessStats"));
- assertTrue(allStats.containsStatisticsType("SolarisSystemStats"));
- } else if (osName.startsWith("Windows")) {
- // fails on Windows 7: 45395 "ProcessStats are not created on Windows 7"
- assertNotNull("ProcessStats were not created on " + osName, processStats);
- assertTrue(PureJavaMode.osStatsAreAvailable());
- assertTrue(allStats.containsStatisticsType("WindowsProcessStats"));
- assertTrue(allStats.containsStatisticsType("WindowsSystemStats"));
- } else if (osName.startsWith("Linux")) {
- assertNotNull(processStats);
- assertTrue(PureJavaMode.osStatsAreAvailable());
- assertTrue(allStats.containsStatisticsType("LinuxProcessStats"));
- assertTrue(allStats.containsStatisticsType("LinuxSystemStats"));
- } else if (osName.equals("Mac OS X")) {
- assertNull(processStats);
- assertFalse(PureJavaMode.osStatsAreAvailable());
- assertFalse(allStats.containsStatisticsType("OSXProcessStats"));
- assertFalse(allStats.containsStatisticsType("OSXSystemStats"));
- } else {
- assertNull(processStats);
- }
-
- String productDesc = statSampler.getProductDescription();
- assertTrue(productDesc.contains(GemFireVersion.getGemFireVersion()));
- assertTrue(productDesc.contains(GemFireVersion.getBuildId()));
- assertTrue(productDesc.contains(GemFireVersion.getSourceDate()));
- }
-
- /**
- * Tests that the configured archive file is created and exists.
- */
- @Test
- public void testArchiveFileExists() throws Exception {
- final String dir = this.testDir.getName();
- final String archiveFileName = dir + File.separator + this.testName + ".gfs";
-
- final File archiveFile1 = new File(dir + File.separator + this.testName + ".gfs");
-
- Properties props = createGemFireProperties();
- props.setProperty(STATISTIC_ARCHIVE_FILE, archiveFileName);
- connect(props);
-
- GemFireStatSampler statSampler = getGemFireStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- final File archiveFile = statSampler.getArchiveFileName();
- assertNotNull(archiveFile);
- assertEquals(archiveFile1, archiveFile);
-
- waitForFileToExist(archiveFile, 5000, 10);
-
- assertTrue("File name incorrect: archiveFile.getName()=" + archiveFile.getName() +
- " archiveFile.getAbsolutePath()=" + archiveFile.getAbsolutePath() +
- " getCanonicalPath()" + archiveFile.getCanonicalPath(),
- archiveFileName.contains(archiveFile.getName()));
- }
-
- /**
- * Tests the statistics sample rate within an acceptable margin of error.
- */
- @Test
- public void testSampleRate() throws Exception {
- connect(createGemFireProperties());
-
- GemFireStatSampler statSampler = getGemFireStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- assertEquals(STAT_SAMPLE_RATE, statSampler.getSampleRate());
-
- assertTrue(getStatisticsManager().getStatListModCount() > 0);
-
- List<Statistics> statistics = getStatisticsManager().getStatsList();
- assertNotNull(statistics);
- assertTrue(statistics.size() > 0);
-
- StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
- Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
- assertEquals(1, statsArray.length);
-
- final Statistics statSamplerStats = statsArray[0];
- final int initialSampleCount = statSamplerStats.getInt("sampleCount");
- final int expectedSampleCount = initialSampleCount + 2;
-
- waitForExpectedStatValue(statSamplerStats, "sampleCount", expectedSampleCount, 5000, 10);
- }
-
- /**
- * Adds a LocalStatListener for an individual stat. Validates that it
- * receives notifications. Removes the listener and validates that it
- * was in fact removed and no longer receives notifications.
- */
- @Test
- public void testLocalStatListener() throws Exception {
- connect(createGemFireProperties());
-
- GemFireStatSampler statSampler = getGemFireStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- Method getLocalListeners = getGemFireStatSampler().getClass().getMethod("getLocalListeners");
- assertNotNull(getLocalListeners);
-
- Method addLocalStatListener = getGemFireStatSampler().getClass().getMethod("addLocalStatListener", LocalStatListener.class, Statistics.class, String.class);
- assertNotNull(addLocalStatListener);
-
- Method removeLocalStatListener = getGemFireStatSampler().getClass().getMethod("removeLocalStatListener", LocalStatListener.class);
- assertNotNull(removeLocalStatListener);
-
- // validate that there are no listeners
- assertTrue(statSampler.getLocalListeners().isEmpty());
-
- // add a listener for sampleCount stat in StatSampler statistics
- StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
- Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
- assertEquals(1, statsArray.length);
-
- final Statistics statSamplerStats = statsArray[0];
- final String statName = "sampleCount";
- final AtomicInteger sampleCountValue = new AtomicInteger(0);
- final AtomicInteger sampleCountChanged = new AtomicInteger(0);
-
- LocalStatListener listener = new LocalStatListener() {
- public void statValueChanged(double value) {
- sampleCountValue.set((int)value);
- sampleCountChanged.incrementAndGet();
- }
- };
-
- statSampler.addLocalStatListener(listener, statSamplerStats, statName);
- assertTrue(statSampler.getLocalListeners().size() == 1);
-
- // there's a level of indirection here and some protected member fields
- LocalStatListenerImpl lsli = (LocalStatListenerImpl)
- statSampler.getLocalListeners().iterator().next();
- assertEquals("sampleCount", lsli.stat.getName());
-
- // wait for the listener to update 4 times
- final int expectedChanges = 4;
- boolean done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 5000; done = (sampleCountChanged.get() >= expectedChanges)) {
- Thread.sleep(10);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertTrue("Waiting for sampleCountChanged >= " + expectedChanges, done);
-
- // validate that the listener fired and updated the value
- assertTrue(sampleCountValue.get() > 0);
- assertTrue(sampleCountChanged.get() >= expectedChanges);
-
- // remove the listener
- statSampler.removeLocalStatListener(listener);
- final int expectedSampleCountValue = sampleCountValue.get();
- final int expectedSampleCountChanged = sampleCountChanged.get();
-
- // validate that there are no listeners now
- assertTrue(statSampler.getLocalListeners().isEmpty());
-
- // wait for 2 stat samples to occur
- waitForStatSample(statSamplerStats, expectedSampleCountValue, 5000, 10);
-
- // validate that the listener did not fire
- assertEquals(expectedSampleCountValue, sampleCountValue.get());
- assertEquals(expectedSampleCountChanged, sampleCountChanged.get());
- }
-
- /**
- * Invokes stop() and then validates that the sampler did in fact stop.
- */
- @Test
- public void testStop() throws Exception {
- connect(createGemFireProperties());
-
- GemFireStatSampler statSampler = getGemFireStatSampler();
- assertTrue(statSampler.waitForInitialization(5000));
-
- // validate the stat sampler is running
- StatisticsType statSamplerType = getStatisticsManager().findType("StatSampler");
- Statistics[] statsArray = getStatisticsManager().findStatisticsByType(statSamplerType);
- assertEquals(1, statsArray.length);
-
- final Statistics statSamplerStats = statsArray[0];
- final int initialSampleCount = statSamplerStats.getInt("sampleCount");
- final int expectedSampleCount = initialSampleCount + 2;
-
- waitForStatSample(statSamplerStats, expectedSampleCount, 20000, 10);
-
- // stop the stat sampler
- statSampler.stop();
-
- // validate the stat sampler has stopped
- final int stoppedSampleCount = statSamplerStats.getInt("sampleCount");
-
- // the following should timeout rather than complete
- assertStatValueDoesNotChange(statSamplerStats, "sampleCount", stoppedSampleCount, 5000, 10);
-
- assertEquals(stoppedSampleCount, statSamplerStats.getInt("sampleCount"));
- }
-
- /**
- * Verifies that archive rolling works correctly when archive-file-size-limit
- * is specified.
- */
- @Test
- public void testArchiveRolling() throws Exception {
- final String dirName = this.testDir.getName() + File.separator + this.testName;
- new File(dirName).mkdirs();
- final String archiveFileName = dirName + File.separator + this.testName + ".gfs";
-
- final File archiveFile = new File(archiveFileName);
- final File archiveFile1 = new File(dirName + File.separator + this.testName + "-01-01.gfs");
- final File archiveFile2 = new File(dirName + File.separator + this.testName + "-01-02.gfs");
- final File archiveFile3 = new File(dirName + File.separator + this.testName + "-01-03.gfs");
-
- // set the system property to use KB instead of MB for file size
- System.setProperty(HostStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY, "true");
- Properties props = createGemFireProperties();
- props.setProperty(ARCHIVE_FILE_SIZE_LIMIT, "1");
- props.setProperty(ARCHIVE_DISK_SPACE_LIMIT, "0");
- props.setProperty(STATISTIC_ARCHIVE_FILE, archiveFileName);
- connect(props);
-
- assertTrue(getGemFireStatSampler().waitForInitialization(5000));
-
- boolean done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 4000; done = (getSampleCollector() != null && getSampleCollector().getStatArchiveHandler() != null)) {
- Thread.sleep(10);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertTrue("Waiting for getSampleCollector().getStatArchiveHandler() to not be null", done);
-
- StatArchiveHandler statArchiveHandler = getSampleCollector().getStatArchiveHandler();
- StatArchiveHandlerConfig config = statArchiveHandler.getStatArchiveHandlerConfig();
- assertEquals(1 * 1024, config.getArchiveFileSizeLimit());
-
- waitForFileToExist(archiveFile, 4000, 10);
- waitForFileToExist(archiveFile1, 4000, 10);
- waitForFileToExist(archiveFile2, 4000, 10);
- waitForFileToExist(archiveFile3, 4000, 10);
- }
-
- /**
- * Verifies that archive removal works correctly when archive-disk-space-limit
- * is specified.
- */
- @Test
- public void testArchiveRemoval() throws Exception {
- final String dirName = this.testDir.getName();// + File.separator + this.testName;
- new File(dirName).mkdirs();
- final String archiveFileName = dirName + File.separator + this.testName + ".gfs";
-
- final File archiveFile = new File(archiveFileName);
- final File archiveFile1 = new File(dirName + File.separator + this.testName + "-01-01.gfs");
- final File archiveFile2 = new File(dirName + File.separator + this.testName + "-01-02.gfs");
- final File archiveFile3 = new File(dirName + File.separator + this.testName + "-01-03.gfs");
- final File archiveFile4 = new File(dirName + File.separator + this.testName + "-01-04.gfs");
-
- final int sampleRate = 1000;
-
- // set the system property to use KB instead of MB for file size
- System.setProperty(HostStatSampler.TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY, "true");
- Properties props = createGemFireProperties();
- props.setProperty(STATISTIC_ARCHIVE_FILE, archiveFileName);
- props.setProperty(ARCHIVE_FILE_SIZE_LIMIT, "1");
- props.setProperty(ARCHIVE_DISK_SPACE_LIMIT, "12");
- props.setProperty(STATISTIC_SAMPLE_RATE, String.valueOf(sampleRate));
- connect(props);
-
- assertTrue(getGemFireStatSampler().waitForInitialization(5000));
-
- boolean exists1 = false;
- boolean exists2 = false;
- boolean exists3 = false;
- boolean exists4 = false;
- boolean exists = false;
- boolean done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 10*sampleRate;) {
- exists1 = exists1 || archiveFile1.exists();
- exists2 = exists2 || archiveFile2.exists();
- exists3 = exists3 || archiveFile3.exists();
- exists4 = exists4 || archiveFile4.exists();
- exists = exists || archiveFile.exists();
- done = exists1 && exists2 && exists3 && exists4 && exists;
- if (!done) {
- Thread.sleep(10);
- }
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertTrue("Waiting for archive files to exist:"
- + " exists1=" + exists1
- + " exists2=" + exists2
- + " exists3=" + exists3
- + " exists4=" + exists4
- + " exists=" + exists, done);
-
- waitForFileToDelete(archiveFile1, 10*sampleRate, 10);
- }
-
- @Test
- public void testLocalStatListenerRegistration() throws Exception {
- connect(createGemFireProperties());
-
- final GemFireStatSampler statSampler = getGemFireStatSampler();
- statSampler.waitForInitialization(5000);
-
- final AtomicBoolean flag = new AtomicBoolean(false);
- final LocalStatListener listener = new LocalStatListener(){
- public void statValueChanged(double value) {
- flag.set(true);
- }
- };
-
- final String tenuredPoolName = HeapMemoryMonitor.getTenuredMemoryPoolMXBean().getName();
- logger.info("TenuredPoolName: {}", tenuredPoolName);
-
- final List<Statistics> list = ((StatisticsManager)this.system).getStatsList();
- assertFalse(list.isEmpty());
-
- boolean done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 5000;) {
- Thread.sleep(10);
- int i=0;
- synchronized (list) {
- for (Object obj : list) {
- ++i;
- logger.info("List:{}:{}", i, obj);
- if (obj instanceof StatisticsImpl) {
- StatisticsImpl si = (StatisticsImpl)obj;
- logger.info("stat:{}", si.getTextId());
- if (si.getTextId().contains(tenuredPoolName)) {
- statSampler.addLocalStatListener(listener, si, "currentUsedMemory");
- done = true;
- }
- }
- }
- }
- //done = false;
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertTrue("Waiting for " + tenuredPoolName + " statistics to be added to create listener for", done);
-
- assertTrue("expected at least one stat listener, found " +
- statSampler.getLocalListeners().size(),
- statSampler.getLocalListeners().size() > 0);
-
- long maxTenuredMemory = HeapMemoryMonitor.getTenuredMemoryPoolMXBean()
- .getUsage().getMax();
-
- //byte[] bytes = new byte[1024 * 1024 * 10];
- byte[] bytes = new byte[(int)(maxTenuredMemory*0.01)];
- Arrays.fill(bytes, Byte.MAX_VALUE);
-
- done = false;
- try {
- for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < 5000; done = (flag.get())) {
- Thread.sleep(10);
- }
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- assertTrue("Waiting for listener to set flag to true", done);
- }
-
- @Override
- protected StatisticsManager getStatisticsManager() {
- return (InternalDistributedSystem)this.system;
- }
-
- protected OsStatisticsFactory getOsStatisticsFactory() {
- return (InternalDistributedSystem)this.system;
- }
-
- private GemFireStatSampler getGemFireStatSampler() {
- return ((InternalDistributedSystem)this.system).getStatSampler();
- }
-
- private SampleCollector getSampleCollector() {
- return getGemFireStatSampler().getSampleCollector();
- }
-
- private Properties createGemFireProperties() {
- Properties props = new Properties();
- props.setProperty(STATISTIC_SAMPLING_ENABLED, "true"); // TODO: test true/false
- props.setProperty(ENABLE_TIME_STATISTICS, "true"); // TODO: test true/false
- props.setProperty(STATISTIC_SAMPLE_RATE, String.valueOf(STAT_SAMPLE_RATE));
- props.setProperty(ARCHIVE_FILE_SIZE_LIMIT, "0");
- props.setProperty(ARCHIVE_DISK_SPACE_LIMIT, "0");
- props.setProperty(MCAST_PORT, "0");
- props.setProperty(LOCATORS, "");
- return props;
- }
-
- /**
- * Creates a fresh loner DistributedSystem for each test. Note
- * that the DistributedSystem is the StatisticsManager/Factory/etc.
- */
- @SuppressWarnings("deprecation")
- private void connect(Properties props) {
- this.system = DistributedSystem.connect(props);
- }
-
- @SuppressWarnings("deprecation")
- private void disconnect() {
- if (this.system != null) {
- this.system.disconnect();
- this.system = null;
- }
- }
-
-// public static class AsyncInvoker {
-// public static AsyncInvocation invokeAsync(Runnable r) {
-// return invokeAsync(r, "run", new Object[0]);
-// }
-// public static AsyncInvocation invokeAsync(Callable c) {
-// return invokeAsync(c, "call", new Object[0]);
-// }
-// public static AsyncInvocation invokeAsync(
-// final Object o, final String methodName, final Object[] args) {
-// AsyncInvocation ai =
-// new AsyncInvocation(o, methodName, new Runnable() {
-// public void run() {
-// MethExecutorResult result =
-// MethExecutor.executeObject(o, methodName, args);
-// if (result.exceptionOccurred()) {
-// throw new AsyncInvocationException(result.getException());
-// }
-// AsyncInvocation.setReturnValue(result.getResult());
-// }
-// });
-// ai.start();
-// return ai;
-// }
-//
-// public static class AsyncInvocationException extends RuntimeException {
-// private static final long serialVersionUID = -5522299018650622945L;
-// /**
-// * Creates a new <code>AsyncInvocationException</code>.
-// */
-// public AsyncInvocationException(String message) {
-// super(message);
-// }
-//
-// /**
-// * Creates a new <code>AsyncInvocationException</code> that was
-// * caused by a given exception
-// */
-// public AsyncInvocationException(String message, Throwable thr) {
-// super(message, thr);
-// }
-//
-// /**
-// * Creates a new <code>AsyncInvocationException</code> that was
-// * caused by a given exception
-// */
-// public AsyncInvocationException(Throwable thr) {
-// super(thr.getMessage(), thr);
-// }
-// }
-// }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/LocalStatisticsImplJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/LocalStatisticsImplJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/LocalStatisticsImplJUnitTest.java
deleted file mode 100644
index a9b1ec7..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/LocalStatisticsImplJUnitTest.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.*;
-
-import java.util.function.DoubleSupplier;
-import java.util.function.IntSupplier;
-import java.util.function.LongSupplier;
-
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.internal.LocalStatisticsImpl;
-import com.gemstone.gemfire.internal.StatisticsImpl;
-import com.gemstone.gemfire.internal.StatisticsManager;
-import com.gemstone.gemfire.internal.StatisticsTypeImpl;
-import com.gemstone.gemfire.test.junit.categories.UnitTest;
-
-import org.apache.commons.lang.ObjectUtils.Null;
-import org.apache.logging.log4j.Logger;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.ExpectedException;
-
-@Category(UnitTest.class)
-public class LocalStatisticsImplJUnitTest {
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- private StatisticsImpl stats;
-
- @Before
- public void createStats() {
- final StatisticsTypeImpl type = mock(StatisticsTypeImpl.class);
- when(type.getIntStatCount()).thenReturn(5);
- when(type.getDoubleStatCount()).thenReturn(5);
- when(type.getLongStatCount()).thenReturn(5);
- final String textId = "";
- final long numbericId = 0;
- final long uniqueId = 0;
- final int osStatFlags = 0;
- final boolean atomicIncrements = false;
- final StatisticsManager system = mock(StatisticsManager.class);
- stats = new LocalStatisticsImpl(type, textId, numbericId, uniqueId, atomicIncrements, osStatFlags, system);
- }
-
- @Test
- public void invokeIntSuppliersShouldUpdateStats() {
- IntSupplier supplier1 = mock(IntSupplier.class);
- when(supplier1.getAsInt()).thenReturn(23);
- stats.setIntSupplier(4, supplier1);
- assertEquals(0, stats.invokeSuppliers());
-
- verify(supplier1).getAsInt();
- assertEquals(23, stats.getInt(4));
- }
-
- @Test
- public void invokeLongSuppliersShouldUpdateStats() {
- LongSupplier supplier1 = mock(LongSupplier.class);
- when(supplier1.getAsLong()).thenReturn(23L);
- stats.setLongSupplier(4, supplier1);
- assertEquals(0, stats.invokeSuppliers());
-
- verify(supplier1).getAsLong();
- assertEquals(23L, stats.getLong(4));
- }
-
- @Test
- public void invokeDoubleSuppliersShouldUpdateStats() {
- DoubleSupplier supplier1 = mock(DoubleSupplier.class);
- when(supplier1.getAsDouble()).thenReturn(23.3);
- stats.setDoubleSupplier(4, supplier1);
- assertEquals(0, stats.invokeSuppliers());
-
- verify(supplier1).getAsDouble();
- assertEquals(23.3, stats.getDouble(4), 0.1f);
- }
-
- @Test
- public void getSupplierCountShouldReturnCorrectCount() {
- IntSupplier supplier1 = mock(IntSupplier.class);
- stats.setIntSupplier(4, supplier1);
- assertEquals(1, stats.getSupplierCount());
- }
-
- @Test
- public void invokeSuppliersShouldCatchSupplierErrorsAndReturnCount() {
- IntSupplier supplier1 = mock(IntSupplier.class);
- when(supplier1.getAsInt()).thenThrow(NullPointerException.class);
- stats.setIntSupplier(4, supplier1);
- assertEquals(1, stats.invokeSuppliers());
-
- verify(supplier1).getAsInt();
- }
-
- @Test
- public void invokeSuppliersShouldLogErrorOnlyOnce() {
- final Logger originalLogger = StatisticsImpl.logger;
- try {
- final Logger logger = mock(Logger.class);
- StatisticsImpl.logger = logger;
- IntSupplier supplier1 = mock(IntSupplier.class);
- when(supplier1.getAsInt()).thenThrow(NullPointerException.class);
- stats.setIntSupplier(4, supplier1);
- assertEquals(1, stats.invokeSuppliers());
- verify(logger, times(1)).warn(anyString(), anyString(), anyInt(), isA(NullPointerException.class));
- assertEquals(1, stats.invokeSuppliers());
- //Make sure the logger isn't invoked again
- verify(logger, times(1)).warn(anyString(), anyString(), anyInt(), isA(NullPointerException.class));
- } finally {
- StatisticsImpl.logger = originalLogger;
- }
- }
-
- @Test
- public void badSupplierParamShouldThrowError() {
- IntSupplier supplier1 = mock(IntSupplier.class);
- when(supplier1.getAsInt()).thenReturn(23);
- thrown.expect(IllegalArgumentException.class);
- stats.setIntSupplier(23, supplier1);
- }
-}
[18/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveReader.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveReader.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveReader.java
deleted file mode 100644
index 0947b0d..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatArchiveReader.java
+++ /dev/null
@@ -1,3338 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.GemFireIOException;
-import com.gemstone.gemfire.InternalGemFireException;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-import com.gemstone.gemfire.internal.logging.DateFormatter;
-
-import java.io.BufferedInputStream;
-import java.io.DataInputStream;
-import java.io.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.text.DateFormat;
-import java.text.NumberFormat;
-import java.text.SimpleDateFormat;
-import java.util.AbstractList;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.SimpleTimeZone;
-import java.util.TimeZone;
-import java.util.zip.GZIPInputStream;
-
-/**
- * StatArchiveReader provides APIs to read statistic snapshots from an archive
- * file.
- */
-public class StatArchiveReader implements StatArchiveFormat {
-
- protected static final NumberFormat nf = NumberFormat.getNumberInstance();
- static {
- nf.setMaximumFractionDigits(2);
- nf.setGroupingUsed(false);
- }
-
- private final StatArchiveFile[] archives;
- private boolean dump;
- private boolean closed = false;
-
- /**
- * Creates a StatArchiveReader that will read the named archive file.
- * @param autoClose if its <code>true</code> then the reader will close
- * input files as soon as it finds their end.
- * @throws IOException if <code>archiveName</code> could not be opened
- * read, or closed.
- */
- public StatArchiveReader(File[] archiveNames, ValueFilter[] filters, boolean autoClose)
- throws IOException
- {
- this.archives = new StatArchiveFile[archiveNames.length];
- this.dump = Boolean.getBoolean("StatArchiveReader.dumpall");
- for (int i=0; i < archiveNames.length; i++) {
- this.archives[i] = new StatArchiveFile(this, archiveNames[i], dump, filters);
- }
-
- update(false, autoClose);
-
- if (this.dump || Boolean.getBoolean("StatArchiveReader.dump")) {
- this.dump(new PrintWriter(System.out));
- }
- }
-
- /**
- * Creates a StatArchiveReader that will read the named archive file.
- * @throws IOException if <code>archiveName</code> could not be opened
- * read, or closed.
- */
- public StatArchiveReader(String archiveName) throws IOException {
- this(new File[]{new File(archiveName)}, null, false);
- }
-
- /**
- * Returns an array of stat values that match the specified spec.
- * If nothing matches then an empty array is returned.
- */
- public StatValue[] matchSpec(StatSpec spec) {
- if (spec.getCombineType() == StatSpec.GLOBAL) {
- StatValue[] allValues = matchSpec(new RawStatSpec(spec));
- if (allValues.length == 0) {
- return allValues;
- } else {
- ComboValue cv = new ComboValue(allValues);
- // need to save this in reader's combo value list
- return new StatValue[]{cv};
- }
- } else {
- List l = new ArrayList();
- StatArchiveReader.StatArchiveFile[] archives = getArchives();
- for (int i=0; i < archives.length; i++) {
- StatArchiveFile f = archives[i];
- if (spec.archiveMatches(f.getFile())) {
- f.matchSpec(spec, l);
- }
- }
- StatValue[] result = new StatValue[l.size()];
- return (StatValue[])l.toArray(result);
- }
- }
-
- /**
- * Checks to see if any archives have changed since the StatArchiverReader
- * instance was created or last updated. If an archive has additional
- * samples then those are read the resource instances maintained by the
- * reader are updated.
- * <p>Once closed a reader can no longer be updated.
- * @return true if update read some new data.
- * @throws IOException if an archive could not be opened
- * read, or closed.
- */
- public boolean update() throws IOException {
- return update(true, false);
- }
- private boolean update(boolean doReset, boolean autoClose) throws IOException {
- if (this.closed) {
- return false;
- }
- boolean result = false;
- StatArchiveReader.StatArchiveFile[] archives = getArchives();
- for (int i=0; i < archives.length; i++) {
- StatArchiveFile f = archives[i];
- if (f.update(doReset)) {
- result = true;
- }
- if (autoClose) {
- f.close();
- }
- }
- return result;
- }
-
- /**
- * Returns an unmodifiable list of all the {@link ResourceInst}
- * this reader contains.
- */
- public List getResourceInstList() {
- return new ResourceInstList();
- }
-
- public StatArchiveFile[] getArchives() {
- return this.archives;
- }
-
- /**
- * Closes all archives.
- */
- public void close() throws IOException {
- if (!this.closed) {
- StatArchiveReader.StatArchiveFile[] archives = getArchives();
- for (int i=0; i < archives.length; i++) {
- StatArchiveFile f = archives[i];
- f.close();
- }
- this.closed = true;
- }
- }
-
- private int getMemoryUsed() {
- int result = 0;
- StatArchiveReader.StatArchiveFile[] archives = getArchives();
- for (int i=0; i < archives.length; i++) {
- StatArchiveFile f = archives[i];
- result += f.getMemoryUsed();
- }
- return result;
- }
-
- private void dump(PrintWriter stream) {
- StatArchiveReader.StatArchiveFile[] archives = getArchives();
- for (int i=0; i < archives.length; i++) {
- StatArchiveFile f = archives[i];
- f.dump(stream);
- }
- }
-
- protected static double bitsToDouble(int type, long bits) {
- switch (type) {
- case BOOLEAN_CODE:
- case BYTE_CODE:
- case CHAR_CODE:
- case WCHAR_CODE:
- case SHORT_CODE:
- case INT_CODE:
- case LONG_CODE:
- return bits;
- case FLOAT_CODE:
- return Float.intBitsToFloat((int)bits);
- case DOUBLE_CODE:
- return Double.longBitsToDouble(bits);
- default:
- throw new InternalGemFireException(LocalizedStrings.StatArchiveReader_UNEXPECTED_TYPECODE_0.toLocalizedString(Integer.valueOf(type)));
- }
- }
-
- /**
- * Simple utility to read and dump statistic archive.
- */
- public static void main(String args[]) throws IOException {
- String archiveName = null;
- if (args.length > 1) {
- System.err.println("Usage: [archiveName]");
- System.exit(1);
- } else if (args.length == 1) {
- archiveName = args[0];
- } else {
- archiveName = "statArchive.gfs";
- }
- StatArchiveReader reader = new StatArchiveReader(archiveName);
- System.out.println("DEBUG: memory used = " + reader.getMemoryUsed());
- reader.close();
- }
-
- /**
- * Wraps an instance of StatSpec but alwasy returns a combine type of NONE.
- */
- private static class RawStatSpec implements StatSpec {
- private final StatSpec spec;
- RawStatSpec(StatSpec wrappedSpec) {
- this.spec = wrappedSpec;
- }
- public int getCombineType() {
- return StatSpec.NONE;
- }
- public boolean typeMatches(String typeName) {
- return spec.typeMatches(typeName);
- }
- public boolean statMatches(String statName) {
- return spec.statMatches(statName);
- }
- public boolean instanceMatches(String textId, long numericId) {
- return spec.instanceMatches(textId, numericId);
- }
- public boolean archiveMatches(File archive) {
- return spec.archiveMatches(archive);
- }
- }
-
- private class ResourceInstList extends AbstractList {
- protected ResourceInstList() {
- // nothing needed.
- }
- @Override
- public Object get(int idx) {
- int archiveIdx = 0;
- StatArchiveReader.StatArchiveFile[] archives = getArchives();
- for (int i=0; i < archives.length; i++) {
- StatArchiveFile f = archives[i];
- if (idx < (archiveIdx + f.resourceInstSize)) {
- return f.resourceInstTable[idx - archiveIdx];
- }
- archiveIdx += f.resourceInstSize;
- }
- return null;
- }
- @Override
- public int size() {
- int result = 0;
- StatArchiveReader.StatArchiveFile[] archives = getArchives();
- for (int i=0; i < archives.length; i++) {
- result += archives[i].resourceInstSize;
- }
- return result;
- }
- }
-
- /**
- * Describes a single statistic.
- */
- public static class StatDescriptor {
- private boolean loaded;
- private String name;
- private final int offset;
- private final boolean isCounter;
- private final boolean largerBetter;
- private final byte typeCode;
- private String units;
- private String desc;
-
- protected void dump(PrintWriter stream) {
- stream.println(" " + name + ": type=" + typeCode + " offset=" + offset
- + (isCounter? " counter" : "")
- + " units=" + units
- + " largerBetter=" + largerBetter
- + " desc=" + desc);
- }
-
- protected StatDescriptor(String name, int offset, boolean isCounter,
- boolean largerBetter,
- byte typeCode, String units, String desc) {
- this.loaded = true;
- this.name = name;
- this.offset = offset;
- this.isCounter = isCounter;
- this.largerBetter = largerBetter;
- this.typeCode = typeCode;
- this.units = units;
- this.desc = desc;
- }
- public boolean isLoaded() {
- return this.loaded;
- }
- void unload() {
- this.loaded = false;
- this.name = null;
- this.units = null;
- this.desc = null;
- }
- /**
- * Returns the type code of this statistic.
- * It will be one of the following values:
- * <ul>
- * <li> {@link #BOOLEAN_CODE}
- * <li> {@link #WCHAR_CODE}
- * <li> {@link #CHAR_CODE}
- * <li> {@link #BYTE_CODE}
- * <li> {@link #SHORT_CODE}
- * <li> {@link #INT_CODE}
- * <li> {@link #LONG_CODE}
- * <li> {@link #FLOAT_CODE}
- * <li> {@link #DOUBLE_CODE}
- * </ul>
- */
- public byte getTypeCode() {
- return this.typeCode;
- }
- /**
- * Returns the name of this statistic.
- */
- public String getName() {
- return this.name;
- }
- /**
- * Returns true if this statistic's value will always increase.
- */
- public boolean isCounter() {
- return this.isCounter;
- }
- /**
- * Returns true if larger values indicate better performance.
- */
- public boolean isLargerBetter() {
- return this.largerBetter;
- }
- /**
- * Returns a string that describes the units this statistic measures.
- */
- public String getUnits() {
- return this.units;
- }
- /**
- * Returns a textual description of this statistic.
- */
- public String getDescription() {
- return this.desc;
- }
- /**
- * Returns the offset of this stat in its type.
- */
- public int getOffset() {
- return this.offset;
- }
- }
-
- public static interface StatValue {
- /**
- * {@link StatArchiveReader.StatValue} filter that causes the
- * statistic values to be unfiltered. This causes the raw values
- * written to the archive to be used.
- * <p>This is the default filter for non-counter statistics.
- * To determine if a statistic is not a counter use {@link StatArchiveReader.StatDescriptor#isCounter}. */
- public static final int FILTER_NONE = 0;
- /**
- * {@link StatArchiveReader.StatValue} filter that causes the
- * statistic values to be filtered to reflect how often they
- * change per second. Since the difference between two samples is
- * used to calculate the value this causes the {@link StatArchiveReader.StatValue}
- * to have one less sample than {@link #FILTER_NONE}. The instance
- * time stamp that does not have a per second value is the
- * instance's first time stamp {@link
- * StatArchiveReader.ResourceInst#getFirstTimeMillis}.
- * <p>This is the default filter for counter statistics.
- * To determine if a statistic is a counter use {@link StatArchiveReader.StatDescriptor#isCounter}. */
- public static final int FILTER_PERSEC = 1;
- /**
- * {@link StatArchiveReader.StatValue} filter that causes the
- * statistic values to be filtered to reflect how much they
- * changed between sample periods. Since the difference between
- * two samples is used to calculate the value this causes the
- * {@link StatArchiveReader.StatValue} to have one less sample than {@link
- * #FILTER_NONE}. The instance time stamp that does not have a per
- * second value is the instance's first time stamp {@link
- * StatArchiveReader.ResourceInst#getFirstTimeMillis}.
- */
- public static final int FILTER_PERSAMPLE = 2;
- /**
- * Creates and returns a trimmed version of this stat value.
- * Any samples taken before <code>startTime</code> and after
- * <code>endTime</code> are discarded from the resulting value.
- * Set a time parameter to <code>-1</code> to not trim that side.
- */
- public StatValue createTrimmed(long startTime, long endTime);
- /**
- * Returns true if value has data that has been trimmed off it
- * by a start timestamp.
- */
- public boolean isTrimmedLeft();
- /**
- * Gets the {@link StatArchiveReader.ResourceType type} of the
- * resources that this value belongs to.
- */
- public ResourceType getType();
- /**
- * Gets the {@link StatArchiveReader.ResourceInst resources} that this value
- * belongs to.
- */
- public ResourceInst[] getResources();
- /**
- * Returns an array of timestamps for each unfiltered snapshot in this value.
- * Each returned time stamp is the number of millis since
- * midnight, Jan 1, 1970 UTC.
- */
- public long[] getRawAbsoluteTimeStamps();
- /**
- * Returns an array of timestamps for each unfiltered snapshot in this value.
- * Each returned time stamp is the number of millis since
- * midnight, Jan 1, 1970 UTC.
- * The resolution is seconds.
- */
- public long[] getRawAbsoluteTimeStampsWithSecondRes();
- /**
- * Returns an array of doubles containing the unfiltered value of this
- * statistic for each point in time that it was sampled.
- */
- public double[] getRawSnapshots();
- /**
- * Returns an array of doubles containing the filtered value of this
- * statistic for each point in time that it was sampled.
- */
- public double[] getSnapshots();
- /**
- * Returns the number of samples taken of this statistic's value.
- */
- public int getSnapshotsSize();
- /**
- * Returns the smallest of all the samples taken of this statistic's value.
- */
- public double getSnapshotsMinimum();
- /**
- * Returns the largest of all the samples taken of this statistic's value.
- */
- public double getSnapshotsMaximum();
- /**
- * Returns the average of all the samples taken of this statistic's value.
- */
- public double getSnapshotsAverage();
- /**
- * Returns the standard deviation of all the samples taken of this statistic's value.
- */
- public double getSnapshotsStandardDeviation();
- /**
- * Returns the most recent value of all the samples taken of this statistic's value.
- */
- public double getSnapshotsMostRecent();
- /**
- * Returns true if sample whose value was different from previous values
- * has been added to this StatValue since the last time this method was
- * called.
- */
- public boolean hasValueChanged();
- /**
- * Returns the current filter used to calculate this statistic's values.
- * It will be one of these values:
- * <ul>
- * <li> {@link #FILTER_NONE}
- * <li> {@link #FILTER_PERSAMPLE}
- * <li> {@link #FILTER_PERSEC}
- * </ul>
- */
- public int getFilter();
- /**
- * Sets the current filter used to calculate this statistic's values.
- * The default filter is {@link #FILTER_NONE} unless the statistic
- * is a counter, {@link StatArchiveReader.StatDescriptor#isCounter},
- * in which case its {@link #FILTER_PERSEC}.
- * @param filter It must be one of these values:
- * <ul>
- * <li> {@link #FILTER_NONE}
- * <li> {@link #FILTER_PERSAMPLE}
- * <li> {@link #FILTER_PERSEC}
- * </ul>
- * @throws IllegalArgumentException if <code>filter</code> is not a valid filter constant.
- */
- public void setFilter(int filter);
- /**
- * Returns a description of this statistic.
- */
- public StatDescriptor getDescriptor();
- }
-
- protected static abstract class AbstractValue implements StatValue {
- protected StatDescriptor descriptor;
- protected int filter;
-
- protected long startTime = -1;
- protected long endTime = -1;
-
- protected boolean statsValid = false;
- protected int size;
- protected double min;
- protected double max;
- protected double avg;
- protected double stddev;
- protected double mostRecent;
-
- public void calcStats() {
- if (!statsValid) {
- getSnapshots();
- }
- }
-
- public int getSnapshotsSize() {
- calcStats();
- return this.size;
- }
- public double getSnapshotsMinimum() {
- calcStats();
- return this.min;
- }
- public double getSnapshotsMaximum() {
- calcStats();
- return this.max;
- }
- public double getSnapshotsAverage() {
- calcStats();
- return this.avg;
- }
- public double getSnapshotsStandardDeviation() {
- calcStats();
- return this.stddev;
- }
- public double getSnapshotsMostRecent() {
- calcStats();
- return this.mostRecent;
- }
- public StatDescriptor getDescriptor() {
- return this.descriptor;
- }
- public int getFilter() {
- return this.filter;
- }
-
- public void setFilter(int filter) {
- if (filter != this.filter) {
- if (filter != FILTER_NONE
- && filter != FILTER_PERSEC
- && filter != FILTER_PERSAMPLE) {
- throw new IllegalArgumentException(LocalizedStrings.StatArchiveReader_FILTER_VALUE_0_MUST_BE_1_2_OR_3
- .toLocalizedString(
- new Object[] {
- Integer.valueOf(filter),
- Integer.valueOf(FILTER_NONE),
- Integer.valueOf(FILTER_PERSEC),
- Integer.valueOf(FILTER_PERSAMPLE)}));
- }
- this.filter = filter;
- this.statsValid = false;
- }
- }
-
- /**
- * Calculates each stat given the result of calling getSnapshots
- */
- protected void calcStats(double[] values) {
- if (statsValid) {
- return;
- }
- size = values.length;
- if (size == 0) {
- min = 0.0;
- max = 0.0;
- avg = 0.0;
- stddev = 0.0;
- mostRecent = 0.0;
- } else {
- min = values[0];
- max = values[0];
- mostRecent = values[values.length-1];
- double total = values[0];
- for (int i=1; i < size; i++) {
- total += values[i];
- if (values[i] < min) {
- min = values[i];
- } else if (values[i] > max) {
- max = values[i];
- }
- }
- avg = total / size;
- stddev = 0.0;
- if (size > 1) {
- for (int i=0; i < size; i++) {
- double dv = values[i] - avg;
- stddev += (dv*dv);
- }
- stddev /= (size - 1);
- stddev = Math.sqrt(stddev);
- }
- }
- statsValid = true;
- }
-
- /**
- * Returns a string representation of this object.
- */
- @Override
- public String toString() {
- calcStats();
- StringBuffer result = new StringBuffer();
- result.append(getDescriptor().getName());
- String units = getDescriptor().getUnits();
- if (units != null && units.length() > 0) {
- result.append(' ').append(units);
- }
- if (filter == FILTER_PERSEC) {
- result.append("/sec");
- } else if (filter == FILTER_PERSAMPLE) {
- result.append("/sample");
- }
- result.append(": samples=")
- .append(getSnapshotsSize());
- if (startTime != -1) {
- result.append(" startTime=\"")
- .append(new Date(startTime))
- .append("\"");
- }
- if (endTime != -1) {
- result.append(" endTime=\"")
- .append(new Date(endTime))
- .append("\"");
- }
- result.append(" min=")
- .append(nf.format(min));
- result.append(" max=")
- .append(nf.format(max));
- result.append(" average=")
- .append(nf.format(avg));
- result.append(" stddev=")
- .append(nf.format(stddev));
- result.append(" last=") // for bug 42532
- .append(nf.format(mostRecent));
- return result.toString();
- }
- }
-
- /**
- * A ComboValue is a value that is the logical combination of
- * a set of other stat values.
- * <p> For now ComboValue has a simple implementation that does not
- * suppport updates.
- */
- private static class ComboValue extends AbstractValue {
- private final ResourceType type;
- private final StatValue[] values;
- /**
- * Creates a ComboValue by adding all the specified values together.
- */
- ComboValue(List valueList) {
- this((StatValue[])valueList.toArray(new StatValue[valueList.size()]));
- }
- /**
- * Creates a ComboValue by adding all the specified values together.
- */
- ComboValue(StatValue[] values) {
- this.values = values;
- this.filter = this.values[0].getFilter();
- String typeName = this.values[0].getType().getName();
- String statName = this.values[0].getDescriptor().getName();
- int bestTypeIdx = 0;
- for (int i=1; i < this.values.length; i++) {
- if (this.filter != this.values[i].getFilter()) {
- /* I'm not sure why this would happen.
- * If it really can happen then this code should change
- * the filter since a client has no way to select values
- * based on the filter.
- */
- throw new IllegalArgumentException(LocalizedStrings.StatArchiveReader_CANT_COMBINE_VALUES_WITH_DIFFERENT_FILTERS.toLocalizedString());
- }
- if (!typeName.equals(this.values[i].getType().getName())) {
- throw new IllegalArgumentException(LocalizedStrings.StatArchiveReader_CANT_COMBINE_VALUES_WITH_DIFFERENT_TYPES.toLocalizedString());
- }
- if (!statName.equals(this.values[i].getDescriptor().getName())) {
- throw new IllegalArgumentException(LocalizedStrings.StatArchiveReader_CANT_COMBINE_DIFFERENT_STATS.toLocalizedString());
- }
- if (this.values[i].getDescriptor().isCounter()) {
- // its a counter which is not the default
- if (!this.values[i].getDescriptor().isLargerBetter()) {
- // this guy has non-defaults for both use him
- bestTypeIdx = i;
- } else if (this.values[bestTypeIdx].getDescriptor().isCounter()
- == this.values[bestTypeIdx].getDescriptor().isLargerBetter()) {
- // as long as we haven't already found a guy with defaults
- // make this guy the best type
- bestTypeIdx = i;
- }
- } else {
- // its a gauge, see if it has a non-default largerBetter
- if (this.values[i].getDescriptor().isLargerBetter()) {
- // as long as we haven't already found a guy with defaults
- if (this.values[bestTypeIdx].getDescriptor().isCounter()
- == this.values[bestTypeIdx].getDescriptor().isLargerBetter()) {
- // make this guy the best type
- bestTypeIdx = i;
- }
- }
- }
- }
- this.type = this.values[bestTypeIdx].getType();
- this.descriptor = this.values[bestTypeIdx].getDescriptor();
- }
- private ComboValue(ComboValue original, long startTime, long endTime) {
- this.startTime = startTime;
- this.endTime = endTime;
- this.type = original.getType();
- this.descriptor = original.getDescriptor();
- this.filter = original.getFilter();
- this.values = new StatValue[original.values.length];
- for (int i=0; i < this.values.length; i++) {
- this.values[i] = original.values[i].createTrimmed(startTime, endTime);
- }
- }
- public StatValue createTrimmed(long startTime, long endTime) {
- if (startTime == this.startTime && endTime == this.endTime) {
- return this;
- } else {
- return new ComboValue(this, startTime, endTime);
- }
- }
- public ResourceType getType() {
- return this.type;
- }
- public ResourceInst[] getResources() {
- Set set = new HashSet();
- for (int i=0; i < values.length; i++) {
- set.addAll(Arrays.asList(values[i].getResources()));
- }
- ResourceInst[] result = new ResourceInst[set.size()];
- return (ResourceInst[])set.toArray(result);
- }
- public boolean hasValueChanged() {
- return true;
- }
-
- public static boolean closeEnough(long v1, long v2, long delta) {
- return (v1 == v2) || ((Math.abs(v1-v2)/2) <= delta);
- }
- /**
- * Return true if v is closer to prev.
- * Return false if v is closer to next.
- * Return true if v is the same distance from both.
- */
- public static boolean closer(long v, long prev, long next) {
- return Math.abs(v-prev) <= Math.abs(v-next);
- }
-
-
- /**
- * Return true if the current ts must be inserted instead of
- * being mapped to the tsAtInsertPoint
- */
- private static boolean mustInsert(int nextIdx, long[] valueTimeStamps, long tsAtInsertPoint) {
- return (nextIdx < valueTimeStamps.length)
- && (valueTimeStamps[nextIdx] <= tsAtInsertPoint);
- }
-
- public long[] getRawAbsoluteTimeStampsWithSecondRes() {
- return getRawAbsoluteTimeStamps();
- }
-
- public long[] getRawAbsoluteTimeStamps() {
- if (values.length == 0) {
- return new long[0];
- }
-// for (int i=0; i < values.length; i++) {
-// System.out.println("DEBUG: inst# " + i + " has "
-// + values[i].getRawAbsoluteTimeStamps().length
-// + " timestamps");
-// }
- long[] valueTimeStamps = values[0].getRawAbsoluteTimeStamps();
- int tsCount = valueTimeStamps.length + 1;
- long[] ourTimeStamps = new long[(tsCount*2) + 1];
- System.arraycopy(valueTimeStamps, 0, ourTimeStamps, 0, valueTimeStamps.length);
- // Note we add a MAX sample to make the insert logic simple
- ourTimeStamps[valueTimeStamps.length] = Long.MAX_VALUE;
- for (int i=1; i < values.length; i++) {
- valueTimeStamps = values[i].getRawAbsoluteTimeStamps();
- if (valueTimeStamps.length == 0) {
- continue;
- }
- int ourIdx = 0;
- int j=0;
- long tsToInsert = valueTimeStamps[0] - 1000; // default to 1 second
- if (valueTimeStamps.length > 1) {
- tsToInsert = valueTimeStamps[0] - (valueTimeStamps[1] - valueTimeStamps[0]);
- }
- // tsToInsert is now initialized to a value that we can pretend
- // was the previous timestamp inserted.
- while (j < valueTimeStamps.length) {
- long timeDelta = (valueTimeStamps[j] - tsToInsert) / 2;
- tsToInsert = valueTimeStamps[j];
- long tsAtInsertPoint = ourTimeStamps[ourIdx];
- while (tsToInsert > tsAtInsertPoint
- && !closeEnough(tsToInsert, tsAtInsertPoint, timeDelta)) {
-// System.out.println("DEBUG: skipping " + ourIdx + " because it was not closeEnough");
- ourIdx++;
- tsAtInsertPoint = ourTimeStamps[ourIdx];
- }
- if (closeEnough(tsToInsert, tsAtInsertPoint, timeDelta)
- && !mustInsert(j+1, valueTimeStamps, tsAtInsertPoint)) {
- // It was already in our list so just go to the next one
- j++;
- ourIdx++; // never put the next timestamp at this index
- while (!closer(tsToInsert, ourTimeStamps[ourIdx-1], ourTimeStamps[ourIdx])
- && !mustInsert(j, valueTimeStamps, ourTimeStamps[ourIdx])) {
-// System.out.println("DEBUG: skipping mergeTs[" + (ourIdx-1) + "]="
-// + tsAtInsertPoint + " because it was closer to the next one");
- ourIdx++; // it is closer to the next one so skip forward on more
- }
- } else {
- // its not in our list so add it
- int endRunIdx=j+1;
- while (endRunIdx < valueTimeStamps.length
- && valueTimeStamps[endRunIdx] < tsAtInsertPoint
- && !closeEnough(valueTimeStamps[endRunIdx], tsAtInsertPoint, timeDelta)) {
- endRunIdx++;
- }
- int numToCopy = endRunIdx - j;
-// System.out.println("DEBUG: tsToInsert=" + tsToInsert
-// + " tsAtInsertPoint=" + tsAtInsertPoint
-// + " timeDelta=" + timeDelta
-// + " vDelta=" + (Math.abs(tsToInsert-tsAtInsertPoint)/2)
-// + " numToCopy=" + numToCopy);
-// if (j > 0) {
-// System.out.println("DEBUG: prevTsToInsert=" + valueTimeStamps[j-1]);
-// }
-// if (ourIdx > 0) {
-// System.out.println("DEBUG ourTimeStamps[" + (ourIdx-1) + "]=" + ourTimeStamps[ourIdx-1]);
-// }
-
-// if (numToCopy > 1) {
-// System.out.println("DEBUG: endRunTs=" + valueTimeStamps[endRunIdx-1]);
-// }
- if (tsCount+numToCopy > ourTimeStamps.length) {
- // grow our timestamp array
- long[] tmp = new long[(tsCount+numToCopy)*2];
- System.arraycopy(ourTimeStamps, 0, tmp, 0, tsCount);
- ourTimeStamps = tmp;
- }
- // make room for insert
- System.arraycopy(ourTimeStamps, ourIdx,
- ourTimeStamps, ourIdx+numToCopy,
- tsCount-ourIdx);
- // insert the elements
- if (numToCopy == 1) {
- ourTimeStamps[ourIdx] = valueTimeStamps[j];
- } else {
- System.arraycopy(valueTimeStamps, j,
- ourTimeStamps, ourIdx,
- numToCopy);
- }
- ourIdx += numToCopy;
- tsCount += numToCopy;
- // skip over all inserted elements
- j += numToCopy;
- }
-// System.out.println("DEBUG: inst #" + i
-// + " valueTs[" + (j-1) + "]=" + tsToInsert
-// + " found/inserted at"
-// + " mergeTs[" + (ourIdx-1) + "]=" + ourTimeStamps[ourIdx-1]);
- }
- }
-// for (int i=0; i < tsCount; i++) {
-// System.out.println("DEBUG: mergedTs[" + i + "]=" + ourTimeStamps[i]);
-// if (i > 0 && ourTimeStamps[i] <= ourTimeStamps[i-1]) {
-// System.out.println("DEBUG: ERROR ts was not greater than previous");
-// }
-// }
- // Now make one more pass over all the timestamps and make sure they
- // will all fit into the current merged timestamps in ourTimeStamps
-// boolean changed;
-// do {
-// changed = false;
-// for (int i=0; i < values.length; i++) {
-// valueTimeStamps = values[i].getRawAbsoluteTimeStamps();
-// if (valueTimeStamps.length == 0) {
-// continue;
-// }
-// int ourIdx = 0;
-// for (int j=0; j < valueTimeStamps.length; j++) {
-// while ((ourIdx < (tsCount-1))
-// && !isClosest(valueTimeStamps[j], ourTimeStamps, ourIdx)) {
-// ourIdx++;
-// }
-// if (ourIdx == (tsCount-1)) {
-// // we are at the end so we need to append all our remaining stamps [j..valueTimeStamps.length-1]
-// // and then reappend the Long.MAX_VALUE that
-// // is currently at tsCount-1
-// int numToCopy = valueTimeStamps.length - j;
-// if (tsCount+numToCopy > ourTimeStamps.length) {
-// // grow our timestamp array
-// long[] tmp = new long[tsCount+numToCopy+1];
-// System.arraycopy(ourTimeStamps, 0, tmp, 0, tsCount);
-// ourTimeStamps = tmp;
-// }
-// System.arraycopy(valueTimeStamps, j,
-// ourTimeStamps, ourIdx,
-// numToCopy);
-// tsCount += numToCopy;
-// ourTimeStamps[tsCount-1] = Long.MAX_VALUE;
-// //changed = true;
-// System.out.println("DEBUG: had to add " + numToCopy
-// + " timestamps for inst#" + i + " starting at index " + j + " starting with ts=" + valueTimeStamps[j]);
-// break; // our of the for j loop since we just finished off this guy
-// } else {
-// ourIdx++;
-// }
-// }
-// }
-// } while (changed);
- // remove the max ts we added
- tsCount--;
- {
- int startIdx = 0;
- int endIdx = tsCount-1;
- if (startTime != -1) {
-// for (int i=0; i < tsCount; i++) {
-// if (ourTimeStamps[i] >= startTime) {
-// break;
-// }
-// startIdx++;
-// }
- Assert.assertTrue(ourTimeStamps[startIdx] >= startTime);
- }
- if (endTime != -1) {
-// endIdx = startIdx-1;
-// for (int i=startIdx; i < tsCount; i++) {
-// if (ourTimeStamps[i] >= endTime) {
-// break;
-// }
-// endIdx++;
-// }
- Assert.assertTrue(endIdx == startIdx-1 || ourTimeStamps[endIdx] < endTime);
- }
- tsCount = (endIdx-startIdx) + 1;
-
- // shrink and trim our timestamp array
- long[] tmp = new long[tsCount];
- System.arraycopy(ourTimeStamps, startIdx, tmp, 0, tsCount);
- ourTimeStamps = tmp;
- }
- return ourTimeStamps;
- }
- public double[] getRawSnapshots() {
- return getRawSnapshots(getRawAbsoluteTimeStamps());
- }
- /**
- * Returns true if the timeStamp at curIdx is the one that ts is
- * the closest to.
- * We know that timeStamps[curIdx-1], if it exists, was not the closest.
- */
- private static boolean isClosest(long ts, long[] timeStamps, int curIdx) {
- if (curIdx >= (timeStamps.length - 1)) {
- // curIdx is the last one so it must be the closest
- return true;
- }
- if (ts == timeStamps[curIdx]) {
- return true;
- }
- return closer(ts, timeStamps[curIdx], timeStamps[curIdx+1]);
- }
-
- public boolean isTrimmedLeft() {
- for (int i=0; i < this.values.length; i++) {
- if (this.values[i].isTrimmedLeft()) {
- return true;
- }
- }
- return false;
- }
-
- private double[] getRawSnapshots(long[] ourTimeStamps) {
- double[] result = new double[ourTimeStamps.length];
-// System.out.println("DEBUG: producing " + result.length + " values");
- if (result.length > 0) {
- for (int i=0; i < values.length; i++) {
- long[] valueTimeStamps = values[i].getRawAbsoluteTimeStamps();
- double[] valueSnapshots = values[i].getRawSnapshots();
- double currentValue = 0.0;
- int curIdx = 0;
- if (values[i].isTrimmedLeft() && valueSnapshots.length > 0) {
- currentValue = valueSnapshots[0];
- }
-// System.out.println("DEBUG: inst#" + i + " has " + valueSnapshots.length + " values");
- for (int j=0; j < valueSnapshots.length; j++) {
-// System.out.println("DEBUG: Doing v with"
-// + " vTs[" + j + "]=" + valueTimeStamps[j]
-// + " at mergeTs[" + curIdx + "]=" + ourTimeStamps[curIdx]);
- while (!isClosest(valueTimeStamps[j], ourTimeStamps, curIdx)) {
- if (descriptor.isCounter()) {
- result[curIdx] += currentValue;
- }
-// System.out.println("DEBUG: skipping curIdx=" + curIdx
-// + " valueTimeStamps[" + j + "]=" + valueTimeStamps[j]
-// + " ourTimeStamps[" + curIdx + "]=" + ourTimeStamps[curIdx]
-// + " ourTimeStamps[" + (curIdx+1) + "]=" + ourTimeStamps[curIdx+1]);
-
- curIdx++;
- }
- if (curIdx >= result.length) {
- // Add this to workaround bug 30288
- int samplesSkipped = valueSnapshots.length - j;
- StringBuffer msg = new StringBuffer(100);
- msg.append("WARNING: dropping last ");
- if (samplesSkipped == 1) {
- msg.append("sample because it");
- } else {
- msg.append(samplesSkipped).append(" samples because they");
- }
- msg.append(" could not fit in the merged result.");
- System.out.println(msg.toString());
- break;
- }
- currentValue = valueSnapshots[j];
- result[curIdx] += currentValue;
- curIdx++;
- }
- if (descriptor.isCounter()) {
- for (int j=curIdx; j < result.length; j++) {
- result[j] += currentValue;
- }
- }
- }
- }
- return result;
- }
- public double[] getSnapshots() {
- double[] result;
- if (filter != FILTER_NONE) {
- long[] timestamps = getRawAbsoluteTimeStamps();
- double[] snapshots = getRawSnapshots(timestamps);
- if (snapshots.length <= 1) {
- return new double[0];
- }
- result = new double[snapshots.length - 1];
- for (int i=0; i < result.length; i++) {
- double valueDelta = snapshots[i+1] - snapshots[i];
- if (filter == FILTER_PERSEC) {
- long timeDelta = timestamps[i+1] - timestamps[i];
- result[i] = valueDelta / (timeDelta / 1000.0);
-// if (result[i] > valueDelta) {
-// System.out.println("DEBUG: timeDelta was " + timeDelta + " ms.");
-// System.out.println("DEBUG: valueDelta was " + valueDelta);
-// System.out.println("DEBUG: valueDelta/sec was " + result[i]);
-// }
- } else {
- result[i] = valueDelta;
- }
- }
- } else {
- result = getRawSnapshots();
- }
- calcStats(result);
- return result;
- }
- }
-
- /**
- * Provides the value series related to a single statistics.
- */
- private static class SimpleValue extends AbstractValue {
- private final ResourceInst resource;
-
- private boolean useNextBits = false;
- private long nextBits;
- private final BitSeries series;
- private boolean valueChangeNoticed = false;
-
-
- public StatValue createTrimmed(long startTime, long endTime) {
- if (startTime == this.startTime && endTime == this.endTime) {
- return this;
- } else {
- return new SimpleValue(this, startTime, endTime);
- }
- }
-
- protected SimpleValue(ResourceInst resource, StatDescriptor sd) {
- this.resource = resource;
- if (sd.isCounter()) {
- this.filter = FILTER_PERSEC;
- } else {
- this.filter = FILTER_NONE;
- }
- this.descriptor = sd;
- this.series = new BitSeries();
- this.statsValid = false;
- }
-
- private SimpleValue(SimpleValue in, long startTime, long endTime) {
- this.startTime = startTime;
- this.endTime = endTime;
- this.useNextBits = in.useNextBits;
- this.nextBits = in.nextBits;
- this.resource = in.resource;
- this.series = in.series;
- this.descriptor = in.descriptor;
- this.filter = in.filter;
- this.statsValid = false;
- this.valueChangeNoticed = true;
- }
-
- public ResourceType getType() {
- return this.resource.getType();
- }
-
- public ResourceInst[] getResources() {
- return new ResourceInst[] {this.resource};
- }
-
- public boolean isTrimmedLeft() {
- return getStartIdx() != 0;
- }
-
- private int getStartIdx() {
- int startIdx = 0;
- if (startTime != -1) {
- long startTimeStamp = startTime - resource.getTimeBase();
- long[] timestamps = resource.getAllRawTimeStamps();
- for (int i=resource.getFirstTimeStampIdx();
- i < resource.getFirstTimeStampIdx() + series.getSize();
- i++) {
- if (timestamps[i] >= startTimeStamp) {
- break;
- }
- startIdx++;
- }
- }
- return startIdx;
- }
- private int getEndIdx(int startIdx) {
- int endIdx = series.getSize()-1;
- if (endTime != -1) {
- long endTimeStamp = endTime - resource.getTimeBase();
- long[] timestamps = resource.getAllRawTimeStamps();
- endIdx = startIdx-1;
- for (int i=resource.getFirstTimeStampIdx()+startIdx;
- i < resource.getFirstTimeStampIdx() + series.getSize();
- i++) {
- if (timestamps[i] >= endTimeStamp) {
- break;
- }
- endIdx++;
- }
- Assert.assertTrue(endIdx == startIdx-1 || timestamps[endIdx] < endTimeStamp);
- }
- return endIdx;
- }
- public double[] getSnapshots() {
- double[] result;
- int startIdx = getStartIdx();
- int endIdx = getEndIdx(startIdx);
- int resultSize=(endIdx-startIdx) + 1;
-
- if (filter != FILTER_NONE && resultSize > 1) {
- long[] timestamps = null;
- if (filter == FILTER_PERSEC) {
- timestamps = resource.getAllRawTimeStamps();
- }
- result = new double[resultSize-1];
- int tsIdx = resource.getFirstTimeStampIdx()+startIdx;
- double[] values = series.getValuesEx(descriptor.getTypeCode(), startIdx, resultSize);
- for (int i=0; i < result.length; i++) {
- double valueDelta = values[i+1] - values[i];
- if (filter == FILTER_PERSEC) {
- double timeDelta = (timestamps[tsIdx+i+1] - timestamps[tsIdx+i]); // millis
- valueDelta /= (timeDelta / 1000); // per second
- }
- result[i] = valueDelta;
- }
- } else {
- result = series.getValuesEx(descriptor.getTypeCode(), startIdx, resultSize);
- }
- calcStats(result);
- return result;
- }
-
- public double[] getRawSnapshots() {
- int startIdx = getStartIdx();
- int endIdx = getEndIdx(startIdx);
- int resultSize=(endIdx-startIdx) + 1;
- return series.getValuesEx(descriptor.getTypeCode(), startIdx, resultSize);
- }
-
- public long[] getRawAbsoluteTimeStampsWithSecondRes() {
- long[] result = getRawAbsoluteTimeStamps();
- for (int i=0; i < result.length; i++) {
- result[i] += 500;
- result[i] /= 1000;
- result[i] *= 1000;
- }
- return result;
- }
-
- public long[] getRawAbsoluteTimeStamps() {
- int startIdx = getStartIdx();
- int endIdx = getEndIdx(startIdx);
- int resultSize=(endIdx-startIdx) + 1;
- if (resultSize <= 0) {
- return new long[0];
- } else {
- long[] result = new long[resultSize];
- long[] timestamps = resource.getAllRawTimeStamps();
- int tsIdx = resource.getFirstTimeStampIdx()+startIdx;
- long base = resource.getTimeBase();
- for (int i=0; i < resultSize; i++) {
- result[i] = base + timestamps[tsIdx+i];
- }
- return result;
- }
- }
-
- public boolean hasValueChanged() {
- if (valueChangeNoticed) {
- valueChangeNoticed = false;
- return true;
- } else {
- return false;
- }
- }
- protected int getMemoryUsed() {
- int result = 0;
- if (series != null) {
- result += series.getMemoryUsed();
- }
- return result;
- }
-
- protected void dump(PrintWriter stream) {
- calcStats();
- stream.print(" " + descriptor.getName() + "=");
- stream.print("[size=" + getSnapshotsSize()
- + " min=" + nf.format(min)
- + " max=" + nf.format(max)
- + " avg=" + nf.format(avg)
- + " stddev=" + nf.format(stddev) + "]");
- if (Boolean.getBoolean("StatArchiveReader.dumpall")) {
- series.dump(stream);
- } else {
- stream.println();
- }
- }
-
- protected void shrink() {
- this.series.shrink();
- }
-
- protected void initialValue(long v) {
- this.series.initialBits(v);
- }
- protected void prepareNextBits(long bits) {
- useNextBits = true;
- nextBits = bits;
- }
- protected void addSample() {
- statsValid = false;
- if (useNextBits) {
- useNextBits = false;
- series.addBits(nextBits);
- valueChangeNoticed = true;
- } else {
- series.addBits(0);
- }
- }
- }
-
- private static abstract class BitInterval {
- /** Returns number of items added to values */
- abstract int fill(double[] values, int valueOffset, int typeCode, int skipCount);
- abstract void dump(PrintWriter stream);
- abstract boolean attemptAdd(long addBits, long addInterval, int addCount);
- int getMemoryUsed() {
- return 0;
- }
-
- protected int count;
-
- public final int getSampleCount() {
- return this.count;
- }
-
- static BitInterval create(long bits, long interval, int count) {
- if (interval == 0) {
- if (bits <= Integer.MAX_VALUE && bits >= Integer.MIN_VALUE) {
- return new BitZeroIntInterval((int)bits, count);
- } else {
- return new BitZeroLongInterval(bits, count);
- }
- } else if (count <= 3) {
- if (interval <= Byte.MAX_VALUE && interval >= Byte.MIN_VALUE) {
- return new BitExplicitByteInterval(bits, interval, count);
- } else if (interval <= Short.MAX_VALUE && interval >= Short.MIN_VALUE) {
- return new BitExplicitShortInterval(bits, interval, count);
- } else if (interval <= Integer.MAX_VALUE && interval >= Integer.MIN_VALUE) {
- return new BitExplicitIntInterval(bits, interval, count);
- } else {
- return new BitExplicitLongInterval(bits, interval, count);
- }
- } else {
- boolean smallBits = false;
- boolean smallInterval = false;
- if (bits <= Integer.MAX_VALUE && bits >= Integer.MIN_VALUE) {
- smallBits = true;
- }
- if (interval <= Integer.MAX_VALUE && interval >= Integer.MIN_VALUE) {
- smallInterval = true;
- }
- if (smallBits) {
- if (smallInterval) {
- return new BitNonZeroIntIntInterval((int)bits, (int)interval, count);
- } else {
- return new BitNonZeroIntLongInterval((int)bits, interval, count);
- }
- } else {
- if (smallInterval) {
- return new BitNonZeroLongIntInterval(bits, (int)interval, count);
- } else {
- return new BitNonZeroLongLongInterval(bits, interval, count);
- }
- }
- }
- }
- }
-
- private static abstract class BitNonZeroInterval extends BitInterval {
- @Override
- int getMemoryUsed() {
- return super.getMemoryUsed() + 4;
- }
- abstract long getBits();
- abstract long getInterval();
-
- @Override
- int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
- int fillcount = values.length - valueOffset; // space left in values
- int maxCount = count - skipCount; // maximum values this interval can produce
- if (fillcount > maxCount) {
- fillcount = maxCount;
- }
- long base = getBits();
- long interval = getInterval();
- base += skipCount * interval;
- for (int i=0; i < fillcount; i++) {
- values[valueOffset+i] = bitsToDouble(typeCode, base);
- base += interval;
- }
- return fillcount;
- }
-
- @Override
- void dump(PrintWriter stream) {
- stream.print(getBits());
- if (count > 1) {
- long interval = getInterval();
- if (interval != 0) {
- stream.print("+=" + interval);
- }
- stream.print("r" + count);
- }
- }
- BitNonZeroInterval(int count) {
- this.count = count;
- }
- @Override
- boolean attemptAdd(long addBits, long addInterval, int addCount) {
- // addCount >= 2; count >= 2
- if (addInterval == getInterval()) {
- if (addBits == (getBits() + (addInterval * (count-1)))) {
- count += addCount;
- return true;
- }
- }
- return false;
- }
- }
-
- private static class BitNonZeroIntIntInterval extends BitNonZeroInterval {
- int bits;
- int interval;
-
- @Override
- int getMemoryUsed() {
- return super.getMemoryUsed() + 8;
- }
- @Override
- long getBits() {
- return this.bits;
- }
- @Override
- long getInterval() {
- return this.interval;
- }
-
- BitNonZeroIntIntInterval(int bits, int interval, int count) {
- super(count);
- this.bits = bits;
- this.interval = interval;
- }
- }
-
- private static class BitNonZeroIntLongInterval extends BitNonZeroInterval {
- int bits;
- long interval;
-
- @Override
- int getMemoryUsed() {
- return super.getMemoryUsed() + 12;
- }
- @Override
- long getBits() {
- return this.bits;
- }
- @Override
- long getInterval() {
- return this.interval;
- }
-
- BitNonZeroIntLongInterval(int bits, long interval, int count) {
- super(count);
- this.bits = bits;
- this.interval = interval;
- }
- }
-
- private static class BitNonZeroLongIntInterval extends BitNonZeroInterval {
- long bits;
- int interval;
-
- @Override
- int getMemoryUsed() {
- return super.getMemoryUsed() + 12;
- }
- @Override
- long getBits() {
- return this.bits;
- }
- @Override
- long getInterval() {
- return this.interval;
- }
-
- BitNonZeroLongIntInterval(long bits, int interval, int count) {
- super(count);
- this.bits = bits;
- this.interval = interval;
- }
- }
-
- private static class BitNonZeroLongLongInterval extends BitNonZeroInterval {
- long bits;
- long interval;
-
- @Override
- int getMemoryUsed() {
- return super.getMemoryUsed() + 16;
- }
- @Override
- long getBits() {
- return this.bits;
- }
- @Override
- long getInterval() {
- return this.interval;
- }
-
- BitNonZeroLongLongInterval(long bits, long interval, int count) {
- super(count);
- this.bits = bits;
- this.interval = interval;
- }
- }
-
- private static abstract class BitZeroInterval extends BitInterval {
- @Override
- int getMemoryUsed() {
- return super.getMemoryUsed() + 4;
- }
- abstract long getBits();
-
- @Override
- int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
- int fillcount = values.length - valueOffset; // space left in values
- int maxCount = count - skipCount; // maximum values this interval can produce
- if (fillcount > maxCount) {
- fillcount = maxCount;
- }
- double value = bitsToDouble(typeCode, getBits());
- for (int i=0; i < fillcount; i++) {
- values[valueOffset+i] = value;
- }
- return fillcount;
- }
-
- @Override
- void dump(PrintWriter stream) {
- stream.print(getBits());
- if (count > 1) {
- stream.print("r" + count);
- }
- }
- BitZeroInterval(int count) {
- this.count = count;
- }
- @Override
- boolean attemptAdd(long addBits, long addInterval, int addCount) {
- // addCount >= 2; count >= 2
- if (addInterval == 0 && addBits == getBits()) {
- count += addCount;
- return true;
- }
- return false;
- }
- }
-
- private static class BitZeroIntInterval extends BitZeroInterval {
- int bits;
-
- @Override
- int getMemoryUsed() {
- return super.getMemoryUsed() + 4;
- }
- @Override
- long getBits() {
- return bits;
- }
- BitZeroIntInterval(int bits, int count) {
- super(count);
- this.bits = bits;
- }
- }
-
- private static class BitZeroLongInterval extends BitZeroInterval {
- long bits;
-
- @Override
- int getMemoryUsed() {
- return super.getMemoryUsed() + 8;
- }
- @Override
- long getBits() {
- return bits;
- }
- BitZeroLongInterval(long bits, int count) {
- super(count);
- this.bits = bits;
- }
- }
-
- private static class BitExplicitByteInterval extends BitInterval {
- long firstValue;
- long lastValue;
- byte[] bitIntervals = null;
-
- @Override
- int getMemoryUsed() {
- int result = super.getMemoryUsed() + 4 + 8 + 8 + 4;
- if (bitIntervals != null) {
- result += bitIntervals.length;
- }
- return result;
- }
- @Override
- int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
- int fillcount = values.length - valueOffset; // space left in values
- int maxCount = count - skipCount; // maximum values this interval can produce
- if (fillcount > maxCount) {
- fillcount = maxCount;
- }
- long bitValue = firstValue;
- for (int i=0; i < skipCount; i++) {
- bitValue += bitIntervals[i];
- }
- for (int i=0; i < fillcount; i++) {
- bitValue += bitIntervals[skipCount+i];
- values[valueOffset+i] = bitsToDouble(typeCode, bitValue);
- }
- return fillcount;
- }
-
- @Override
- void dump(PrintWriter stream) {
- stream.print("(byteIntervalCount=" + count + " start=" + firstValue);
- for (int i=0; i < count; i++) {
- if (i != 0) {
- stream.print(", ");
- }
- stream.print(bitIntervals[i]);
- }
- stream.print(")");
- }
- BitExplicitByteInterval(long bits, long interval, int addCount) {
- count = addCount;
- firstValue = bits;
- lastValue = bits + (interval * (addCount-1));
- bitIntervals = new byte[count*2];
- bitIntervals[0] = 0;
- for (int i=1; i < count; i++) {
- bitIntervals[i] = (byte)interval;
- }
- }
- @Override
- boolean attemptAdd(long addBits, long addInterval, int addCount) {
- // addCount >= 2; count >= 2
- if (addCount <= 11) {
- if (addInterval <= Byte.MAX_VALUE && addInterval >= Byte.MIN_VALUE) {
- long firstInterval = addBits - lastValue;
- if (firstInterval <= Byte.MAX_VALUE && firstInterval >= Byte.MIN_VALUE) {
- lastValue = addBits + (addInterval * (addCount-1));
- if ((count + addCount) >= bitIntervals.length) {
- byte[] tmp = new byte[(count+addCount)*2];
- System.arraycopy(bitIntervals, 0, tmp, 0, bitIntervals.length);
- bitIntervals = tmp;
- }
- bitIntervals[count++] = (byte)firstInterval;
- for (int i=1; i < addCount; i++) {
- bitIntervals[count++] = (byte)addInterval;
- }
- return true;
- }
- }
- }
- return false;
- }
- }
-
- private static class BitExplicitShortInterval extends BitInterval {
- long firstValue;
- long lastValue;
- short[] bitIntervals = null;
-
- @Override
- int getMemoryUsed() {
- int result = super.getMemoryUsed() + 4 + 8 + 8 + 4;
- if (bitIntervals != null) {
- result += bitIntervals.length * 2;
- }
- return result;
- }
-
- @Override
- int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
- int fillcount = values.length - valueOffset; // space left in values
- int maxCount = count - skipCount; // maximum values this interval can produce
- if (fillcount > maxCount) {
- fillcount = maxCount;
- }
- long bitValue = firstValue;
- for (int i=0; i < skipCount; i++) {
- bitValue += bitIntervals[i];
- }
- for (int i=0; i < fillcount; i++) {
- bitValue += bitIntervals[skipCount+i];
- values[valueOffset+i] = bitsToDouble(typeCode, bitValue);
- }
- return fillcount;
- }
-
- @Override
- void dump(PrintWriter stream) {
- stream.print("(shortIntervalCount=" + count + " start=" + firstValue);
- for (int i=0; i < count; i++) {
- if (i != 0) {
- stream.print(", ");
- }
- stream.print(bitIntervals[i]);
- }
- stream.print(")");
- }
- BitExplicitShortInterval(long bits, long interval, int addCount) {
- count = addCount;
- firstValue = bits;
- lastValue = bits + (interval * (addCount-1));
- bitIntervals = new short[count*2];
- bitIntervals[0] = 0;
- for (int i=1; i < count; i++) {
- bitIntervals[i] = (short)interval;
- }
- }
- @Override
- boolean attemptAdd(long addBits, long addInterval, int addCount) {
- // addCount >= 2; count >= 2
- if (addCount <= 6) {
- if (addInterval <= Short.MAX_VALUE && addInterval >= Short.MIN_VALUE) {
- long firstInterval = addBits - lastValue;
- if (firstInterval <= Short.MAX_VALUE && firstInterval >= Short.MIN_VALUE) {
- lastValue = addBits + (addInterval * (addCount-1));
- if ((count + addCount) >= bitIntervals.length) {
- short[] tmp = new short[(count+addCount)*2];
- System.arraycopy(bitIntervals, 0, tmp, 0, bitIntervals.length);
- bitIntervals = tmp;
- }
- bitIntervals[count++] = (short)firstInterval;
- for (int i=1; i < addCount; i++) {
- bitIntervals[count++] = (short)addInterval;
- }
- return true;
- }
- }
- }
- return false;
- }
- }
-
- private static class BitExplicitIntInterval extends BitInterval {
- long firstValue;
- long lastValue;
- int[] bitIntervals = null;
-
- @Override
- int getMemoryUsed() {
- int result = super.getMemoryUsed() + 4 + 8 + 8 + 4;
- if (bitIntervals != null) {
- result += bitIntervals.length * 4;
- }
- return result;
- }
-
- @Override
- int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
- int fillcount = values.length - valueOffset; // space left in values
- int maxCount = count - skipCount; // maximum values this interval can produce
- if (fillcount > maxCount) {
- fillcount = maxCount;
- }
- long bitValue = firstValue;
- for (int i=0; i < skipCount; i++) {
- bitValue += bitIntervals[i];
- }
- for (int i=0; i < fillcount; i++) {
- bitValue += bitIntervals[skipCount+i];
- values[valueOffset+i] = bitsToDouble(typeCode, bitValue);
- }
- return fillcount;
- }
-
- @Override
- void dump(PrintWriter stream) {
- stream.print("(intIntervalCount=" + count + " start=" + firstValue);
- for (int i=0; i < count; i++) {
- if (i != 0) {
- stream.print(", ");
- }
- stream.print(bitIntervals[i]);
- }
- stream.print(")");
- }
- BitExplicitIntInterval(long bits, long interval, int addCount) {
- count = addCount;
- firstValue = bits;
- lastValue = bits + (interval * (addCount-1));
- bitIntervals = new int[count*2];
- bitIntervals[0] = 0;
- for (int i=1; i < count; i++) {
- bitIntervals[i] = (int)interval;
- }
- }
- @Override
- boolean attemptAdd(long addBits, long addInterval, int addCount) {
- // addCount >= 2; count >= 2
- if (addCount <= 4) {
- if (addInterval <= Integer.MAX_VALUE && addInterval >= Integer.MIN_VALUE) {
- long firstInterval = addBits - lastValue;
- if (firstInterval <= Integer.MAX_VALUE && firstInterval >= Integer.MIN_VALUE) {
- lastValue = addBits + (addInterval * (addCount-1));
- if ((count + addCount) >= bitIntervals.length) {
- int[] tmp = new int[(count+addCount)*2];
- System.arraycopy(bitIntervals, 0, tmp, 0, bitIntervals.length);
- bitIntervals = tmp;
- }
- bitIntervals[count++] = (int)firstInterval;
- for (int i=1; i < addCount; i++) {
- bitIntervals[count++] = (int)addInterval;
- }
- return true;
- }
- }
- }
- return false;
- }
- }
-
- private static class BitExplicitLongInterval extends BitInterval {
- long[] bitArray = null;
-
- @Override
- int getMemoryUsed() {
- int result = super.getMemoryUsed() + 4 + 4;
- if (bitArray != null) {
- result += bitArray.length * 8;
- }
- return result;
- }
-
- @Override
- int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
- int fillcount = values.length - valueOffset; // space left in values
- int maxCount = count - skipCount; // maximum values this interval can produce
- if (fillcount > maxCount) {
- fillcount = maxCount;
- }
- for (int i=0; i < fillcount; i++) {
- values[valueOffset+i] = bitsToDouble(typeCode, bitArray[skipCount+i]);
- }
- return fillcount;
- }
-
- @Override
- void dump(PrintWriter stream) {
- stream.print("(count=" + count + " ");
- for (int i=0; i < count; i++) {
- if (i != 0) {
- stream.print(", ");
- }
- stream.print(bitArray[i]);
- }
- stream.print(")");
- }
- BitExplicitLongInterval(long bits, long interval, int addCount) {
- count = addCount;
- bitArray = new long[count*2];
- for (int i=0; i < count; i++) {
- bitArray[i] = bits;
- bits += interval;
- }
- }
- @Override
- boolean attemptAdd(long addBits, long addInterval, int addCount) {
- // addCount >= 2; count >= 2
- if (addCount <= 3) {
- if ((count + addCount) >= bitArray.length) {
- long[] tmp = new long[(count+addCount)*2];
- System.arraycopy(bitArray, 0, tmp, 0, bitArray.length);
- bitArray = tmp;
- }
- for (int i=0; i < addCount; i++) {
- bitArray[count++] = addBits;
- addBits += addInterval;
- }
- return true;
- }
- return false;
- }
- }
-
- private static class BitSeries {
- int count; // number of items in this series
- long currentStartBits;
- long currentEndBits;
- long currentInterval;
- int currentCount;
- int intervalIdx; // index of most recent BitInterval
- BitInterval intervals[];
-
- /**
- * Returns the amount of memory used to implement this series.
- */
- protected int getMemoryUsed() {
- int result = 4 + 8 + 8 + 8 + 4 + 4 + 4;
- if (intervals != null) {
- result += 4 * intervals.length;
- for (int i=0; i <= intervalIdx; i++) {
- result += intervals[i].getMemoryUsed();
- }
- }
- return result;
- }
-
- public double[] getValues(int typeCode) {
- return getValuesEx(typeCode, 0, getSize());
- }
- /**
- * Gets the first "resultSize" values of this series
- * skipping over the first "samplesToSkip" ones.
- * The first value in a series is at index 0.
- * The maximum result size can be obtained by calling "getSize()".
- */
- public double[] getValuesEx(int typeCode, int samplesToSkip, int resultSize) {
- double[] result = new double[resultSize];
- int firstInterval = 0;
- int idx = 0;
- while (samplesToSkip > 0
- && firstInterval <= intervalIdx
- && intervals[firstInterval].getSampleCount() <= samplesToSkip) {
- samplesToSkip -= intervals[firstInterval].getSampleCount();
- firstInterval++;
- }
- for (int i=firstInterval; i <= intervalIdx; i++) {
- idx += intervals[i].fill(result, idx, typeCode, samplesToSkip);
- samplesToSkip = 0;
- }
- if (currentCount != 0) {
- idx += BitInterval.create(currentStartBits, currentInterval, currentCount).fill(result, idx, typeCode, samplesToSkip);
- }
- // assert
- if (idx != resultSize) {
- throw new InternalGemFireException(LocalizedStrings.StatArchiveReader_GETVALUESEX_DIDNT_FILL_THE_LAST_0_ENTRIES_OF_ITS_RESULT.toLocalizedString(Integer.valueOf(resultSize-idx)));
- }
- return result;
- }
-
- void dump(PrintWriter stream) {
- stream.print("[size=" + count + " intervals=" + (intervalIdx+1)
- + " memused=" + getMemoryUsed() + " ");
- for (int i=0; i <= intervalIdx; i++) {
- if (i != 0) {
- stream.print(", ");
- }
- intervals[i].dump(stream);
- }
- if (currentCount != 0) {
- if (intervalIdx != -1) {
- stream.print(", ");
- }
- BitInterval.create(currentStartBits, currentInterval, currentCount).dump(stream);
- }
- stream.println("]");
- }
-
- BitSeries() {
- count = 0;
- currentStartBits = 0;
- currentEndBits = 0;
- currentInterval = 0;
- currentCount = 0;
- intervalIdx = -1;
- intervals = null;
- }
-
- void initialBits(long bits) {
- this.currentEndBits = bits;
- }
-
- int getSize() {
- return this.count;
- }
-
- void addBits(long deltaBits) {
- long bits = currentEndBits + deltaBits;
- if (currentCount == 0) {
- currentStartBits = bits;
- currentCount = 1;
- } else if (currentCount == 1) {
- currentInterval = deltaBits;
- currentCount++;
- } else if (deltaBits == currentInterval) {
- currentCount++;
- } else {
- // we need to move currentBits into a BitInterval
- if (intervalIdx == -1) {
- intervals = new BitInterval[2];
- intervalIdx = 0;
- intervals[0] = BitInterval.create(currentStartBits, currentInterval, currentCount);
- } else {
- if (!intervals[intervalIdx].attemptAdd(currentStartBits, currentInterval, currentCount)) {
- // wouldn't fit in current bit interval so add a new one
- intervalIdx++;
- if (intervalIdx >= intervals.length) {
- BitInterval[] tmp = new BitInterval[intervals.length * 2];
- System.arraycopy(intervals, 0, tmp, 0, intervals.length);
- intervals = tmp;
- }
- intervals[intervalIdx] = BitInterval.create(currentStartBits, currentInterval, currentCount);
- }
- }
- // now start a new currentBits
- currentStartBits = bits;
- currentCount = 1;
- }
- currentEndBits = bits;
- count++;
- }
- /**
- * Free up any unused memory
- */
- void shrink() {
- if (intervals != null) {
- int currentSize = intervalIdx+1;
- if (currentSize < intervals.length) {
- BitInterval[] tmp = new BitInterval[currentSize];
- System.arraycopy(intervals, 0, tmp, 0, currentSize);
- intervals = tmp;
- }
- }
- }
- }
-
- private static class TimeStampSeries {
- static private final int GROW_SIZE = 256;
- int count; // number of items in this series
- long base; // millis since midnight, Jan 1, 1970 UTC.
- long[] timeStamps = new long[GROW_SIZE]; // elapsed millis from base
-
- void dump(PrintWriter stream) {
- stream.print("[size=" + count);
- for (int i=0; i < count; i++) {
- if (i != 0) {
- stream.print(", ");
- stream.print(timeStamps[i]-timeStamps[i-1]);
- } else {
- stream.print(" " + timeStamps[i]);
- }
- }
- stream.println("]");
- }
-
- void shrink() {
- if (count < timeStamps.length) {
- long[] tmp = new long[count];
- System.arraycopy(timeStamps, 0, tmp, 0, count);
- timeStamps = tmp;
- }
- }
-
- TimeStampSeries() {
- count = 0;
- base = 0;
- }
-
- void setBase(long base) {
- this.base = base;
- }
-
- int getSize() {
- return this.count;
- }
-
- void addTimeStamp(int ts) {
- if (count >= timeStamps.length) {
- long[] tmp = new long[timeStamps.length + GROW_SIZE];
- System.arraycopy(timeStamps, 0, tmp, 0, timeStamps.length);
- timeStamps = tmp;
- }
- if (count != 0) {
- timeStamps[count] = timeStamps[count-1] + ts;
- } else {
- timeStamps[count] = ts;
- }
- count++;
- }
-
- long getBase() {
- return this.base;
- }
- /** Provides direct access to underlying data.
- * Do not modify contents and use getSize() to keep from reading
- * past end of array.
- */
- long[] getRawTimeStamps() {
- return this.timeStamps;
- }
- long getMilliTimeStamp(int idx) {
- return this.base + this.timeStamps[idx];
- }
- /**
- * Returns an array of time stamp values the first of which
- * has the specified index.
- * Each returned time stamp is the number of millis since
- * midnight, Jan 1, 1970 UTC.
- */
- double[] getTimeValuesSinceIdx(int idx) {
- int resultSize = this.count - idx;
- double[] result = new double[resultSize];
- for (int i=0; i < resultSize; i++) {
- result[i] = getMilliTimeStamp(idx+i);
- }
- return result;
- }
- }
-
- /**
- * Defines a statistic resource type. Each resource instance must be
- * of a single type. The type defines what statistics each instance
- * of it will support. The type also has a description of itself.
- */
- public static class ResourceType {
- private boolean loaded;
-// private final int id;
- private final String name;
- private String desc;
- private final StatDescriptor[] stats;
- private Map descriptorMap;
-
- public void dump(PrintWriter stream) {
- if (loaded) {
- stream.println(name + ": " + desc);
- for (int i=0; i < stats.length; i++) {
- stats[i].dump(stream);
- }
- }
- }
-
- protected ResourceType(int id, String name, int statCount) {
- this.loaded = false;
-// this.id = id;
- this.name = name;
- this.desc = null;
- this.stats = new StatDescriptor[statCount];
- this.descriptorMap = null;
- }
-
- protected ResourceType(int id, String name, String desc, int statCount) {
- this.loaded = true;
-// this.id = id;
- this.name = name;
- this.desc = desc;
- this.stats = new StatDescriptor[statCount];
- this.descriptorMap = new HashMap();
- }
- public boolean isLoaded() {
- return this.loaded;
- }
- /**
- * Frees up any resources no longer needed after the archive file is closed.
- * Returns true if this guy is no longer needed.
- */
- protected boolean close() {
- if (isLoaded()) {
- for (int i=0; i < stats.length; i++) {
- if (stats[i] != null) {
- if (!stats[i].isLoaded()) {
- stats[i] = null;
- }
- }
- }
- return false;
- } else {
- return true;
- }
- }
-
- void unload() {
- this.loaded = false;
- this.desc = null;
- for (int i=0; i < this.stats.length; i++) {
- this.stats[i].unload();
- }
- this.descriptorMap.clear();
- this.descriptorMap = null;
- }
-
- protected void addStatDescriptor(StatArchiveFile archive, int offset, String name, boolean isCounter,
- boolean largerBetter,
- byte typeCode, String units, String desc) {
- StatDescriptor descriptor = new StatDescriptor(name, offset, isCounter, largerBetter, typeCode, units, desc);
- this.stats[offset] = descriptor;
- if (archive.loadStatDescriptor(descriptor, this)) {
- descriptorMap.put(name, descriptor);
- }
- }
-
-// private int getId() {
-// return this.id;
-// }
- /**
- * Returns the name of this resource type.
- */
- public String getName() {
- return this.name;
- }
- /**
- * Returns an array of descriptors for each statistic this resource
- * type supports.
- */
- public StatDescriptor[] getStats() {
- return this.stats;
- }
- /**
- * Gets a stat descriptor contained in this type given the stats name.
- * @param name the name of the stat to find in the current type
- * @return the descriptor that matches the name or null if the type
- * does not have a stat of the given name
- */
- public StatDescriptor getStat(String name) {
- return (StatDescriptor)descriptorMap.get(name);
- }
- /**
- * Returns a description of this resource type.
- */
- public String getDescription() {
- return this.desc;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- ResourceType other = (ResourceType) obj;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- return true;
- }
- }
-
- /**
- * Describes some global information about the archive.
- */
- public static class ArchiveInfo {
- private final StatArchiveFile archive;
- private final byte archiveVersion;
- private final long startTimeStamp; // in milliseconds
- private final long systemStartTimeStamp; // in milliseconds
- private final int timeZoneOffset;
- private final String timeZoneName;
- private final String systemDirectory;
- private final long systemId;
- private final String productVersion;
- private final String os;
- private final String machine;
-
- public ArchiveInfo(StatArchiveFile archive, byte archiveVersion,
- long startTimeStamp, long systemStartTimeStamp,
- int timeZoneOffset,String timeZoneName,
- String systemDirectory, long systemId,
- String productVersion, String os, String machine) {
- this.archive = archive;
- this.archiveVersion = archiveVersion;
- this.startTimeStamp = startTimeStamp;
- this.systemStartTimeStamp = systemStartTimeStamp;
- this.timeZoneOffset = timeZoneOffset;
- this.timeZoneName = timeZoneName;
- this.systemDirectory = systemDirectory;
- this.systemId = systemId;
- this.productVersion = productVersion;
- this.os = os;
- this.machine = machine;
- archive.setTimeZone(getTimeZone());
- }
-
- /**
- * Returns the difference, measured in milliseconds, between the time
- * the archive file was create and midnight, January 1, 1970 UTC.
- */
- public long getStartTimeMillis() {
- return this.startTimeStamp;
- }
- /**
- * Returns the difference, measured in milliseconds, between the time
- * the archived system was started and midnight, January 1, 1970 UTC.
- */
- public long getSystemStartTimeMillis() {
- return this.systemStartTimeStamp;
- }
- /**
- * Returns a numeric id of the archived system. It can be used in
- * conjunction with the {@link #getSystemStartTimeMillis} to
- * uniquely identify an archived system.
- */
- public long getSystemId() {
- return this.systemId;
- }
- /**
- * Returns a string describing the operating system the archive was
- * written on.
- */
- public String getOs() {
- return this.os;
- }
- /**
- * Returns a string describing the machine the archive was
- * written on.
- */
- public String getMachine() {
- return this.machine;
- }
- /**
- * Returns the time zone used when the archive was created.
- * This can be used to print timestamps in the same time zone
- * that was in effect when the archive was created.
- */
- public TimeZone getTimeZone() {
- TimeZone result = TimeZone.getTimeZone(this.timeZoneName);
- if (result.getRawOffset() != this.timeZoneOffset) {
- result = new SimpleTimeZone(this.timeZoneOffset, this.timeZoneName);
- }
- return result;
- }
- /**
- * Returns a string containing the version of the product that wrote
- * this archive.
- */
- public String getProductVersion() {
- return this.productVersion;
- }
- /**
- * Returns a numeric code that represents the format version used to
- * encode the archive as a stream of bytes.
- */
- public int getArchiveFormatVersion() {
- return this.archiveVersion;
- }
- /**
- * Returns a string describing the system that this archive recorded.
- */
- public String getSystem() {
- return this.systemDirectory;
- }
- /**
- * Return the name of the file this archive was stored in or
- * an empty string if the archive was not stored in a file.
- */
- public String getArchiveFileName() {
- if (this.archive != null) {
- return this.archive.getFile().getPath();
- } else {
- return "";
- }
- }
-
- /**
- * Returns a string representation of this object.
- */
- @Override
- public String toString() {
- StringWriter sw = new StringWriter();
- this.dump(new PrintWriter(sw));
- return sw.toString();
- }
-
- protected void dump(PrintWriter stream) {
- if (archive != null) {
- stream.println("archive=" + archive.getFile());
- }
- stream.println("archiveVersion=" + archiveVersion);
- if (archive != null) {
- stream.println("startDate=" + archive.formatTimeMillis(startTimeStamp));
- }
- // stream.println("startTimeStamp=" + startTimeStamp +" tz=" + timeZoneName + " tzOffset=" + timeZoneOffset);
- // stream.println("timeZone=" + getTimeZone().getDisplayName());
- stream.println("systemDirectory=" + systemDirectory);
- if (archive != null) {
- stream.println("systemStartDate=" + archive.formatTimeMillis(systemStartTimeStamp));
- }
- stream.println("systemId=" + systemId);
- stream.println("productVersion=" + productVersion);
- stream.println("osInfo=" + os);
- stream.println("machineInfo=" + machine);
- }
- }
-
- /**
- * Defines a single instance of a resource type.
- */
- public static class ResourceInst {
- private final boolean loaded;
- private final StatArchiveFile archive;
-// private final int uniqueId;
- private final ResourceType type;
- private final String name;
- private final long id;
- private boolean active = true;
- private final SimpleValue[] values;
- private int firstTSidx = -1;
- private int lastTSidx = -1;
-
- /**
- * Returns the approximate amount of memory used to implement this object.
- */
- protected int getMemoryUsed() {
- int result = 0;
- if (values != null) {
- for (int i=0; i < values.length; i++) {
- result += this.values[i].getMemoryUsed();
- }
- }
- return result;
- }
-
- public StatArchiveReader getReader() {
- return archive.getReader();
- }
- /**
- * Returns a string representation of this object.
- */
- @Override
- public String toString() {
- StringBuffer result = new StringBuffer();
- result.append(name)
- .append(", ")
- .append(id)
- .append(", ")
- .append(type.getName())
- .append(": \"")
- .append(archive.formatTimeMillis(getFirstTimeMillis()))
- .append('\"');
- if (!active) {
- result.append(" inactive");
- }
- result.append(" samples="+ getSampleCount());
- return result.toString();
- }
- /**
- * Returns the number of times this resource instance has been sampled.
- */
- public int getSampleCount() {
- if (active) {
- return archive.getTimeStamps().getSize() - firstTSidx;
- } else {
- return (lastTSidx+1) - firstTSidx;
- }
- }
-
- public StatArchiveFile getArchive() {
- return this.archive;
- }
-
- protected void dump(PrintWriter stream) {
- stream.println(name + ":"
- + " file=" + getArchive().getFile()
- + " id=" + id
- + (active? "" : " deleted")
- + " start=" + archive.formatTimeMillis(getFirstTimeMillis()));
- for (int i=0; i < values.length; i++) {
- values[i].dump(stream);
- }
- }
-
- protected ResourceInst(StatArchiveFile archive, int uniqueId, String name, long id, ResourceType type, boolean loaded) {
- this.loaded = loaded;
- this.archive = archive;
-// this.uniqueId = uniqueId;
- this.name = name;
- this.id = id;
- Assert.assertTrue(type != null);
- this.type = type;
- if (loaded) {
- StatDescriptor[] stats = type.getStats();
- this.values = new SimpleValue[stats.length];
- for (int i=0; i < stats.length; i++) {
- if (archive.loadStat(stats[i], this)) {
- this.values[i] = new SimpleValue(this, stats[i]);
- } else {
- this.values[i] = null;
- }
- }
- } else {
- this.values = null;
- }
- }
-
- void matchSpec(StatSpec spec, List matchedValues) {
- if (spec.typeMatches(this.type.getName())) {
- if (spec.instanceMatches(this.getName(), this.getId())) {
- for (int statIdx=0; statIdx < values.length; statIdx++) {
- if (values[statIdx] != null) {
- if (spec.statMatches(values[statIdx].getDescriptor().getName())) {
- matchedValues.add(values[statIdx]);
- }
- }
- }
- }
- }
- }
-
- protected void initialValue(int statOffset, long v) {
- if (this.values != null && this.values[statOffset] != null) {
- this.values[statOffset].initialValue(v);
- }
- }
- /**
- * Returns true if sample was added.
- */
- protected boolean addValueSample(int statOffset, long statDeltaBits) {
- if (this.values != null && this.values[statOffset] != null) {
- this.values[statOffset].prepareNextBits(statDeltaBits);
- return true;
- } else {
- return false;
- }
- }
-
- public boolean isLoaded() {
- return this.loaded;
- }
-
- /**
- * Frees up any resources no longer needed after the archive file is closed.
- * Returns true if this guy is no longer needed.
- */
- protected boolean close() {
- if (isLoaded()) {
- for (int i=0; i < values.length; i++) {
- if (values[i] != null) {
- values[i].shrink();
- }
- }
- return false;
- } else {
- return true;
- }
- }
-
- protected int getFirstTimeStampIdx() {
- return this.firstTSidx;
- }
- protected long[] getAllRawTimeStamps() {
- return archive.getTimeStamps().getRawTimeStamps();
- }
- protected long getTimeBase() {
- return archive.getTimeStamps().getBase();
- }
- /**
- * Returns an array of doubles containing the timestamps at which
- * this instances samples where taken. Each of these timestamps
- * is the difference, measured in milliseconds, between the sample
- * time and midnight, January 1, 1970 UTC.
- * Although these values are double they can safely be converted
- * to <code>long</code> with no loss of information.
- */
- public double[] getSnapshotTimesMillis() {
- return archive.getTimeStamps().getTimeValuesSinceIdx(firstTSidx);
- }
- /**
- * Returns an array of statistic value descriptors. Each element
- * of the array describes the corresponding statistic this instance
- * supports. The <code>StatValue</code> instances can be used to
- * obtain the actual sampled values of the instances statistics.
- */
- public StatValue[] getStatValues() {
- return this.values;
- }
- /**
- * Gets the value of the stat in the current instance given the stat name.
- * @param name the name of the stat to find in the current instance
- * @return the value that matches the name or null if the instance
- * does not have a stat of the given name
- *
- */
- public StatValue getStatValue(String name) {
- StatValue result = null;
- StatDescriptor desc = getType().getStat(name);
- if (desc != null) {
- result = values[desc.getOffset()];
- }
- return result;
- }
-
- /**
- * Returns the name of this instance.
- */
- public String getName() {
- return this.name;
- }
- /**
- * Returns the id of this instance.
- */
- public long getId() {
- return this.id;
- }
- /**
- * Returns the difference, measured in milliseconds, between the time
- * of the instance's first sample and midnight, January 1, 1970 UTC.
- */
- public long getFirstTimeMillis() {
- return archive.getTimeStamps().getMilliTimeStamp(firstTSidx);
- }
- /**
- * Returns resource type of this instance.
- */
- public ResourceType getType() {
- return this.type;
- }
- protected void makeInactive() {
- this.active = false;
- lastTSidx = archive.getTimeStamps().getSize() - 1;
- close(); // this frees up unused memory now that no more samples
- }
- /**
- * Returns true if archive might still have future samples for this instance.
- */
- public boolean isActive() {
- return this.active;
- }
- protected void addTimeStamp() {
- if (this.loaded) {
- if (firstTSidx == -1) {
- firstTSidx = archive.getTimeStamps().getSize() - 1;
- }
- for (int i=0; i < values.length; i++) {
- if (values[i] != null) {
- values[i].addSample();
- }
- }
- }
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (int) (id ^ (id >>> 32));
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- result = prime * result + ((type == null) ? 0 : type.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getCl
<TRUNCATED>
[21/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/HostStatHelper.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/HostStatHelper.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/HostStatHelper.java
deleted file mode 100644
index 7ff0b1b..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/HostStatHelper.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-//import com.gemstone.gemfire.util.*;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * Provides native methods which fetch operating system statistics.
- */
-public class HostStatHelper {
- static final int SOLARIS_CODE = 1; // Sparc Solaris
- static final int WINDOWS_CODE = 2;
- static final int LINUX_CODE = 3; // x86 Linux
- static final int OSX_CODE = 4; // Mac OS X
-
- static final int PROCESS_STAT_FLAG = 1;
- static final int SYSTEM_STAT_FLAG = 2;
-
- static final int osCode;
-
- static {
- String osName = System.getProperty("os.name", "unknown");
- if (! PureJavaMode.osStatsAreAvailable()) {
- throw new RuntimeException(LocalizedStrings.HostStatHelper_HOSTSTATHELPER_NOT_ALLOWED_IN_PURE_JAVA_MODE.toLocalizedString());
- } else if (osName.equals("SunOS")) {
- osCode = SOLARIS_CODE;
- } else if (osName.startsWith("Windows")) {
- osCode = WINDOWS_CODE;
- } else if (osName.startsWith("Linux")) {
- osCode = LINUX_CODE;
- } else if (osName.equals("Mac OS X")) {
- osCode = OSX_CODE;
- } else {
- throw new InternalGemFireException(LocalizedStrings.HostStatHelper_UNSUPPORTED_OS_0_SUPPORTED_OSS_ARE_SUNOSSPARC_SOLARIS_LINUXX86_AND_WINDOWS.toLocalizedString(osName));
- }
- }
- public static boolean isWindows() {
- return osCode == WINDOWS_CODE;
- }
- public static boolean isUnix() {
- return osCode != WINDOWS_CODE;
- }
- public static boolean isSolaris() {
- return osCode == SOLARIS_CODE;
- }
- public static boolean isLinux() {
- return osCode == LINUX_CODE;
- }
- public static boolean isOSX() {
- return osCode == OSX_CODE;
- }
-
- private HostStatHelper() {
- // instances are not allowed
- }
-
- static int initOSStats() {
- if(isLinux()) {
- return LinuxProcFsStatistics.init();
- } else {
- return HostStatHelper.init();
- }
- }
-
- static void closeOSStats() {
- if(isLinux()) {
- LinuxProcFsStatistics.close();
- } else {
- HostStatHelper.close();
- }
- }
-
- static void readyRefreshOSStats() {
- if(isLinux()) {
- LinuxProcFsStatistics.readyRefresh();
- } else {
- HostStatHelper.readyRefresh();
- }
- }
-
- /**
- * Allocates and initializes any resources required to sample
- * operating system statistics.
- * returns 0 if initialization succeeded
- */
- private static native int init();
- /**
- * Frees up resources used by this class. Once close is called this
- * class can no longer be used.
- */
- private static native void close();
- /**
- * Should be called before any calls to the refresh methods.
- * On some platforms if this is not called then the refesh methods
- * will just keep returning the same old data.
- */
- private static native void readyRefresh();
- /**
- * Refreshes the specified process stats instance by fetching
- * the current OS values for the given stats and storing them in the instance.
- */
- private static void refreshProcess(LocalStatisticsImpl s) {
- int pid = (int)s.getNumericId();
- if(isLinux()) {
- LinuxProcFsStatistics.refreshProcess(pid, s._getIntStorage(), s._getLongStorage(), s._getDoubleStorage());
- } else {
- refreshProcess(pid, s._getIntStorage(), s._getLongStorage(), s._getDoubleStorage());
- }
- }
- private static native void refreshProcess(int pid, int[] ints, long[] longs, double[] doubles);
- /**
- * Refreshes the specified system stats instance by fetching
- * the current OS values for the local machine and storing them in
- * the instance.
- */
- private static void refreshSystem(LocalStatisticsImpl s) {
- if(isLinux()) {
- LinuxProcFsStatistics.refreshSystem(s._getIntStorage(), s._getLongStorage(), s._getDoubleStorage());
- } else {
- refreshSystem(s._getIntStorage(), s._getLongStorage(), s._getDoubleStorage());
- }
- }
- private static native void refreshSystem(int[] ints, long[] longs, double[] doubles);
-
- /**
- * The call should have already checked to make sure
- * usesSystemCalls returns true.
- */
- public static void refresh(LocalStatisticsImpl stats) {
- int flags = stats.getOsStatFlags();
- if ((flags & PROCESS_STAT_FLAG) != 0) {
- HostStatHelper.refreshProcess(stats);
- } else if ((flags & SYSTEM_STAT_FLAG) != 0) {
- HostStatHelper.refreshSystem(stats);
- } else {
- throw new RuntimeException(LocalizedStrings.HostStatHelper_UNEXPECTED_OS_STATS_FLAGS_0.toLocalizedString(Integer.valueOf(flags)));
- }
- }
-
- /**
- * Creates and returns a {@link Statistics} with
- * the given pid and name. The resource's stats will contain a snapshot
- * of the current statistic values for the specified process.
- */
- public static Statistics newProcess(OsStatisticsFactory f, long pid, String name) {
- Statistics stats;
- switch (osCode) {
- case SOLARIS_CODE:
- stats = f.createOsStatistics(SolarisProcessStats.getType(),
- name, pid, PROCESS_STAT_FLAG);
- break;
- case LINUX_CODE:
- stats = f.createOsStatistics(LinuxProcessStats.getType(),
- name, pid, PROCESS_STAT_FLAG);
- break;
- case OSX_CODE:
- stats = f.createOsStatistics(OSXProcessStats.getType(),
- name, pid, PROCESS_STAT_FLAG);
- break;
- case WINDOWS_CODE:
- stats = f.createOsStatistics(WindowsProcessStats.getType(),
- name, pid, PROCESS_STAT_FLAG);
- break;
- default:
- throw new InternalGemFireException(LocalizedStrings.HostStatHelper_UNHANDLED_OSCODE_0_HOSTSTATHELPERNEWPROCESS.toLocalizedString(Integer.valueOf(osCode)));
- }
- // Note we don't call refreshProcess since we only want the manager to do that
- return stats;
- }
-
- /**
- * Creates a new <code>ProcessStats</code> instance that wraps the
- * given <code>Statistics</code>.
- *
- * @see #newProcess
- * @since GemFire 3.5
- */
- static ProcessStats newProcessStats(Statistics stats) {
- switch (osCode) {
- case SOLARIS_CODE:
- return SolarisProcessStats.createProcessStats(stats);
-
- case LINUX_CODE:
- return LinuxProcessStats.createProcessStats(stats);
-
- case WINDOWS_CODE:
- return WindowsProcessStats.createProcessStats(stats);
-
- case OSX_CODE:
- return OSXProcessStats.createProcessStats(stats);
-
- default:
- throw new InternalGemFireException(LocalizedStrings.HostStatHelper_UNHANDLED_OSCODE_0_HOSTSTATHELPERNEWPROCESSSTATS.toLocalizedString(Integer.valueOf(osCode)));
- }
- }
-
- /**
- * Creates and returns a {@link Statistics} with the current
- * machine's stats. The resource's stats will contain a snapshot
- * of the current statistic values for the local machine.
- */
- static void newSystem(OsStatisticsFactory f) {
- Statistics stats;
- switch (osCode) {
- case SOLARIS_CODE:
- stats = f.createOsStatistics(SolarisSystemStats.getType(),
- getHostSystemName(),
- getHostSystemId(),
- SYSTEM_STAT_FLAG);
- break;
- case LINUX_CODE:
- stats = f.createOsStatistics(LinuxSystemStats.getType(),
- getHostSystemName(),
- getHostSystemId(),
- SYSTEM_STAT_FLAG);
- break;
- case WINDOWS_CODE:
- stats = f.createOsStatistics(WindowsSystemStats.getType(),
- getHostSystemName(),
- getHostSystemId(),
- SYSTEM_STAT_FLAG);
- break;
- case OSX_CODE:
- stats = f.createOsStatistics(OSXSystemStats.getType(),
- getHostSystemName(),
- getHostSystemId(),
- SYSTEM_STAT_FLAG);
- break;
- default:
- throw new InternalGemFireException(LocalizedStrings.HostStatHelper_UNHANDLED_OSCODE_0_HOSTSTATHELPERNEWSYSTEM.toLocalizedString(Integer.valueOf(osCode)));
- }
- if (stats instanceof LocalStatisticsImpl) {
- refreshSystem((LocalStatisticsImpl)stats);
- } // otherwise its a Dummy implementation so do nothing
- }
-
- /**
- * @return this machine's fully qualified hostname
- * or "unknownHostName" if one cannot be found.
- */
- private static String getHostSystemName() {
- String hostname = "unknownHostName";
- try {
- InetAddress addr = SocketCreator.getLocalHost();
- hostname = addr.getCanonicalHostName();
- } catch (UnknownHostException uhe) {
- }
- return hostname;
- }
-
- /**
- * Generate a systemid based off of the ip address of the host.
- * This duplicates the common implementation of
- * <code>long gethostid(void) </code>.
- * Punt on the ipv6 case and just use the same algorithm.
- * @return a psuedo unique id based on the ip address
- */
- private static long getHostSystemId() {
- long id = 0L;
- try {
- InetAddress host = SocketCreator.getLocalHost();
- byte[] addr = host.getAddress();
- id = (addr[1] & 0xFFL) << 24 |
- (addr[0] & 0xFFL) << 16 |
- (addr[3] & 0xFFL) << 8 |
- (addr[2] & 0xFFL) << 0;
- } catch (UnknownHostException uhe) {
- }
- return id;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/HostStatSampler.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/HostStatSampler.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/HostStatSampler.java
deleted file mode 100644
index ff9d2fb..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/HostStatSampler.java
+++ /dev/null
@@ -1,550 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.CancelCriterion;
-import com.gemstone.gemfire.CancelException;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.SystemFailure;
-import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-import com.gemstone.gemfire.internal.logging.LogService;
-import com.gemstone.gemfire.internal.logging.LoggingThreadGroup;
-import com.gemstone.gemfire.internal.logging.log4j.LocalizedMessage;
-import com.gemstone.gemfire.internal.logging.log4j.LogMarker;
-import com.gemstone.gemfire.internal.statistics.CallbackSampler;
-import com.gemstone.gemfire.internal.statistics.SampleCollector;
-import com.gemstone.gemfire.internal.statistics.StatArchiveHandlerConfig;
-import com.gemstone.gemfire.internal.statistics.StatisticsSampler;
-import com.gemstone.gemfire.internal.util.concurrent.StoppableCountDownLatch;
-import org.apache.logging.log4j.Logger;
-
-import java.io.File;
-import java.net.UnknownHostException;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
-/**
- * HostStatSampler implements a thread which will monitor, sample, and archive
- * statistics. It only has the common functionality that any sampler needs.
-
- */
-public abstract class HostStatSampler
- implements Runnable, StatisticsSampler, StatArchiveHandlerConfig {
-
- private static final Logger logger = LogService.getLogger();
-
- public static final String TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY = DistributionConfig.GEMFIRE_PREFIX + "stats.test.fileSizeLimitInKB";
- public static final String OS_STATS_DISABLED_PROPERTY = "osStatsDisabled";
-
- protected static final String INITIALIZATION_TIMEOUT_PROPERTY = DistributionConfig.GEMFIRE_PREFIX + "statSamplerInitializationTimeout";
- protected static final int INITIALIZATION_TIMEOUT_DEFAULT = 30000;
- protected static final long INITIALIZATION_TIMEOUT_MILLIS =
- Long.getLong(INITIALIZATION_TIMEOUT_PROPERTY, INITIALIZATION_TIMEOUT_DEFAULT);
-
- /**
- * Used to check if the sampler thread wake-up is delayed, and log a warning if it is delayed by longer than
- * the amount of milliseconds specified by this property. The value of 0 disables the check.
- */
- private static final long STAT_SAMPLER_DELAY_THRESHOLD = Long.getLong(DistributionConfig.GEMFIRE_PREFIX + "statSamplerDelayThreshold", 3000);
- private static final long STAT_SAMPLER_DELAY_THRESHOLD_NANOS = NanoTimer.millisToNanos(STAT_SAMPLER_DELAY_THRESHOLD);
-
- private static final int MIN_MS_SLEEP = 1;
-
- private static final int WAIT_FOR_SLEEP_INTERVAL = 10;
-
- private static Thread statThread = null;
-
- private volatile boolean stopRequested = false;
-
- private final boolean osStatsDisabled = Boolean.getBoolean(OS_STATS_DISABLED_PROPERTY);
- private final boolean fileSizeLimitInKB;
- private final StatSamplerStats samplerStats;
-
- private VMStatsContract vmStats;
- private SampleCollector sampleCollector;
-
- /**
- * Used to signal thread that are waiting for the stat sampler to be initialized.
- */
- private final StoppableCountDownLatch statSamplerInitializedLatch;
-
- private final CancelCriterion stopper;
-
- private final CallbackSampler callbackSampler;
-
- protected HostStatSampler(CancelCriterion stopper,
- StatSamplerStats samplerStats) {
- this.stopper = stopper;
- this.statSamplerInitializedLatch = new StoppableCountDownLatch(this.stopper, 1);
- this.samplerStats = samplerStats;
- this.fileSizeLimitInKB = Boolean.getBoolean(TEST_FILE_SIZE_LIMIT_IN_KB_PROPERTY);
- this.callbackSampler = new CallbackSampler(stopper, samplerStats);
- }
-
- public final StatSamplerStats getStatSamplerStats() {
- return this.samplerStats;
- }
-
- /**
- * Returns the number of times a statistics resource has been add or deleted.
- */
- @Override
- public final int getStatisticsModCount() {
- return getStatisticsManager().getStatListModCount();
- }
-
- /**
- * Returns an array of all the current statistic resource instances.
- */
- @Override
- public final Statistics[] getStatistics() {
- return getStatisticsManager().getStatistics();
- }
-
- /**
- * Returns a unique id for the sampler's system.
- */
- @Override
- public final long getSystemId() {
- return getStatisticsManager().getId();
- }
-
- /**
- * Returns the time this sampler's system was started.
- */
- @Override
- public final long getSystemStartTime() {
- return getStatisticsManager().getStartTime();
- }
-
- /**
- * Returns the path to this sampler's system directory; if it has one.
- */
- @Override
- public final String getSystemDirectoryPath() {
- try {
- return SocketCreator.getHostName(SocketCreator.getLocalHost());
- } catch (UnknownHostException ignore) {
- return "";
- }
- }
-
- @Override
- public boolean waitForSample(long timeout) throws InterruptedException {
- final long endTime = System.currentTimeMillis() + timeout;
- final int startSampleCount = this.samplerStats.getSampleCount();
- while (System.currentTimeMillis() < endTime &&
- this.samplerStats.getSampleCount() <= startSampleCount) {
- Thread.sleep(WAIT_FOR_SLEEP_INTERVAL);
- }
- return this.samplerStats.getSampleCount() > startSampleCount;
- }
-
- @Override
- public SampleCollector waitForSampleCollector(long timeout) throws InterruptedException {
- final long endTime = System.currentTimeMillis() + timeout;
- while (System.currentTimeMillis() < endTime &&
- this.sampleCollector == null || !this.sampleCollector.isInitialized()) {
- Thread.sleep(WAIT_FOR_SLEEP_INTERVAL);
- }
- return this.sampleCollector;
- }
-
- /**
- * This service's main loop
- */
- @Override
- public final void run() {
- NanoTimer timer = new NanoTimer();
-
- final boolean isDebugEnabled_STATISTICS = logger.isTraceEnabled(LogMarker.STATISTICS);
- if (isDebugEnabled_STATISTICS) {
- logger.trace(LogMarker.STATISTICS, "HostStatSampler started");
- }
- boolean latchCountedDown = false;
- try {
- initSpecialStats();
-
- this.sampleCollector = new SampleCollector(this);
- this.sampleCollector.initialize(this, NanoTimer.getTime());
-
- this.statSamplerInitializedLatch.countDown();
- latchCountedDown = true;
-
- timer.reset();
- // subtract getNanoRate from lastTS to force a quick initial sample
- long nanosLastTimeStamp = timer.getLastResetTime() - getNanoRate();
- while (!stopRequested()) {
- SystemFailure.checkFailure();
- if (Thread.currentThread().isInterrupted()) {
- break;
- }
- final long nanosBeforeSleep = timer.getLastResetTime();
- final long nanosToDelay = nanosLastTimeStamp + getNanoRate();
- delay(timer, nanosToDelay);
- nanosLastTimeStamp = timer.getLastResetTime();
- if (!stopRequested() && isSamplingEnabled()) {
- final long nanosTimeStamp = timer.getLastResetTime();
- final long nanosElapsedSleeping = nanosTimeStamp - nanosBeforeSleep;
- checkElapsedSleepTime(nanosElapsedSleeping);
- if (stopRequested()) break;
- sampleSpecialStats(false);
- if (stopRequested()) break;
- checkListeners();
- if (stopRequested()) break;
-
- this.sampleCollector.sample(nanosTimeStamp);
-
- final long nanosSpentWorking = timer.reset();
- accountForTimeSpentWorking(nanosSpentWorking, nanosElapsedSleeping);
- } else if (!stopRequested() && !isSamplingEnabled()) {
- sampleSpecialStats(true); // fixes bug 42527
- }
- }
- }
- catch (InterruptedException ex) {
- // Silently exit
- }
- catch (CancelException ex) {
- // Silently exit
- }
- catch (RuntimeException ex) {
- logger.fatal(LogMarker.STATISTICS, ex.getMessage(), ex);
- throw ex;
- }
- catch (VirtualMachineError err) {
- SystemFailure.initiateFailure(err);
- // If this ever returns, rethrow the error. We're poisoned
- // now, so don't let this thread continue.
- throw err;
- }
- catch (Error ex) {
- // Whenever you catch Error or Throwable, you must also
- // catch VirtualMachineError (see above). However, there is
- // _still_ a possibility that you are dealing with a cascading
- // error condition, so you also need to check to see if the JVM
- // is still usable:
- SystemFailure.checkFailure();
- logger.fatal(LogMarker.STATISTICS, ex.getMessage(), ex);
- throw ex;
- } finally {
- try {
- closeSpecialStats();
- if (this.sampleCollector != null) {
- this.sampleCollector.close();
- }
- } finally {
- if (!latchCountedDown) {
- // Make sure the latch gets counted down since
- // other threads wait for this to indicate that
- // the sampler is initialized.
- this.statSamplerInitializedLatch.countDown();
- }
- }
- if (isDebugEnabled_STATISTICS) {
- logger.trace(LogMarker.STATISTICS, "HostStatSampler stopped");
- }
- }
- }
-
- /**
- * Starts the main thread for this service.
- * @throws IllegalStateException if an instance of the {@link #statThread} is still running from a previous DistributedSystem.
- */
- public final void start() {
- synchronized(HostStatSampler.class) {
- if (statThread != null) {
- try {
- int msToWait = getSampleRate() + 100;
- statThread.join(msToWait);
- } catch (InterruptedException ex) {
- Thread.currentThread().interrupt();
- }
- if (statThread.isAlive()) {
- throw new IllegalStateException(LocalizedStrings.HostStatSampler_STATISTICS_SAMPLING_THREAD_IS_ALREADY_RUNNING_INDICATING_AN_INCOMPLETE_SHUTDOWN_OF_A_PREVIOUS_CACHE.toLocalizedString());
- }
- }
- ThreadGroup group =
- LoggingThreadGroup.createThreadGroup("StatSampler Threads");
-
- this.callbackSampler.start(getStatisticsManager(), group, getSampleRate(), TimeUnit.MILLISECONDS);
- statThread = new Thread(group, this);
- statThread.setName(statThread.getName() + " StatSampler");
- statThread.setPriority(Thread.MAX_PRIORITY);
- statThread.setDaemon(true);
- statThread.start();
- // fix #46310 (race between management and sampler init) by waiting for init here
- try {
- waitForInitialization(INITIALIZATION_TIMEOUT_MILLIS);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- }
-
- /**
- * Tell this service's main thread to terminate.
- */
- public final void stop() {
- stop(true);
- }
- private final void stop(boolean interruptIfAlive) {
- synchronized (HostStatSampler.class) {
- this.callbackSampler.stop();
- if ( statThread == null) {
- return;
- }
-
- this.stopRequested = true;
- synchronized (this) {
- this.notifyAll();
- }
- try {
- statThread.join(5000);
- } catch (InterruptedException ignore) {
- //It is important that we shutdown so we'll continue trying for another 2 seconds
- try {
- statThread.join(2000);
- } catch (InterruptedException ex) {
- } finally {
- Thread.currentThread().interrupt();
- }
- } finally {
- if ( statThread.isAlive() ) {
- if (interruptIfAlive) {
- // It is still alive so interrupt the thread
- statThread.interrupt();
- stop(false);
- } else {
- logger.warn(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.HostStatSampler_HOSTSTATSAMPLER_THREAD_COULD_NOT_BE_STOPPED));
- }
- } else {
- this.stopRequested = false;
- statThread = null;
- }
- }
- }
- }
-
- public final boolean isAlive() {
- synchronized (HostStatSampler.class) {
- return statThread != null && statThread.isAlive();
- }
- }
-
- /**
- * Waits for the special statistics to be initialized. For tests, please
- * use {@link #waitForInitialization(long)} instead.
- *
- * @see #initSpecialStats
- * @since GemFire 3.5
- */
- public final void waitForInitialization() throws InterruptedException {
- this.statSamplerInitializedLatch.await();
- }
-
- /**
- * Waits for the special statistics to be initialized. This overridden
- * version of {@link #waitForInitialization()} should always be used
- * within tests.
- *
- * @see #initSpecialStats
- * @since GemFire 7.0
- */
- public final boolean waitForInitialization(long ms) throws InterruptedException {
- return this.statSamplerInitializedLatch.await(ms);
- }
-
- public final void changeArchive(File newFile) {
- this.sampleCollector.changeArchive(newFile, NanoTimer.getTime());
- }
-
- /**
- * Returns the <code>VMStatsContract</code> for this VM.
- *
- * @since GemFire 3.5
- */
- public final VMStatsContract getVMStats() {
- return this.vmStats;
- }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder(getClass().getName());
- sb.append("@").append(System.identityHashCode(this));
- return sb.toString();
- }
-
- protected abstract void checkListeners();
-
- /**
- * Gets the sample rate in milliseconds
- */
- protected abstract int getSampleRate();
-
- /**
- * Returns true if sampling is enabled.
- */
- public abstract boolean isSamplingEnabled();
-
- /**
- * Returns the statistics manager using this sampler.
- */
- protected abstract StatisticsManager getStatisticsManager();
-
- protected OsStatisticsFactory getOsStatisticsFactory() {
- return null;
- }
-
- protected void initProcessStats(long id) {
- // do nothing by default
- }
-
- protected void sampleProcessStats(boolean prepareOnly) {
- // do nothing by default
- }
-
- protected void closeProcessStats() {
- // do nothing by default
- }
-
- protected long getSpecialStatsId() {
- return getStatisticsManager().getId();
- }
-
- protected final boolean fileSizeLimitInKB() {
- return this.fileSizeLimitInKB;
- }
-
- protected final boolean osStatsDisabled() {
- return this.osStatsDisabled;
- }
-
- protected final boolean stopRequested() {
- return stopper.isCancelInProgress() || this.stopRequested;
- }
-
- public final SampleCollector getSampleCollector() {
- return this.sampleCollector;
- }
-
- /**
- * Initialize any special sampler stats
- */
- private synchronized void initSpecialStats() {
- // add a vm resource
- long id = getSpecialStatsId();
- this.vmStats = VMStatsContractFactory.create(getStatisticsManager(), id);
- initProcessStats(id);
- }
-
- /**
- * Closes down anything initialied by initSpecialStats.
- */
- private synchronized void closeSpecialStats() {
- if (this.vmStats != null) {
- this.vmStats.close();
- }
- closeProcessStats();
- }
-
- /**
- * Called when this sampler has spent some time working and wants
- * it to be accounted for.
- */
- private void accountForTimeSpentWorking(long nanosSpentWorking,
- long nanosSpentSleeping) {
- this.samplerStats.tookSample(
- nanosSpentWorking, getStatisticsManager().getStatisticsCount(), nanosSpentSleeping);
- }
-
- /**
- * @param timer a NanoTimer used to compute the elapsed delay
- * @param nanosToDelay the timestamp to delay until it is the current time
- */
- private void delay(NanoTimer timer, final long nanosToDelay) throws InterruptedException {
- timer.reset();
- long now = timer.getLastResetTime();
- long remainingNanos = nanosToDelay - now;
- if (remainingNanos <= 0) {
- remainingNanos = NanoTimer.millisToNanos(MIN_MS_SLEEP);
- }
- while (remainingNanos > 0 && !stopRequested()) {
- long ms = NanoTimer.nanosToMillis(remainingNanos);
- if (ms <= 0) {
- Thread.yield();
- } else {
- if (ms > MIN_MS_SLEEP) {
- ms -= MIN_MS_SLEEP;
- }
- synchronized (this) {
- if (stopRequested()) {
- // check stopRequested inside the sync to prevent a race in which the wait misses the stopper's notify.
- return;
- }
- this.wait(ms); // spurious wakeup ok
- }
- }
- timer.reset();
- now = timer.getLastResetTime();
- remainingNanos = nanosToDelay - now;
- }
- }
-
- private long getNanoRate() {
- return NanoTimer.millisToNanos(getSampleRate());
- }
-
- /**
- * Collect samples of any operating system statistics
- *
- * @param prepareOnly
- * set to true if you only want to call prepareForSample
- */
- private void sampleSpecialStats(boolean prepareOnly) {
- List<Statistics> statsList = getStatisticsManager().getStatsList();
- for (Statistics s : statsList) {
- if (stopRequested()) return;
- if (s instanceof StatisticsImpl) {
- ((StatisticsImpl)s).prepareForSample();
- }
- }
-
- if (!prepareOnly && this.vmStats != null) {
- if (stopRequested()) return;
- this.vmStats.refresh();
- }
- sampleProcessStats(prepareOnly);
- }
-
- /**
- * Check the elapsed sleep time upon wakeup, and log a warning if it is longer than the delay
- * threshold.
- *
- * @param elapsedSleepTime duration of sleep in nanoseconds
- */
- private void checkElapsedSleepTime(long elapsedSleepTime) {
- if (STAT_SAMPLER_DELAY_THRESHOLD > 0) {
- final long wakeupDelay = elapsedSleepTime - getNanoRate();
- if (wakeupDelay > STAT_SAMPLER_DELAY_THRESHOLD_NANOS) {
- this.samplerStats.incJvmPauses();
- logger.warn(LogMarker.STATISTICS, LocalizedMessage.create(LocalizedStrings.HostStatSampler_STATISTICS_SAMPLING_THREAD_DETECTED_A_WAKEUP_DELAY_OF_0_MS_INDICATING_A_POSSIBLE_RESOURCE_ISSUE, NanoTimer.nanosToMillis(wakeupDelay)));
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxProcFsStatistics.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxProcFsStatistics.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxProcFsStatistics.java
deleted file mode 100644
index 3070287..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxProcFsStatistics.java
+++ /dev/null
@@ -1,783 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import org.apache.logging.log4j.Logger;
-
-import java.io.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.NoSuchElementException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class LinuxProcFsStatistics {
- private enum CPU {
- USER, NICE, SYSTEM, IDLE, IOWAIT, IRQ, SOFTIRQ,
- /** stands for aggregation of all columns not present in the enum list*/
- OTHER
- }
-
- private static final int DEFAULT_PAGESIZE = 4 * 1024;
- private static final int OneMeg = 1024 * 1024;
- private static final String pageSizeProperty = DistributionConfig.GEMFIRE_PREFIX + "statistics.linux.pageSize";
- private static CpuStat cpuStatSingleton;
- private static int pageSize;
- private static int sys_cpus;
- private static boolean hasProcVmStat;
- private static boolean hasDiskStats;
- static SpaceTokenizer st;
-
- /** The number of non-process files in /proc */
- private static int nonPidFilesInProc;
-
- /** /proc/stat tokens */
- private static final String CPU_TOKEN = "cpu ";
- private static final String PAGE = "page ";
- private static final String SWAP = "swap ";
- private static final String CTXT = "ctxt ";
- private static final String PROCESSES = "processes ";
-
- /** /proc/vmstat tokens */
- private static final String PGPGIN = "pgpgin ";
- private static final String PGPGOUT = "pgpgout ";
- private static final String PSWPIN = "pswpin ";
- private static final String PSWPOUT = "pswpout ";
-
- //Do not create instances of this class
- private LinuxProcFsStatistics() {
- }
-
- static int init() {
- nonPidFilesInProc = getNumberOfNonProcessProcFiles();
- sys_cpus = Runtime.getRuntime().availableProcessors();
- pageSize = Integer.getInteger(pageSizeProperty, DEFAULT_PAGESIZE);
- cpuStatSingleton = new CpuStat();
- hasProcVmStat = new File("/proc/vmstat").exists();
- hasDiskStats = new File("/proc/diskstats").exists();
- st = new SpaceTokenizer();
- return 0;
- }
-
- static void close() {
- cpuStatSingleton = null;
- st = null;
- }
-
- static void readyRefresh() {
- }
-
- /* get the statistics for the specified process.
- * ( pid_rssSize, pid_imageSize )
- * vsize is assumed to be in units of kbytes
- * System property gemfire.statistics.pagesSize can be used to configure
- * pageSize. This is the mem_unit member of the struct returned by sysinfo()
- *
- */
- static void refreshProcess(int pid, int[] ints, long[] longs, double[] doubles) {
- //Just incase a pid is not available
- if(pid == 0) return;
- InputStreamReader isr = null;
- BufferedReader br = null;
- try {
- File file = new File( "/proc/" + pid + "/stat" );
- isr = new InputStreamReader( new FileInputStream( file ));
- br = new BufferedReader(isr, 2048);
- String line = br.readLine();
- if ( line == null ) {
- return;
- }
- st.setString(line);
- st.skipTokens(22);
- ints[LinuxProcessStats.imageSizeINT] = (int) (st.nextTokenAsLong() / OneMeg);
- ints[LinuxProcessStats.rssSizeINT] = (int) ((st.nextTokenAsLong()*pageSize)/OneMeg);
- } catch ( NoSuchElementException nsee ) {
- // It might just be a case of the process going away while we
- // where trying to get its stats.
- // So for now lets just ignore the failure and leave the stats
- // as they are.
- } catch ( IOException ioe ) {
- // It might just be a case of the process going away while we
- // where trying to get its stats.
- // So for now lets just ignore the failure and leave the stats
- // as they are.
- } finally {
- st.releaseResources();
- if(br != null) try { br.close(); } catch(IOException ignore) {}
- }
- }
-
- static void refreshSystem(int[] ints, long[] longs, double[] doubles) {
- ints[LinuxSystemStats.processesINT] = getProcessCount();
- ints[LinuxSystemStats.cpusINT] = sys_cpus;
- InputStreamReader isr = null;
- BufferedReader br = null;
- try {
- isr = new InputStreamReader( new FileInputStream( "/proc/stat" ));
- br = new BufferedReader(isr);
- String line = null;
- while ( ( line = br.readLine() ) != null ) {
- try {
- if (line.startsWith(CPU_TOKEN)) {
- int[] cpuData = cpuStatSingleton.calculateStats(line);
- ints[LinuxSystemStats.cpuIdleINT] = cpuData[CPU.IDLE.ordinal()];
- ints[LinuxSystemStats.cpuNiceINT] = cpuData[CPU.NICE.ordinal()];
- ints[LinuxSystemStats.cpuSystemINT] = cpuData[CPU.SYSTEM.ordinal()];
- ints[LinuxSystemStats.cpuUserINT] = cpuData[CPU.USER.ordinal()];
- ints[LinuxSystemStats.iowaitINT] = cpuData[CPU.IOWAIT.ordinal()];
- ints[LinuxSystemStats.irqINT] = cpuData[CPU.IRQ.ordinal()];
- ints[LinuxSystemStats.softirqINT] = cpuData[CPU.SOFTIRQ.ordinal()];
- ints[LinuxSystemStats.cpuActiveINT] = 100 - cpuData[CPU.IDLE.ordinal()];
- ints[LinuxSystemStats.cpuNonUserINT] = cpuData[CPU.OTHER.ordinal()]
- + cpuData[CPU.SYSTEM.ordinal()]
- + cpuData[CPU.IOWAIT.ordinal()]
- + cpuData[CPU.IRQ.ordinal()]
- + cpuData[CPU.SOFTIRQ.ordinal()];
- } else if ( !hasProcVmStat && line.startsWith(PAGE)) {
- int secondIndex = line.indexOf(" ", PAGE.length());
- longs[LinuxSystemStats.pagesPagedInLONG] = SpaceTokenizer.parseAsLong(line.substring(PAGE.length(), secondIndex));
- longs[LinuxSystemStats.pagesPagedOutLONG] = SpaceTokenizer.parseAsLong(line.substring(secondIndex+1));
- } else if ( !hasProcVmStat && line.startsWith(SWAP)) {
- int secondIndex = line.indexOf(" ", SWAP.length());
- longs[LinuxSystemStats.pagesSwappedInLONG] = SpaceTokenizer.parseAsLong(line.substring(SWAP.length(), secondIndex));
- longs[LinuxSystemStats.pagesSwappedOutLONG] = SpaceTokenizer.parseAsLong(line.substring(secondIndex+1));
- } else if ( line.startsWith(CTXT)) {
- longs[LinuxSystemStats.contextSwitchesLONG] = SpaceTokenizer.parseAsLong(line.substring(CTXT.length()));
- } else if ( line.startsWith(PROCESSES)) {
- longs[LinuxSystemStats.processCreatesLONG] = SpaceTokenizer.parseAsInt(line.substring(PROCESSES.length()));
- }
- } catch ( NoSuchElementException nsee ) {
- //this is the result of reading a partially formed file
- //just do not update what ever entry had the problem
- }
- }
- } catch ( IOException ioe ) {
- } finally {
- if(br != null) try { br.close(); } catch(IOException ignore) {}
- }
- getLoadAvg(doubles);
- getMemInfo(ints);
- getDiskStats(longs);
- getNetStats(longs);
- if(hasProcVmStat) {
- getVmStats(longs);
- }
- st.releaseResources();
- }
-
- // Example of /proc/loadavg
- // 0.00 0.00 0.07 1/218 7907
- private static void getLoadAvg(double[] doubles) {
- InputStreamReader isr = null;
- BufferedReader br = null;
- try {
- isr = new InputStreamReader( new FileInputStream( "/proc/loadavg" ));
- br = new BufferedReader(isr, 512);
- String line = br.readLine();
- if ( line == null ) {
- return;
- }
- st.setString(line);
- doubles[LinuxSystemStats.loadAverage1DOUBLE] = st.nextTokenAsDouble();
- doubles[LinuxSystemStats.loadAverage5DOUBLE] = st.nextTokenAsDouble();
- doubles[LinuxSystemStats.loadAverage15DOUBLE] = st.nextTokenAsDouble();
- } catch ( NoSuchElementException nsee ) {
- } catch (IOException ioe) {
- } finally {
- st.releaseResources();
- if(br != null) try { br.close(); } catch(IOException ignore) {}
- }
- }
-
- /**
- * Returns the available system memory (free + cached).
- * @param logger the logger
- * @return the available memory in bytes
- */
- public static long getAvailableMemory(Logger logger) {
- try {
- BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("/proc/meminfo")));
- try {
- long free = 0;
- Pattern p = Pattern.compile("(.*)?:\\s+(\\d+)( kB)?");
-
- String line;
- while ((line = br.readLine()) != null) {
- Matcher m = p.matcher(line);
- if (m.matches() && ("MemFree".equals(m.group(1)) || "Cached".equals(m.group(1)))) {
- free += Long.parseLong(m.group(2));
- }
- }
-
- // convert to bytes
- return 1024 * free;
-
- } finally {
- br.close();
- }
- } catch (IOException e) {
- logger.warn("Error determining free memory", e);
- return Long.MAX_VALUE;
- }
- }
-
- // Example of /proc/meminfo
- // total: used: free: shared: buffers: cached:
- //Mem: 4118380544 3816050688 302329856 0 109404160 3060326400
- //Swap: 4194881536 127942656 4066938880
- private static void getMemInfo(int[] ints) {
- InputStreamReader isr = null;
- BufferedReader br = null;
- try {
- isr = new InputStreamReader( new FileInputStream( "/proc/meminfo" ));
- br = new BufferedReader(isr);
- //Assume all values read in are in kB, convert to MB
- String line = null;
- while ( (line = br.readLine()) != null) {
- try {
- if ( line.startsWith("MemTotal: ")) {
- st.setString(line);
- st.skipToken(); //Burn initial token
- ints[LinuxSystemStats.physicalMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
- } else if ( line.startsWith("MemFree: ")) {
- st.setString(line);
- st.skipToken(); //Burn initial token
- ints[LinuxSystemStats.freeMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
- } else if ( line.startsWith("SharedMem: ")) {
- st.setString(line);
- st.skipToken(); //Burn initial token
- ints[LinuxSystemStats.sharedMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
- } else if ( line.startsWith("Buffers: ")) {
- st.setString(line);
- st.nextToken(); //Burn initial token
- ints[LinuxSystemStats.bufferMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
- } else if ( line.startsWith("SwapTotal: ")) {
- st.setString(line);
- st.skipToken(); //Burn initial token
- ints[LinuxSystemStats.allocatedSwapINT] = (int) (st.nextTokenAsLong() / 1024);
- } else if ( line.startsWith("SwapFree: ")) {
- st.setString(line);
- st.skipToken(); //Burn initial token
- ints[LinuxSystemStats.unallocatedSwapINT] = (int) (st.nextTokenAsLong() / 1024);
- } else if ( line.startsWith("Cached: ")) {
- st.setString(line);
- st.skipToken(); //Burn initial token
- ints[LinuxSystemStats.cachedMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
- } else if ( line.startsWith("Dirty: ")) {
- st.setString(line);
- st.skipToken(); //Burn initial token
- ints[LinuxSystemStats.dirtyMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
- } else if ( line.startsWith("Inact_dirty: ")) { // 2.4 kernels
- st.setString(line);
- st.skipToken(); //Burn initial token
- ints[LinuxSystemStats.dirtyMemoryINT] = (int) (st.nextTokenAsLong() / 1024);
- }
- } catch(NoSuchElementException nsee) {
- //ignore and let that stat not to be updated this time
- }
- }
- } catch ( IOException ioe ) {
- } finally {
- st.releaseResources();
- if(br != null) try { br.close(); } catch(IOException ignore) {}
- }
- }
-
- /*
-Inter-| Receive | Transmit
- face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
- lo:1908275823 326949246 0 0 0 0 0 0 1908275823 326949246 0 0 0 0 0 0
-*/
-
- private static void getNetStats(long[] longs) {
- InputStreamReader isr = null;
- BufferedReader br = null;
- try {
- isr = new InputStreamReader( new FileInputStream( "/proc/net/dev" ));
- br = new BufferedReader(isr);
- br.readLine(); // Discard header info
- br.readLine(); // Discard header info
- long lo_recv_packets = 0, lo_recv_bytes = 0;
- long other_recv_packets = 0, other_recv_bytes = 0;
- long other_recv_errs = 0, other_recv_drop = 0;
- long other_xmit_packets = 0, other_xmit_bytes = 0;
- long other_xmit_errs = 0, other_xmit_drop = 0, other_xmit_colls = 0;
- String line = null;
- while ( (line = br.readLine()) != null) {
- int index = line.indexOf(":");
- boolean isloopback = (line.indexOf("lo:") != -1);
- st.setString(line.substring(index+1).trim());
- long recv_bytes = st.nextTokenAsLong();
- long recv_packets = st.nextTokenAsLong();
- long recv_errs = st.nextTokenAsLong();
- long recv_drop = st.nextTokenAsLong();
- st.skipTokens(4); //fifo, frame, compressed, multicast
- long xmit_bytes = st.nextTokenAsLong();
- long xmit_packets = st.nextTokenAsLong();
- long xmit_errs = st.nextTokenAsLong();
- long xmit_drop = st.nextTokenAsLong();
- st.skipToken(); //fifo
- long xmit_colls = st.nextTokenAsLong();
-
- if (isloopback) {
- lo_recv_packets = recv_packets;
- lo_recv_bytes = recv_bytes;
- }
- else {
- other_recv_packets += recv_packets;
- other_recv_bytes += recv_bytes;
- }
- other_recv_errs += recv_errs;
- other_recv_drop += recv_drop;
-
- if (isloopback) {
- /* loopback_xmit_packets = xmit_packets; */
- } else {
- other_xmit_packets += xmit_packets;
- other_xmit_bytes += xmit_bytes;
- }
- other_xmit_errs += xmit_errs;
- other_xmit_drop += xmit_drop;
- other_xmit_colls += xmit_colls;
- }
- // fix for bug 43860
- longs[LinuxSystemStats.loopbackPacketsLONG] = lo_recv_packets;
- longs[LinuxSystemStats.loopbackBytesLONG] = lo_recv_bytes;
- longs[LinuxSystemStats.recvPacketsLONG] = other_recv_packets;
- longs[LinuxSystemStats.recvBytesLONG] = other_recv_bytes;
- longs[LinuxSystemStats.recvErrorsLONG] = other_recv_errs;
- longs[LinuxSystemStats.recvDropsLONG] = other_recv_drop;
- longs[LinuxSystemStats.xmitPacketsLONG] = other_xmit_packets;
- longs[LinuxSystemStats.xmitBytesLONG] = other_xmit_bytes;
- longs[LinuxSystemStats.xmitErrorsLONG] = other_xmit_errs;
- longs[LinuxSystemStats.xmitDropsLONG] = other_xmit_drop;
- longs[LinuxSystemStats.xmitCollisionsLONG] = other_xmit_colls;
- } catch (NoSuchElementException nsee) {
- } catch (IOException ioe) {
- } finally {
- st.releaseResources();
- if(br != null) try { br.close(); } catch(IOException ignore) {}
- }
- }
-
- // example of /proc/diskstats
-// 1 0 ram0 0 0 0 0 0 0 0 0 0 0 0
-// 1 1 ram1 0 0 0 0 0 0 0 0 0 0 0
-// 1 2 ram2 0 0 0 0 0 0 0 0 0 0 0
-// 1 3 ram3 0 0 0 0 0 0 0 0 0 0 0
-// 1 4 ram4 0 0 0 0 0 0 0 0 0 0 0
-// 1 5 ram5 0 0 0 0 0 0 0 0 0 0 0
-// 1 6 ram6 0 0 0 0 0 0 0 0 0 0 0
-// 1 7 ram7 0 0 0 0 0 0 0 0 0 0 0
-// 1 8 ram8 0 0 0 0 0 0 0 0 0 0 0
-// 1 9 ram9 0 0 0 0 0 0 0 0 0 0 0
-// 1 10 ram10 0 0 0 0 0 0 0 0 0 0 0
-// 1 11 ram11 0 0 0 0 0 0 0 0 0 0 0
-// 1 12 ram12 0 0 0 0 0 0 0 0 0 0 0
-// 1 13 ram13 0 0 0 0 0 0 0 0 0 0 0
-// 1 14 ram14 0 0 0 0 0 0 0 0 0 0 0
-// 1 15 ram15 0 0 0 0 0 0 0 0 0 0 0
-// 8 0 sda 1628761 56603 37715982 5690640 6073889 34091137 330349716 279787924 0 25235208 285650572
-// 8 1 sda1 151 638 45 360
-// 8 2 sda2 674840 11202608 8591346 68716852
-// 8 3 sda3 1010409 26512312 31733575 253868616
-// 8 16 sdb 12550386 47814 213085738 60429448 5529812 210792345 1731459040 1962038752 0 33797176 2024138028
-// 8 17 sdb1 12601113 213085114 216407197 1731257800
-// 3 0 hda 0 0 0 0 0 0 0 0 0 0 0
- private static void getDiskStats(long[] longs) {
- InputStreamReader isr = null;
- BufferedReader br = null;
- String line = null;
- try {
- if (hasDiskStats) {
- // 2.6 kernel
- isr = new InputStreamReader( new FileInputStream( "/proc/diskstats" ));
- } else {
- // 2.4 kernel
- isr = new InputStreamReader( new FileInputStream( "/proc/partitions" ));
- }
- br = new BufferedReader(isr);
- long readsCompleted = 0, readsMerged = 0;
- long sectorsRead = 0, timeReading = 0;
- long writesCompleted = 0, writesMerged = 0;
- long sectorsWritten = 0, timeWriting = 0;
- long iosInProgress = 0;
- long timeIosInProgress = 0;
- long ioTime = 0;
- if (!hasDiskStats) {
- br.readLine(); // Discard header info
- br.readLine(); // Discard header info
- }
- while ( (line = br.readLine()) != null) {
- st.setString(line);
- {
- // " 8 1 sdb" on 2.6
- // " 8 1 452145145 sdb" on 2.4
- String tok = st.nextToken();
- if (tok.length() == 0 || Character.isWhitespace(tok.charAt(0))) {
- // skip over first token since it is whitespace
- tok = st.nextToken();
- }
- // skip first token it is some number
- tok = st.nextToken();
- // skip second token it is some number
- tok = st.nextToken();
- if (!hasDiskStats) {
- // skip third token it is some number
- tok = st.nextToken();
- }
- // Now tok should be the device name.
- if (Character.isDigit(tok.charAt(tok.length()-1))) {
- // If the last char is a digit
- // skip this line since it is a partition of a device; not a device.
- continue;
- }
- }
- long tmp_readsCompleted = st.nextTokenAsLong();
- long tmp_readsMerged = st.nextTokenAsLong();
- long tmp_sectorsRead = st.nextTokenAsLong();
- long tmp_timeReading = st.nextTokenAsLong();
- if (st.hasMoreTokens()) {
- // If we are on 2.6 then we might only have 4 longs; if so ignore this line
- // Otherwise we should have 11 long tokens.
- long tmp_writesCompleted = st.nextTokenAsLong();
- long tmp_writesMerged = st.nextTokenAsLong();
- long tmp_sectorsWritten = st.nextTokenAsLong();
- long tmp_timeWriting = st.nextTokenAsLong();
- long tmp_iosInProgress = st.nextTokenAsLong();
- long tmp_timeIosInProgress = st.nextTokenAsLong();
- long tmp_ioTime = st.nextTokenAsLong();
- readsCompleted += tmp_readsCompleted;
- readsMerged += tmp_readsMerged;
- sectorsRead += tmp_sectorsRead;
- timeReading += tmp_timeReading;
- writesCompleted += tmp_writesCompleted;
- writesMerged += tmp_writesMerged;
- sectorsWritten += tmp_sectorsWritten;
- timeWriting += tmp_timeWriting;
- iosInProgress += tmp_iosInProgress;
- timeIosInProgress += tmp_timeIosInProgress;
- ioTime += tmp_ioTime;
- }
- } // while
- final int SECTOR_SIZE = 512;
- longs[LinuxSystemStats.readsCompletedLONG] = readsCompleted;
- longs[LinuxSystemStats.readsMergedLONG] = readsMerged;
- longs[LinuxSystemStats.bytesReadLONG] = sectorsRead * SECTOR_SIZE;
- longs[LinuxSystemStats.timeReadingLONG] = timeReading;
- longs[LinuxSystemStats.writesCompletedLONG] = writesCompleted;
- longs[LinuxSystemStats.writesMergedLONG] = writesMerged;
- longs[LinuxSystemStats.bytesWrittenLONG] = sectorsWritten * SECTOR_SIZE;
- longs[LinuxSystemStats.timeWritingLONG] = timeWriting;
- longs[LinuxSystemStats.iosInProgressLONG] = iosInProgress;
- longs[LinuxSystemStats.timeIosInProgressLONG] = timeIosInProgress;
- longs[LinuxSystemStats.ioTimeLONG] = ioTime;
- } catch (NoSuchElementException nsee) {
-// com.gemstone.gemfire.distributed.internal.InternalDistributedSystem.getAnyInstance().getLoggerI18n().fine("unexpected NoSuchElementException line=" + line, nsee);
- } catch (IOException ioe) {
- } finally {
- st.releaseResources();
- if(br != null) try { br.close(); } catch(IOException ignore) {}
- }
- }
-
- //Example of /proc/vmstat
- //...
- //pgpgin 294333738
- //pgpgout 1057420300
- //pswpin 19422
- //pswpout 14495
- private static void getVmStats(long[] longs) {
- assert hasProcVmStat != false : "getVmStats called when hasVmStat was false";
- InputStreamReader isr = null;
- BufferedReader br = null;
- try {
- isr = new InputStreamReader( new FileInputStream( "/proc/vmstat" ));
- br = new BufferedReader(isr);
- String line = null;
- while((line = br.readLine()) != null) {
- if(line.startsWith(PGPGIN)) {
- longs[LinuxSystemStats.pagesPagedInLONG]
- = SpaceTokenizer.parseAsLong(line.substring(PGPGIN.length()));
- } else if(line.startsWith(PGPGOUT)) {
- longs[LinuxSystemStats.pagesPagedOutLONG]
- = SpaceTokenizer.parseAsLong(line.substring(PGPGOUT.length()));
- } else if(line.startsWith(PSWPIN)) {
- longs[LinuxSystemStats.pagesSwappedInLONG]
- = SpaceTokenizer.parseAsLong(line.substring(PSWPIN.length()));
- } else if(line.startsWith(PSWPOUT)) {
- longs[LinuxSystemStats.pagesSwappedOutLONG]
- = SpaceTokenizer.parseAsLong(line.substring(PSWPOUT.length()));
- }
- }
- } catch (NoSuchElementException nsee) {
- } catch (IOException ioe) {
- } finally {
- if(br != null) try { br.close(); } catch(IOException ignore) {}
- }
- }
-
- /**
- * Count the number of files in /proc that do not represent processes.
- * This value is cached to make counting the number of running process a
- * cheap operation. The assumption is that the contents of /proc will not
- * change on a running system.
- * @return the files in /proc that do NOT match /proc/[0-9]*
- */
- private static int getNumberOfNonProcessProcFiles() {
- File proc = new File("/proc");
- String[] procFiles = proc.list();
- int count = 0;
- if(procFiles != null) {
- for(String filename : procFiles) {
- char c = filename.charAt(0);
- if(! Character.isDigit(c)) {
- if (c == '.') {
- // see if the next char is a digit
- if (filename.length() > 1) {
- char c2 = filename.charAt(1);
- if (Character.isDigit(c2)) {
- // for bug 42091 do not count files that begin with a '.' followed by digits
- continue;
- }
- }
- }
- count++;
- }
- }
- }
- return count;
- }
-
- /**
- * @return the number of running processes on the system
- */
- private static int getProcessCount() {
- File proc = new File("/proc");
- String[] procFiles = proc.list();
- if(procFiles == null) {
- //unknown error, continue without this stat
- return 0;
- }
- return procFiles.length - nonPidFilesInProc;
- }
-
- //The array indices must be ordered as they appear in /proc/stats
- // (user) (nice) (system) (idle) (iowait) (irq) (softirq)
- // cpu 42813766 10844 8889075 1450764512 49963779 808244 3084872
- //
- private static class CpuStat {
- private static boolean lastCpuStatsInvalid;
- private static List<Long> lastCpuStats;
-
- public CpuStat() {
- lastCpuStatsInvalid = true;
- }
-
- public int[] calculateStats( String newStatLine ) {
- st.setString(newStatLine);
- st.skipToken(); //cpu name
- final int MAX_CPU_STATS = CPU.values().length;
- /* newer kernels now have 8 columns for cpu in
- * /proc/stat (up from 7). This number may increase
- * even further, hence we now use List in place of long[].
- * We add up entries from all columns after 7 into CPU.OTHER
- */
- List<Long> newStats = new ArrayList<Long>(8);
- List<Long> diffs = new ArrayList<Long>(8);
- long total_change = 0;
- int actualCpuStats = 0;
- long unaccountedCpuUtilization = 0;
-
- while (st.hasMoreTokens()) {
- newStats.add(st.nextTokenAsLong());
- actualCpuStats++;
- }
-
- if ( lastCpuStatsInvalid ) {
- lastCpuStats = newStats;
- lastCpuStatsInvalid = false;
- for (int i=0; i<MAX_CPU_STATS; i++) {
- diffs.add(0L);
- }
- diffs.set(CPU.IDLE.ordinal(), 100L);
- } else {
- for (int i=0; i<actualCpuStats; i++) {
- diffs.add(newStats.get(i) - lastCpuStats.get(i));
- total_change += diffs.get(i);
- lastCpuStats.set(i, newStats.get(i));
- }
- if(total_change == 0) {
- //avoid divide by zero
- total_change = 1;
- }
- for (int i = 0; i < MAX_CPU_STATS; i++) {
- if (i < actualCpuStats) {
- diffs.set(i, (diffs.get(i) * 100) / total_change);
- }
- }
- for (int i=MAX_CPU_STATS; i<actualCpuStats; i++) {
- unaccountedCpuUtilization += (diffs.get(i) * 100) / total_change;
- }
- }
- int[] ret = new int[MAX_CPU_STATS];
- for (int i = 0; i < MAX_CPU_STATS; i++) {
- if (i < actualCpuStats) {
- ret[i] = diffs.get(i).intValue();
- }
- }
- ret[CPU.OTHER.ordinal()] += (int)unaccountedCpuUtilization;
- return ret;
- }
- }
-
- private static class SpaceTokenizer {
- private String str;
- private char[] rawChars;
- private int beginIdx;
- private int endIdx;
- private int nextIdx;
-
- protected SpaceTokenizer() {
- endIdx = -1;
- nextIdx = -1;
- }
-
- protected void releaseResources() {
- str = null;
- rawChars = null;
- endIdx = -1;
- nextIdx = -1;
- }
-
- private void nextIdx() {
- int origin = nextIdx;
- if(endIdx == rawChars.length || beginIdx == -1) {
- endIdx = -1;
- nextIdx = -1;
- return;
- }
- endIdx = -1;
- nextIdx = -1;
- for(int i = origin+1; i < rawChars.length; i++) {
- char c = rawChars[i];
- //Add all delimiters here
- if(c == ' ' || c == '\t' || c == '\n' || c == '\r') {
- if(endIdx == -1) {
- endIdx = i;
- }
- } else {
- //this handles multiple consecutive delimiters
- if(endIdx != -1) {
- nextIdx = i;
- return;
- }
- }
- }
- if( endIdx == -1 ) {
- //indicates we were still reading white space at the end of the string
- endIdx = rawChars.length;
- }
- }
-
- protected boolean hasMoreTokens() {
- return endIdx != -1;
- }
-
- protected void setString(String data) {
- str = data;
- rawChars = new char[str.length()];
- str.getChars(0, str.length(), rawChars, 0);
- beginIdx = 0;
- endIdx = -1;
- nextIdx = -1;
- nextIdx();
- }
-
- protected boolean skipToken() {
- if(hasMoreTokens()) {
- beginIdx = nextIdx;
- nextIdx();
- return true;
- }
- return false;
- }
-
- protected String nextToken() {
- if(hasMoreTokens()) {
- final String ret = str.substring(beginIdx, endIdx);
- beginIdx = nextIdx;
- nextIdx();
- return ret;
- }
- throw new NoSuchElementException();
- }
-
- protected String peekToken() {
- if(hasMoreTokens()) {
- return str.substring(beginIdx, endIdx);
- }
- throw new NoSuchElementException();
- }
-
- protected void skipTokens(int numberToSkip) {
- int remaining = numberToSkip + 1;
- while (--remaining > 0 && skipToken());
- }
-
- protected static long parseAsLong(String number) {
- long l = 0L;
- try {
- l = Long.parseLong(number);
- } catch(NumberFormatException nfe) {}
- return l;
- }
-
- protected static int parseAsInt(String number) {
- int i = 0;
- try {
- i = Integer.parseInt(number);
- } catch(NumberFormatException nfe) {}
- return i;
- }
-
- protected int nextTokenAsInt() {
- int i = 0;
- try {
- i = Integer.parseInt(nextToken());
- } catch(NumberFormatException nfe) {}
- return i;
- }
-
- protected long nextTokenAsLong() {
- long l = 0L;
- try {
- l = Long.parseLong(nextToken());
- } catch(NumberFormatException nfe) {}
- return l;
- }
-
- protected double nextTokenAsDouble() {
- double d = 0;
- try {
- d = Double.parseDouble(nextToken());
- } catch(NumberFormatException nfe) {}
- return d;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxProcessStats.java
deleted file mode 100644
index 05bc284..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxProcessStats.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * <P>This class provides the interface for statistics about a
- * Linux operating system process that is using a GemFire system.
- */
-public class LinuxProcessStats
-{
- final static int imageSizeINT = 0;
- final static int rssSizeINT = 1;
-
- private final static StatisticsType myType;
-
- private static void checkOffset(String name, int offset) {
- int id = myType.nameToId(name);
- Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
- }
-
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- myType = f.createType("LinuxProcessStats",
- "Statistics on a Linux process.",
- new StatisticDescriptor[] {
- f.createIntGauge("imageSize",
- "The size of the process's image in megabytes.",
- "megabytes"),
- f.createIntGauge("rssSize",
- "The size of the process's resident set size in megabytes. (assumes PAGESIZE=4096, specify -Dgemfire.statistics.linux.pageSize=<pagesize> to adjust)",
- "megabytes"),
- });
- checkOffset("imageSize", imageSizeINT);
- checkOffset("rssSize", rssSizeINT);
- }
-
- private LinuxProcessStats() {
- // no instances allowed
- }
- public static StatisticsType getType() {
- return myType;
- }
-
- /**
- * Returns a <code>ProcessStats</code> that wraps Linux process
- * <code>Statistics</code>.
- *
- * @since GemFire 3.5
- */
- static ProcessStats createProcessStats(final Statistics stats) {
- if (stats instanceof LocalStatisticsImpl) {
- HostStatHelper.refresh((LocalStatisticsImpl) stats);
- } // otherwise its a Dummy implementation so do nothing
- return new ProcessStats(stats) {
- @Override
- public long getProcessSize() {
- return stats.getInt(rssSizeINT);
- }
- };
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxSystemStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxSystemStats.java
deleted file mode 100644
index 22158da..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/LinuxSystemStats.java
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * <P>This class provides the interface for statistics about the
- * Linux machine a GemFire system is running on.
- */
-public class LinuxSystemStats
-{
-
- // shared fields
- final static int allocatedSwapINT = 0;
- final static int bufferMemoryINT = 1;
- final static int sharedMemoryINT = 2;
- final static int cpuActiveINT = 3;
- final static int cpuIdleINT = 4;
- final static int cpuNiceINT = 5;
- final static int cpuSystemINT = 6;
- final static int cpuUserINT = 7;
- final static int iowaitINT = 8;
- final static int irqINT = 9;
- final static int softirqINT = 10;
- final static int cpusINT = 11;
- final static int freeMemoryINT = 12;
- final static int physicalMemoryINT = 13;
- final static int processesINT = 14;
- final static int unallocatedSwapINT = 15;
- final static int cachedMemoryINT = 16;
- final static int dirtyMemoryINT = 17;
- final static int cpuNonUserINT = 18;
-
- final static int loopbackPacketsLONG = 0;
- final static int loopbackBytesLONG = 1;
- final static int recvPacketsLONG = 2;
- final static int recvBytesLONG = 3;
- final static int recvErrorsLONG = 4;
- final static int recvDropsLONG = 5;
- final static int xmitPacketsLONG = 6;
- final static int xmitBytesLONG = 7;
- final static int xmitErrorsLONG = 8;
- final static int xmitDropsLONG = 9;
- final static int xmitCollisionsLONG = 10;
- final static int contextSwitchesLONG = 11;
- final static int processCreatesLONG = 12;
- final static int pagesPagedInLONG = 13;
- final static int pagesPagedOutLONG = 14;
- final static int pagesSwappedInLONG = 15;
- final static int pagesSwappedOutLONG = 16;
- final static int readsCompletedLONG = 17;
- final static int readsMergedLONG = 18;
- final static int bytesReadLONG = 19;
- final static int timeReadingLONG = 20;
- final static int writesCompletedLONG = 21;
- final static int writesMergedLONG = 22;
- final static int bytesWrittenLONG = 23;
- final static int timeWritingLONG = 24;
- final static int iosInProgressLONG = 25;
- final static int timeIosInProgressLONG = 26;
- final static int ioTimeLONG = 27;
-
- final static int loadAverage1DOUBLE = 0;
- final static int loadAverage15DOUBLE = 1;
- final static int loadAverage5DOUBLE = 2;
-
- private final static StatisticsType myType;
-
- private static void checkOffset(String name, int offset) {
- int id = myType.nameToId(name);
- Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
- }
-
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- myType = f.createType("LinuxSystemStats",
- "Statistics on a Linux machine.",
- new StatisticDescriptor[] {
- f.createIntGauge("allocatedSwap",
- "The number of megabytes of swap space have actually been written to. Swap space must be reserved before it can be allocated.",
- "megabytes"),
- f.createIntGauge("bufferMemory",
- "The number of megabytes of memory allocated to buffers.",
- "megabytes"),
- f.createIntGauge("sharedMemory",
- "The number of megabytes of shared memory on the machine.",
- "megabytes", true),
- f.createIntGauge("cpuActive",
- "The percentage of the total available time that has been used in a non-idle state.",
- "%"),
- f.createIntGauge("cpuIdle",
- "The percentage of the total available time that has been spent sleeping.",
- "%", true),
- f.createIntGauge("cpuNice",
- "The percentage of the total available time that has been used to execute user code in processes with low priority.",
- "%"),
- f.createIntGauge("cpuSystem",
- "The percentage of the total available time that has been used to execute system (i.e. kernel) code.",
- "%"),
- f.createIntGauge("cpuUser",
- "The percentage of the total available time that has been used to execute user code.",
- "%"),
- f.createIntGauge("iowait",
- "The percentage of the total available time that has been used to wait for I/O to complete.",
- "%"),
- f.createIntGauge("irq",
- "The percentage of the total available time that has been used servicing interrupts.",
- "%"),
- f.createIntGauge("softirq",
- "The percentage of the total available time that has been used servicing softirqs.",
- "%"),
- f.createIntGauge("cpus",
- "The number of online cpus on the local machine.",
- "items"),
- f.createIntGauge("freeMemory",
- "The number of megabytes of unused memory on the machine.",
- "megabytes", true),
- f.createIntGauge("physicalMemory",
- "The actual amount of total physical memory on the machine.",
- "megabytes", true),
- f.createIntGauge("processes",
- "The number of processes in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Each process represents the running of a program.",
- "processes"),
- f.createIntGauge("unallocatedSwap",
- "The number of megabytes of swap space that have not been allocated.",
- "megabytes", true),
- f.createIntGauge("cachedMemory",
- "The number of megabytes of memory used for the file system cache.",
- "megabytes", true),
- f.createIntGauge("dirtyMemory",
- "The number of megabytes of memory in the file system cache that need to be written.",
- "megabytes", true),
- f.createIntGauge("cpuNonUser",
- "The percentage of total available time that has been used to execute non-user code.(includes system, iowait, irq, softirq etc.)",
- "%"),
-
-
- f.createLongCounter("loopbackPackets",
- "The number of network packets sent (or received) on the loopback interface",
- "packets", false),
- f.createLongCounter("loopbackBytes",
- "The number of network bytes sent (or received) on the loopback interface",
- "bytes", false),
- f.createLongCounter("recvPackets",
- "The total number of network packets received (excluding loopback)",
- "packets", false),
- f.createLongCounter("recvBytes",
- "The total number of network bytes received (excluding loopback)",
- "bytes", false),
- f.createLongCounter("recvErrors",
- "The total number of network receive errors",
- "errors", false),
- f.createLongCounter("recvDrops",
- "The total number network receives dropped",
- "packets", false),
- f.createLongCounter("xmitPackets",
- "The total number of network packets transmitted (excluding loopback)",
- "packets", false),
- f.createLongCounter("xmitBytes",
- "The total number of network bytes transmitted (excluding loopback)",
- "bytes", false),
- f.createLongCounter("xmitErrors",
- "The total number of network transmit errors",
- "errors", false),
- f.createLongCounter("xmitDrops",
- "The total number of network transmits dropped",
- "packets", false),
- f.createLongCounter("xmitCollisions",
- "The total number of network transmit collisions",
- "collisions", false),
- f.createLongCounter("contextSwitches",
- "The total number of context switches from one thread to another on the computer. Thread switches can occur either inside of a single process or across processes. A thread switch may be caused either by one thread asking another for information, or by a thread being preempted by another, higher priority thread becoming ready to run.",
- "operations", false),
- f.createLongCounter("processCreates",
- "The total number of times a process has been created.",
- "operations", false),
- f.createLongCounter("pagesPagedIn",
- "The total number of pages that have been brought into memory from disk by the operating system's memory manager.",
- "pages", false),
- f.createLongCounter("pagesPagedOut",
- "The total number of pages that have been flushed from memory to disk by the operating system's memory manager.",
- "pages", false),
- f.createLongCounter("pagesSwappedIn",
- "The total number of swap pages that have been read in from disk by the operating system's memory manager.",
- "pages", false),
- f.createLongCounter("pagesSwappedOut",
- "The total number of swap pages that have been written out to disk by the operating system's memory manager.",
- "pages", false),
- f.createLongCounter("diskReadsCompleted",
- "The total number disk read operations completed successfully",
- "ops"),
- f.createLongCounter("diskReadsMerged",
- "The total number disk read operations that were able to be merge with adjacent reads for efficiency",
- "ops"),
- f.createLongCounter("diskBytesRead",
- "The total number bytes read from disk successfully",
- "bytes"),
- f.createLongCounter("diskTimeReading",
- "The total number of milliseconds spent reading from disk",
- "milliseconds"),
- f.createLongCounter("diskWritesCompleted",
- "The total number disk write operations completed successfully",
- "ops"),
- f.createLongCounter("diskWritesMerged",
- "The total number disk write operations that were able to be merge with adjacent reads for efficiency",
- "ops"),
- f.createLongCounter("diskBytesWritten",
- "The total number bytes written to disk successfully",
- "bytes"),
- f.createLongCounter("diskTimeWriting",
- "The total number of milliseconds spent writing to disk",
- "milliseconds"),
- f.createLongGauge("diskOpsInProgress",
- "The current number of disk operations in progress",
- "ops"),
- f.createLongCounter("diskTimeInProgress",
- "The total number of milliseconds spent with disk ops in progress",
- "milliseconds"),
- f.createLongCounter("diskTime",
- "The total number of milliseconds that measures both completed disk operations and any accumulating backlog of in progress ops.",
- "milliseconds"),
-
-
- f.createDoubleGauge("loadAverage1",
- "The average number of threads in the run queue or waiting for disk I/O over the last minute.",
- "threads"),
- f.createDoubleGauge("loadAverage15",
- "The average number of threads in the run queue or waiting for disk I/O over the last fifteen minutes.",
- "threads"),
- f.createDoubleGauge("loadAverage5",
- "The average number of threads in the run queue or waiting for disk I/O over the last five minutes.",
- "threads"),
- });
-
- checkOffset("allocatedSwap", allocatedSwapINT);
- checkOffset("bufferMemory", bufferMemoryINT);
- checkOffset("sharedMemory", sharedMemoryINT);
- checkOffset("cpuActive", cpuActiveINT);
- checkOffset("cpuIdle", cpuIdleINT);
- checkOffset("cpuNice", cpuNiceINT);
- checkOffset("cpuSystem", cpuSystemINT);
- checkOffset("cpuUser", cpuUserINT);
- checkOffset("iowait", iowaitINT);
- checkOffset("irq", irqINT);
- checkOffset("softirq", softirqINT);
- checkOffset("cpus", cpusINT);
- checkOffset("freeMemory", freeMemoryINT);
- checkOffset("physicalMemory", physicalMemoryINT);
- checkOffset("processes", processesINT);
- checkOffset("unallocatedSwap", unallocatedSwapINT);
- checkOffset("cachedMemory", cachedMemoryINT);
- checkOffset("dirtyMemory", dirtyMemoryINT);
- checkOffset("cpuNonUser", cpuNonUserINT);
-
- checkOffset("loopbackPackets", loopbackPacketsLONG);
- checkOffset("loopbackBytes", loopbackBytesLONG);
- checkOffset("recvPackets", recvPacketsLONG);
- checkOffset("recvBytes", recvBytesLONG);
- checkOffset("recvErrors", recvErrorsLONG);
- checkOffset("recvDrops", recvDropsLONG);
- checkOffset("xmitPackets", xmitPacketsLONG);
- checkOffset("xmitBytes", xmitBytesLONG);
- checkOffset("xmitErrors", xmitErrorsLONG);
- checkOffset("xmitDrops", xmitDropsLONG);
- checkOffset("xmitCollisions", xmitCollisionsLONG);
- checkOffset("contextSwitches", contextSwitchesLONG);
- checkOffset("processCreates", processCreatesLONG);
- checkOffset("pagesPagedIn", pagesPagedInLONG);
- checkOffset("pagesPagedOut", pagesPagedOutLONG);
- checkOffset("pagesSwappedIn", pagesSwappedInLONG);
- checkOffset("pagesSwappedOut", pagesSwappedOutLONG);
- checkOffset("diskReadsCompleted", readsCompletedLONG);
- checkOffset("diskReadsMerged", readsMergedLONG);
- checkOffset("diskBytesRead", bytesReadLONG);
- checkOffset("diskTimeReading", timeReadingLONG);
- checkOffset("diskWritesCompleted", writesCompletedLONG);
- checkOffset("diskWritesMerged", writesMergedLONG);
- checkOffset("diskBytesWritten", bytesWrittenLONG);
- checkOffset("diskTimeWriting", timeWritingLONG);
- checkOffset("diskOpsInProgress", iosInProgressLONG);
- checkOffset("diskTimeInProgress", timeIosInProgressLONG);
- checkOffset("diskTime", ioTimeLONG);
-
- checkOffset("loadAverage1", loadAverage1DOUBLE);
- checkOffset("loadAverage15", loadAverage15DOUBLE);
- checkOffset("loadAverage5", loadAverage5DOUBLE);
- }
-
- private LinuxSystemStats() {
- // no instances allowed
- }
- public static StatisticsType getType() {
- return myType;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatListener.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatListener.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatListener.java
deleted file mode 100644
index c46bc2f..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/LocalStatListener.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-/**
- * Implement this interface to receive call back when a stat value has changed.
- * The listener has to be registered with statSampler. This can be done in the
- * following manner:
- * <code>
- * InternalDistributedSystem internalSystem = (InternalDistributedSystem)cache
- * .getDistributedSystem();
- * final GemFireStatSampler sampler = internalSystem.getStatSampler();
- * sampler.addLocalStatListener(l, stats, statName);
- * </code>
- *
- *
- */
-public interface LocalStatListener {
- /**
- * Invoked when the value of a statistic has changed
- *
- * @param value
- * The new value of the statistic
- */
- public void statValueChanged( double value );
-}
[04/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatSamplerIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatSamplerIntegrationTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatSamplerIntegrationTest.java
new file mode 100755
index 0000000..1742b69
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatSamplerIntegrationTest.java
@@ -0,0 +1,363 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static com.jayway.awaitility.Awaitility.*;
+import static java.util.concurrent.TimeUnit.*;
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.logging.log4j.Logger;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.contrib.java.lang.system.RestoreSystemProperties;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestName;
+
+import com.gemstone.gemfire.CancelCriterion;
+import com.gemstone.gemfire.StatisticDescriptor;
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatValue;
+import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
+
+/**
+ * Integration tests for statistics sampling.
+ *
+ * @since GemFire 7.0
+ */
+@Category(IntegrationTest.class)
+public class StatSamplerIntegrationTest {
+
+ private static final Logger logger = LogService.getLogger();
+
+ private Map<String,String> statisticTypes;
+ private Map<String,Map<String,Number>> allStatistics;
+
+ @Rule
+ public RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
+
+ @Rule
+ public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+ @Rule
+ public TestName testName = new TestName();
+
+ @Before
+ public void setUp() {
+ this.statisticTypes = new HashMap<String,String>();
+ this.allStatistics = new HashMap<String,Map<String,Number>>();
+ }
+
+ @After
+ public void tearDown() {
+ this.statisticTypes = null;
+ this.allStatistics = null;
+ StatisticsTypeFactoryImpl.clear();
+ StatArchiveWriter.clearTraceFilter();
+ }
+
+ private String getName() {
+ return getClass().getSimpleName() + "_" + testName.getMethodName();
+ }
+
+ @Test
+ public void testStatSampler() throws Exception {
+ StatArchiveWriter.setTraceFilter("st1_1", "ST1");
+
+ File folder = temporaryFolder.newFolder();
+ String archiveFileName = folder.getAbsolutePath() + File.separator + getName() + ".gfs";
+
+ System.setProperty("stats.log-level", "config");
+ System.setProperty("stats.disable", "false");
+ System.setProperty("stats.name", getName());
+ System.setProperty("stats.archive-file", archiveFileName);
+ System.setProperty("stats.file-size-limit", "0");
+ System.setProperty("stats.disk-space-limit", "0");
+ System.setProperty("stats.sample-rate", "100");
+
+ final CancelCriterion stopper = new CancelCriterion() {
+ public String cancelInProgress() {
+ return null;
+ }
+ public RuntimeException generateCancelledException(Throwable e) {
+ return null;
+ }
+ };
+ final LocalStatisticsFactory factory = new LocalStatisticsFactory(stopper);
+ final StatisticDescriptor[] statsST1 = new StatisticDescriptor[] {
+ factory.createDoubleCounter("double_counter_1", "d1", "u1"),
+ factory.createDoubleCounter("double_counter_2", "d2", "u2", true),
+ factory.createDoubleGauge( "double_gauge_3", "d3", "u3"),
+ factory.createDoubleGauge( "double_gauge_4", "d4", "u4", false),
+ factory.createIntCounter( "int_counter_5", "d5", "u5"),
+ factory.createIntCounter( "int_counter_6", "d6", "u6", true),
+ factory.createIntGauge( "int_gauge_7", "d7", "u7"),
+ factory.createIntGauge( "int_gauge_8", "d8", "u8", false),
+ factory.createLongCounter( "long_counter_9", "d9", "u9"),
+ factory.createLongCounter( "long_counter_10", "d10", "u10", true),
+ factory.createLongGauge( "long_gauge_11", "d11", "u11"),
+ factory.createLongGauge( "long_gauge_12", "d12", "u12", false),
+ factory.createLongGauge( "sampled_long", "d13", "u13", false),
+ factory.createIntGauge( "sampled_int", "d14", "u14", false),
+ factory.createDoubleGauge( "sampled_double", "d15", "u15", false)
+ };
+ final StatisticsType ST1 = factory.createType("ST1", "ST1", statsST1);
+ final Statistics st1_1 = factory.createAtomicStatistics(ST1, "st1_1", 1);
+ st1_1.setIntSupplier("sampled_int", () -> 5);
+ getOrCreateExpectedValueMap(st1_1).put("sampled_int", 5);
+ st1_1.setLongSupplier("sampled_long", () -> 6);
+ getOrCreateExpectedValueMap(st1_1).put("sampled_long", 6);
+ st1_1.setDoubleSupplier("sampled_double", () -> 7.0);
+ getOrCreateExpectedValueMap(st1_1).put("sampled_double", 7.0);
+
+ await("awaiting StatSampler readiness").atMost(30, SECONDS).until(() -> hasSamplerStatsInstances(factory));
+
+ Statistics[] samplerStatsInstances = factory.findStatisticsByTextId("statSampler");
+ assertNotNull(samplerStatsInstances);
+ assertEquals(1, samplerStatsInstances.length);
+ final Statistics samplerStats = samplerStatsInstances[0];
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_gauge_3", 3);
+ incInt(st1_1, "int_counter_5", 5);
+ incInt(st1_1, "int_gauge_7", 7);
+ incLong(st1_1, "long_counter_9", 9);
+ incLong(st1_1, "long_gauge_11", 11);
+
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_counter_2", 1);
+ incDouble(st1_1, "double_gauge_3", 1);
+ incDouble(st1_1, "double_gauge_4", 1);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 1);
+
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_counter_2", 1);
+ incDouble(st1_1, "double_gauge_3", 1);
+ incDouble(st1_1, "double_gauge_4", 1);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 1);
+ incInt(st1_1, "int_gauge_7", 1);
+ incInt(st1_1, "int_gauge_8", 1);
+ incLong(st1_1, "long_counter_9", 1);
+ incLong(st1_1, "long_counter_10", 1);
+ incLong(st1_1, "long_gauge_11", 1);
+ incLong(st1_1, "long_gauge_12", 1);
+
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_counter_2", 1);
+ incDouble(st1_1, "double_gauge_3", -1);
+ incDouble(st1_1, "double_gauge_4", 1);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 1);
+ incInt(st1_1, "int_gauge_7", -1);
+ incInt(st1_1, "int_gauge_8", 1);
+ incLong(st1_1, "long_counter_9", 1);
+ incLong(st1_1, "long_counter_10", 1);
+ incLong(st1_1, "long_gauge_11", -1);
+ incLong(st1_1, "long_gauge_12", 1);
+
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_counter_2", 1);
+ incDouble(st1_1, "double_gauge_3", 1);
+ incDouble(st1_1, "double_gauge_4", 1);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 1);
+ incInt(st1_1, "int_gauge_7", 1);
+ incInt(st1_1, "int_gauge_8", 1);
+ incLong(st1_1, "long_counter_9", 1);
+ incLong(st1_1, "long_counter_10", 1);
+ incLong(st1_1, "long_gauge_11", 1);
+ incLong(st1_1, "long_gauge_12", 1);
+
+ awaitStatSample(samplerStats);
+ awaitStatSample(samplerStats);
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_gauge_3", 3);
+ incInt(st1_1, "int_counter_5", 5);
+ incInt(st1_1, "int_gauge_7", 7);
+ incLong(st1_1, "long_counter_9", 9);
+ incLong(st1_1, "long_gauge_11", 11);
+
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_counter_2", 1);
+ incDouble(st1_1, "double_gauge_3", 1);
+ incDouble(st1_1, "double_gauge_4", 1);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 1);
+
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_counter_2", 1);
+ incDouble(st1_1, "double_gauge_3", 1);
+ incDouble(st1_1, "double_gauge_4", 1);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 1);
+ incInt(st1_1, "int_gauge_7", 1);
+ incInt(st1_1, "int_gauge_8", 1);
+ incLong(st1_1, "long_counter_9", 1);
+ incLong(st1_1, "long_counter_10", 1);
+ incLong(st1_1, "long_gauge_11", 1);
+ incLong(st1_1, "long_gauge_12", 1);
+
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_counter_2", 1);
+ incDouble(st1_1, "double_gauge_3", -1);
+ incDouble(st1_1, "double_gauge_4", 1);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 1);
+ incInt(st1_1, "int_gauge_7", -1);
+ incInt(st1_1, "int_gauge_8", 1);
+ incLong(st1_1, "long_counter_9", 1);
+ incLong(st1_1, "long_counter_10", 1);
+ incLong(st1_1, "long_gauge_11", -1);
+ incLong(st1_1, "long_gauge_12", 1);
+
+ awaitStatSample(samplerStats);
+
+ incDouble(st1_1, "double_counter_1", 1);
+ incDouble(st1_1, "double_counter_2", 1);
+ incDouble(st1_1, "double_gauge_3", 1);
+ incDouble(st1_1, "double_gauge_4", 1);
+ incInt(st1_1, "int_counter_5", 1);
+ incInt(st1_1, "int_counter_6", 1);
+ incInt(st1_1, "int_gauge_7", 1);
+ incInt(st1_1, "int_gauge_8", 1);
+ incLong(st1_1, "long_counter_9", 1);
+ incLong(st1_1, "long_counter_10", 1);
+ incLong(st1_1, "long_gauge_11", 1);
+ incLong(st1_1, "long_gauge_12", 1);
+
+ awaitStatSample(samplerStats);
+
+ factory.close();
+
+ final File archiveFile = new File(System.getProperty("stats.archive-file"));
+ assertTrue(archiveFile.exists());
+ final StatArchiveReader reader = new StatArchiveReader(
+ new File[]{archiveFile}, null, false);
+
+ List resources = reader.getResourceInstList();
+ for (Iterator iter = resources.iterator(); iter.hasNext();) {
+ StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
+ String resourceName = ri.getName();
+ assertNotNull(resourceName);
+
+ if (!resourceName.equals("st1_1")) {
+ logger.info("testStatSampler skipping {}", resourceName);
+ continue;
+ }
+
+ String expectedStatsType = this.statisticTypes.get(resourceName);
+ assertNotNull(expectedStatsType);
+ assertEquals(expectedStatsType, ri.getType().getName());
+
+ Map<String,Number> expectedStatValues = this.allStatistics.get(resourceName);
+ assertNotNull(expectedStatValues);
+
+ StatValue[] statValues = ri.getStatValues();
+ for (int i = 0; i < statValues.length; i++) {
+ String statName = ri.getType().getStats()[i].getName();
+ assertNotNull(statName);
+ assertNotNull(expectedStatValues.get(statName));
+
+ assertEquals(statName, statValues[i].getDescriptor().getName());
+
+ statValues[i].setFilter(StatValue.FILTER_NONE);
+ //double[] rawSnapshots = statValues[i].getRawSnapshots();
+ assertEquals("Value " + i + " for " + statName + " is wrong: " + expectedStatValues,
+ expectedStatValues.get(statName).doubleValue(),
+ statValues[i].getSnapshotsMostRecent(),
+ 0);
+ }
+ }
+ }
+
+ private boolean hasSamplerStatsInstances(final LocalStatisticsFactory factory) {
+ Statistics[] samplerStatsInstances = factory.findStatisticsByTextId("statSampler");
+ return samplerStatsInstances != null && samplerStatsInstances.length > 0;
+ }
+
+ private void awaitStatSample(final Statistics samplerStats) throws InterruptedException {
+ int startSampleCount = samplerStats.getInt("sampleCount");
+ await("awaiting stat sample").atMost(30, SECONDS).until(() -> samplerStats.getInt("sampleCount") > startSampleCount);
+ }
+
+ private void incDouble(Statistics statistics, String stat, double value) {
+ assertFalse(statistics.isClosed());
+ Map<String, Number> statValues = getOrCreateExpectedValueMap(statistics);
+ statistics.incDouble(stat, value);
+ statValues.put(stat, statistics.getDouble(stat));
+ if (this.statisticTypes.get(statistics.getTextId()) == null) {
+ this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
+ }
+ }
+
+ private void incInt(Statistics statistics, String stat, int value) {
+ assertFalse(statistics.isClosed());
+ Map<String, Number> statValues = getOrCreateExpectedValueMap(statistics);
+ statistics.incInt(stat, value);
+ statValues.put(stat, statistics.getInt(stat));
+ if (this.statisticTypes.get(statistics.getTextId()) == null) {
+ this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
+ }
+ }
+
+ private Map<String, Number> getOrCreateExpectedValueMap(final Statistics statistics) {
+ Map<String,Number> statValues = this.allStatistics.get(statistics.getTextId());
+ if (statValues == null) {
+ statValues = new HashMap<String,Number>();
+ this.allStatistics.put(statistics.getTextId(), statValues);
+ }
+ return statValues;
+ }
+
+ private void incLong(Statistics statistics, String stat, long value) {
+ assertFalse(statistics.isClosed());
+ Map<String, Number> statValues = getOrCreateExpectedValueMap(statistics);
+ statistics.incLong(stat, value);
+ statValues.put(stat, statistics.getLong(stat));
+ if (this.statisticTypes.get(statistics.getTextId()) == null) {
+ this.statisticTypes.put(statistics.getTextId(), statistics.getType().getName());
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatSamplerTestCase.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatSamplerTestCase.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatSamplerTestCase.java
new file mode 100755
index 0000000..9b43dde
--- /dev/null
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatSamplerTestCase.java
@@ -0,0 +1,185 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.logging.log4j.Logger;
+
+import com.gemstone.gemfire.Statistics;
+import com.gemstone.gemfire.StatisticsType;
+import com.gemstone.gemfire.internal.logging.LogService;
+import com.gemstone.gemfire.internal.util.StopWatch;
+
+/**
+ * Integration TestCase for StatSampler.
+ *
+ * @since GemFire 7.0
+ */
+public abstract class StatSamplerTestCase {
+
+ protected static final Logger logger = LogService.getLogger();
+
+ protected abstract StatisticsManager getStatisticsManager();
+
+ protected int getStatListModCount() {
+ return getStatisticsManager().getStatListModCount();
+ }
+
+ protected List<Statistics> getStatsList() {
+ return getStatisticsManager().getStatsList();
+ }
+
+ protected static void waitForFileToExist(final File file, final long millis, final long sleep) {
+ boolean done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < millis; done = (file.exists())) {
+ Thread.sleep(sleep);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertTrue("Waiting for file to exist: " + file, done);
+ }
+
+ protected static void waitForFileToDelete(final File file, final long millis, final long sleep) {
+ boolean done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < millis; done = (!file.exists())) {
+ Thread.sleep(sleep);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertTrue("Waiting for file to be deleted: " + file, done);
+ }
+
+ protected static void waitForExpectedStatValue(final Statistics statSamplerStats, final String statName, final int expectedStatValue, final long millis, final long sleep) {
+ boolean done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < millis; done = (statSamplerStats.getInt(statName) >= expectedStatValue)) {
+ Thread.sleep(sleep);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertTrue("Waiting for " + statName + " >= " + expectedStatValue, done);
+ }
+
+ protected static void waitForStatSample(final Statistics statSamplerStats, final int samples, final long millis, final long sleep) {
+ waitForExpectedStatValue(statSamplerStats, "sampleCount", samples, millis, sleep);
+ }
+
+ protected static void assertStatValueDoesNotChange(final Statistics statSamplerStats, final String statName, final int expectedStatValue, final long millis, final long sleep) {
+ boolean done = false;
+ try {
+ for (StopWatch time = new StopWatch(true); !done && time.elapsedTimeMillis() < millis; done = (statSamplerStats.getInt(statName) != expectedStatValue)) {
+ Thread.sleep(sleep);
+ }
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ assertFalse("Waiting to assert that " + statName + " does not change from " + expectedStatValue, done);
+ }
+
+ protected static class AllStatistics {
+
+ private final HostStatSampler statSampler;
+ private final Map<StatisticsType, Set<Statistics>> allStatistics;
+
+ protected AllStatistics(HostStatSampler statSampler) throws InterruptedException {
+ this.statSampler = statSampler;
+ this.allStatistics = initAllStatistics();
+ }
+
+ private Map<StatisticsType, Set<Statistics>> initAllStatistics() throws InterruptedException {
+ assertTrue(this.statSampler.waitForInitialization(5000));
+
+ Map<StatisticsType, Set<Statistics>> statsTypeToStats = new HashMap<StatisticsType, Set<Statistics>>();
+ Statistics[] stats = this.statSampler.getStatistics();
+ for (int i = 0; i < stats.length; i++) {
+ StatisticsType statsType = stats[i].getType();
+ Set<Statistics> statsSet = statsTypeToStats.get(statsType);
+ if (statsSet == null) {
+ statsSet = new HashSet<Statistics>();
+ statsSet.add(stats[i]);
+ statsTypeToStats.put(statsType, statsSet);
+ } else {
+ statsSet.add(stats[i]);
+ }
+ }
+ return statsTypeToStats;
+ }
+
+ protected boolean containsStatisticsType(StatisticsType type) {
+ throw new UnsupportedOperationException("TODO");
+ }
+
+ protected boolean containsStatisticsType(String typeName) throws InterruptedException {
+ for (StatisticsType statType : this.allStatistics.keySet()) {
+ if (statType.getName().equals(typeName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected boolean containsStatistics(Statistics statistics) {
+ throw new UnsupportedOperationException("TODO");
+ }
+
+ protected boolean containsStatistics(String instanceName) throws InterruptedException {
+ for (StatisticsType statType : this.allStatistics.keySet()) {
+ for (Statistics statistics : this.allStatistics.get(statType)) {
+ if (statistics.getTextId().equals(instanceName)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Statistics[0]: typeName=StatSampler instanceName=statSampler
+ * Statistics[1]: typeName=VMStats instanceName=vmStats
+ * Statistics[2]: typeName=VMMemoryUsageStats instanceName=vmHeapMemoryStats
+ * Statistics[3]: typeName=VMMemoryUsageStats instanceName=vmNonHeapMemoryStats
+ * Statistics[4]: typeName=VMMemoryPoolStats instanceName=Code Cache-Non-heap memory
+ * Statistics[5]: typeName=VMMemoryPoolStats instanceName=PS Eden Space-Heap memory
+ * Statistics[6]: typeName=VMMemoryPoolStats instanceName=PS Survivor Space-Heap memory
+ * Statistics[7]: typeName=VMMemoryPoolStats instanceName=PS Old Gen-Heap memory
+ * Statistics[8]: typeName=VMMemoryPoolStats instanceName=PS Perm Gen-Non-heap memory
+ * Statistics[9]: typeName=VMGCStats instanceName=PS Scavenge
+ * Statistics[10]: typeName=VMGCStats instanceName=PS MarkSweep
+ * Statistics[11]: typeName=LinuxSystemStats instanceName=kuwait.gemstone.com
+ * Statistics[12]: typeName=LinuxProcessStats instanceName=javaApp0-proc
+ */
+ protected void dumpStatistics() throws InterruptedException {
+ Statistics[] stats = this.statSampler.getStatistics();
+ for (int i = 0; i < stats.length; i++) {
+ logger.info("Statistics[{}]: typeName={} instanceName={}", i, stats[i].getType().getName(), stats[i].getTextId());
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsDUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsDUnitTest.java
deleted file mode 100755
index 1e7a4e4..0000000
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/statistics/StatisticsDUnitTest.java
+++ /dev/null
@@ -1,947 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal.statistics;
-
-import static com.gemstone.gemfire.distributed.ConfigurationProperties.*;
-import static org.junit.Assert.*;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.util.Random;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.concurrent.atomic.AtomicReferenceArray;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import com.gemstone.gemfire.StatisticDescriptor;
-import com.gemstone.gemfire.Statistics;
-import com.gemstone.gemfire.StatisticsFactory;
-import com.gemstone.gemfire.StatisticsType;
-import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.cache.Cache;
-import com.gemstone.gemfire.cache.CacheException;
-import com.gemstone.gemfire.cache.CacheListener;
-import com.gemstone.gemfire.cache.EntryEvent;
-import com.gemstone.gemfire.cache.Region;
-import com.gemstone.gemfire.cache.RegionEvent;
-import com.gemstone.gemfire.cache.RegionFactory;
-import com.gemstone.gemfire.cache.Scope;
-import com.gemstone.gemfire.cache.util.CacheListenerAdapter;
-import com.gemstone.gemfire.cache.util.RegionMembershipListenerAdapter;
-import com.gemstone.gemfire.cache30.CacheSerializableRunnable;
-import com.gemstone.gemfire.distributed.DistributedMember;
-import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
-import com.gemstone.gemfire.internal.GemFireStatSampler;
-import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.internal.StatArchiveReader;
-import com.gemstone.gemfire.internal.StatArchiveReader.StatSpec;
-import com.gemstone.gemfire.internal.StatArchiveReader.StatValue;
-import com.gemstone.gemfire.internal.StatSamplerStats;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
-import com.gemstone.gemfire.test.dunit.Assert;
-import com.gemstone.gemfire.test.dunit.AsyncInvocation;
-import com.gemstone.gemfire.test.dunit.Host;
-import com.gemstone.gemfire.test.dunit.Invoke;
-import com.gemstone.gemfire.test.dunit.SerializableCallable;
-import com.gemstone.gemfire.test.dunit.VM;
-import com.gemstone.gemfire.test.dunit.Wait;
-import com.gemstone.gemfire.test.dunit.WaitCriterion;
-import com.gemstone.gemfire.test.dunit.cache.internal.JUnit4CacheTestCase;
-import com.gemstone.gemfire.test.junit.categories.DistributedTest;
-
-/**
- * Integration tests for Statistics. VM0 performs puts and VM1 receives
- * updates. Both use custom statistics for start/end with increment to
- * add up puts and updates. Then validation tests values in stat resource
- * instances and uses StatArchiveReader. Both are tested against static
- * counters in both VMs.
- * <p/>
- * This test mimics hydratest/locators/cacheDS.conf in an attempt to reproduce
- * bug #45478. So far this test passes consistently.
- *
- * @since GemFire 7.0
- */
-@SuppressWarnings("serial")
-@Category(DistributedTest.class)
-public class StatisticsDUnitTest extends JUnit4CacheTestCase {
-
- private static final String dir = "StatisticsDUnitTest";
-
- private static final int MAX_PUTS = 1000;
- private static final int NUM_KEYS = 100;
- private static final int NUM_PUB_THREADS = 2;
- private static final int NUM_PUBS = 2;
- private static final boolean RANDOMIZE_PUTS = true;
-
- private static AtomicInteger updateEvents = new AtomicInteger();
-
- private static AtomicInteger puts = new AtomicInteger();
-
- private static AtomicReference<PubSubStats> subStatsRef = new AtomicReference<PubSubStats>();
-
- private static AtomicReferenceArray<PubSubStats> pubStatsRef = new AtomicReferenceArray<PubSubStats>(NUM_PUB_THREADS);
-
- /** Thread-safe static reference to RegionMembershipListener instance */
- private static AtomicReference<RegionMembershipListener> rmlRef =
- new AtomicReference<RegionMembershipListener>();
-
- @SuppressWarnings("unused") /** invoked by reflection */
- private static void cleanup() {
- updateEvents.set(0);
- rmlRef.set(null);
- }
-
- @SuppressWarnings("unused") /** invoked by reflection */
- private static int getUpdateEvents() {
- return updateEvents.get();
- }
-
- @SuppressWarnings("unused") /** invoked by reflection */
- private static int getPuts() {
- return puts.get();
- }
-
- public StatisticsDUnitTest() {
- super();
- }
-
- @Override
- public final void preTearDownCacheTestCase() throws Exception {
- Invoke.invokeInEveryVM(getClass(), "cleanup");
- disconnectAllFromDS(); // because this test enabled stat sampling!
- }
-
- @Test
- public void testPubAndSubCustomStats() throws Exception {
- final String testName = "testPubAndSubCustomStats";
-
- final String regionName = "region_" + testName;
- final VM[] pubs = new VM[NUM_PUBS];
- for (int pubVM = 0; pubVM < NUM_PUBS; pubVM++) {
- pubs[pubVM] = Host.getHost(0).getVM(pubVM);
- }
- final VM sub = Host.getHost(0).getVM(NUM_PUBS);
-
- final String subArchive = dir + File.separator + testName + "_sub" + ".gfs";
- final String[] pubArchives = new String[NUM_PUBS];
- for (int pubVM = 0; pubVM < NUM_PUBS; pubVM++) {
- pubArchives[pubVM] = dir + File.separator + testName + "_pub-" + pubVM + ".gfs";
- }
-
- for (int i = 0; i < NUM_PUBS; i++) {
- final int pubVM = i;
- pubs[pubVM].invoke(new CacheSerializableRunnable("pub-connect-and-create-data-" + pubVM) {
- public void run2() throws CacheException {
- new File(dir).mkdir();
- final Properties props = new Properties();
- props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
- props.setProperty(STATISTIC_SAMPLE_RATE, "1000");
- props.setProperty(STATISTIC_ARCHIVE_FILE, pubArchives[pubVM]);
- final InternalDistributedSystem system = getSystem(props);
-
- // assert that sampler is working as expected
- final GemFireStatSampler sampler = system.getStatSampler();
- assertTrue(sampler.isSamplingEnabled());
- assertTrue(sampler.isAlive());
- assertEquals(new File(pubArchives[pubVM]), sampler.getArchiveFileName());
-
- final WaitCriterion waitForSampleCollector = new WaitCriterion() {
- public boolean done() {
- return sampler.getSampleCollector() != null;
- }
- public String description() {
- return "sampler.getSampleCollector() is still null!";
- }
- };
- Wait.waitForCriterion(waitForSampleCollector, 4*1000, 10, true);
-
- final SampleCollector sampleCollector = sampler.getSampleCollector();
- assertNotNull(sampleCollector);
-
- final StatArchiveHandler archiveHandler = sampleCollector.getStatArchiveHandler();
- assertNotNull(archiveHandler);
- assertTrue(archiveHandler.isArchiving());
-
- // create cache and region
- final Cache cache = getCache();
- final RegionFactory<String, Number> factory = cache.createRegionFactory();
- factory.setScope(Scope.DISTRIBUTED_ACK);
-
- final RegionMembershipListener rml = new RegionMembershipListener();
- rmlRef.set(rml);
- factory.addCacheListener(rml);
- final Region<String, Number> region = factory.create(regionName);
-
- // create the keys
- if (region.getAttributes().getScope() == Scope.DISTRIBUTED_ACK) {
- for (int key = 0; key < NUM_KEYS; key++) {
- region.create("KEY-"+key, null);
- }
- }
- }
- });
- }
-
- final DistributedMember subMember = (DistributedMember)
- sub.invoke(new SerializableCallable("sub-connect-and-create-keys") {
- @Override
- public Object call() throws Exception {
- new File(dir).mkdir();
- final Properties props = new Properties();
- props.setProperty(STATISTIC_SAMPLING_ENABLED, "true");
- props.setProperty(STATISTIC_SAMPLE_RATE, "1000");
- props.setProperty(STATISTIC_ARCHIVE_FILE, subArchive);
- final InternalDistributedSystem system = getSystem(props);
-
- final PubSubStats statistics = new PubSubStats(system, "sub-1", 1);
- subStatsRef.set(statistics);
-
- // assert that sampler is working as expected
- final GemFireStatSampler sampler = system.getStatSampler();
- assertTrue(sampler.isSamplingEnabled());
- assertTrue(sampler.isAlive());
- assertEquals(new File(subArchive), sampler.getArchiveFileName());
-
- final WaitCriterion waitForSampleCollector = new WaitCriterion() {
- public boolean done() {
- return sampler.getSampleCollector() != null;
- }
- public String description() {
- return "sampler.getSampleCollector() is still null!";
- }
- };
- Wait.waitForCriterion(waitForSampleCollector, 2*1000, 10, true);
-
- final SampleCollector sampleCollector = sampler.getSampleCollector();
- assertNotNull(sampleCollector);
-
- final StatArchiveHandler archiveHandler = sampleCollector.getStatArchiveHandler();
- assertNotNull(archiveHandler);
- assertTrue(archiveHandler.isArchiving());
-
- // create cache and region with UpdateListener
- final Cache cache = getCache();
- final RegionFactory<String, Number> factory = cache.createRegionFactory();
- factory.setScope(Scope.DISTRIBUTED_ACK);
-
- final CacheListener<String, Number> cl = new UpdateListener(statistics);
- factory.addCacheListener(cl);
- final Region<String, Number> region = factory.create(regionName);
-
- // create the keys
- if (region.getAttributes().getScope() == Scope.DISTRIBUTED_ACK) {
- for (int key = 0; key < NUM_KEYS; key++) {
- region.create("KEY-"+key, null);
- }
- }
-
- assertEquals(0, statistics.getUpdateEvents());
- return system.getDistributedMember();
- }
- });
-
- for (int i = 0; i < NUM_PUBS; i++) {
- final int pubVM = i;
- AsyncInvocation[] publishers = new AsyncInvocation[NUM_PUB_THREADS];
- for (int j = 0; j < NUM_PUB_THREADS; j++) {
- final int pubThread = j;
- publishers[pubThread] = pubs[pubVM].invokeAsync(
- new CacheSerializableRunnable("pub-connect-and-put-data-" + pubVM + "-thread-" + pubThread) {
- public void run2() throws CacheException {
- final PubSubStats statistics = new PubSubStats(basicGetSystem(), "pub-" + pubThread, pubVM);
- pubStatsRef.set(pubThread, statistics);
-
- final RegionMembershipListener rml = rmlRef.get();
- final Region<String, Number> region = getCache().getRegion(regionName);
-
- // assert that sub is in rml membership
- assertNotNull(rml);
- WaitCriterion wc = new WaitCriterion() {
- public boolean done() {
- return rml.contains(subMember) && rml.size() == NUM_PUBS;
- }
- public String description() {
- return rml.members + " should contain " + subMember;
- }
- };
- Wait.waitForCriterion(wc, 4*1000, 10, true);
-
- // publish lots of puts cycling through the NUM_KEYS
- assertEquals(0, statistics.getPuts());
-
- // cycle through the keys randomly
- if (RANDOMIZE_PUTS) {
- Random randomGenerator = new Random();
- int key = 0;
- for (int i = 0; i < MAX_PUTS; i++) {
- final long start = statistics.startPut();
- key = randomGenerator.nextInt(NUM_KEYS);
- region.put("KEY-"+key, i);
- statistics.endPut(start);
- }
-
- // cycle through he keys in order and wrapping back around
- } else {
- int key = 0;
- for (int i = 0; i < MAX_PUTS; i++) {
- final long start = statistics.startPut();
- region.put("KEY-"+key, i);
- key++; // cycle through the keys...
- if (key >= NUM_KEYS) {
- key = 0;
- }
- statistics.endPut(start);
- }
- }
- assertEquals(MAX_PUTS, statistics.getPuts());
-
- // wait for 2 samples to ensure all stats have been archived
- final StatisticsType statSamplerType = getSystem().findType("StatSampler");
- final Statistics[] statsArray = getSystem().findStatisticsByType(statSamplerType);
- assertEquals(1, statsArray.length);
-
- final Statistics statSamplerStats = statsArray[0];
- final int initialSampleCount = statSamplerStats.getInt(StatSamplerStats.SAMPLE_COUNT);
-
- wc = new WaitCriterion() {
- public boolean done() {
- return statSamplerStats.getInt(StatSamplerStats.SAMPLE_COUNT) >= initialSampleCount + 2;
- }
- public String description() {
- return "Waiting for " + StatSamplerStats.SAMPLE_COUNT + " >= " + initialSampleCount + 2;
- }
- };
- Wait.waitForCriterion(wc, 4*1000, 10, true);
- }
- });
- }
- for (int pubThread = 0; pubThread < publishers.length; pubThread++) {
- publishers[pubThread].join();
- if (publishers[pubThread].exceptionOccurred()) {
- Assert.fail("Test failed", publishers[pubThread].getException());
- }
- }
- }
-
- sub.invoke(new CacheSerializableRunnable("sub-wait-for-samples") {
- public void run2() throws CacheException {
- // wait for 2 samples to ensure all stats have been archived
- final StatisticsType statSamplerType = getSystem().findType("StatSampler");
- final Statistics[] statsArray = getSystem().findStatisticsByType(statSamplerType);
- assertEquals(1, statsArray.length);
-
- final Statistics statSamplerStats = statsArray[0];
- final int initialSampleCount = statSamplerStats.getInt(StatSamplerStats.SAMPLE_COUNT);
-
- final WaitCriterion wc = new WaitCriterion() {
- public boolean done() {
- return statSamplerStats.getInt(StatSamplerStats.SAMPLE_COUNT) >= initialSampleCount + 2;
- }
- public String description() {
- return "Waiting for " + StatSamplerStats.SAMPLE_COUNT + " >= " + initialSampleCount + 2;
- }
- };
- Wait.waitForCriterion(wc, 4*1000, 10, true);
-
- // now post total updateEvents to static
- final PubSubStats statistics = subStatsRef.get();
- assertNotNull(statistics);
- updateEvents.set(statistics.getUpdateEvents());
- }
- });
-
- // validate pub values against sub values
- final int totalUpdateEvents = sub.invoke(() -> getUpdateEvents());
-
- // validate pub values against pub statistics against pub archive
- for (int i = 0; i < NUM_PUBS; i++) {
- final int pubIdx = i;
- pubs[pubIdx].invoke(new CacheSerializableRunnable("pub-validation") {
- @SuppressWarnings("unused")
- public void run2() throws CacheException {
- // add up all the puts
- assertEquals(NUM_PUB_THREADS, pubStatsRef.length());
- int totalPuts = 0;
- for (int pubThreadIdx = 0; pubThreadIdx < NUM_PUB_THREADS; pubThreadIdx++) {
- PubSubStats statistics = pubStatsRef.get(pubThreadIdx);
- assertNotNull(statistics);
- totalPuts += statistics.getPuts();
- }
-
- // assert that total puts adds up to max puts times num threads
- assertEquals(MAX_PUTS * NUM_PUB_THREADS, totalPuts);
-
- // assert that archive file contains same values as statistics
- File archive = new File(pubArchives[pubIdx]);
- assertTrue(archive.exists());
-
- StatArchiveReader reader = null;
- try {
- reader = new StatArchiveReader(new File[]{archive}, null, false);
- } catch (IOException e) {
- fail("Failed to read " + archive);
- }
-
- double combinedPuts = 0;
-
- @SuppressWarnings("rawtypes")
- List resources = reader.getResourceInstList();
- assertNotNull(resources);
- assertFalse(resources.isEmpty());
-
- for (@SuppressWarnings("rawtypes")
- Iterator iter = resources.iterator(); iter.hasNext();) {
- StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
- if (!ri.getType().getName().equals(PubSubStats.TYPE_NAME)) {
- continue;
- }
-
- StatValue[] statValues = ri.getStatValues();
- for (int i = 0; i < statValues.length; i++) {
- String statName = ri.getType().getStats()[i].getName();
- assertNotNull(statName);
-
- if (statName.equals(PubSubStats.PUTS)) {
- StatValue sv = statValues[i];
- sv.setFilter(StatValue.FILTER_NONE);
-
- double mostRecent = sv.getSnapshotsMostRecent();
- double min = sv.getSnapshotsMinimum();
- double max = sv.getSnapshotsMaximum();
- double maxMinusMin = sv.getSnapshotsMaximum() - sv.getSnapshotsMinimum();
- double mean = sv.getSnapshotsAverage();
- double stdDev = sv.getSnapshotsStandardDeviation();
-
- assertEquals(mostRecent, max, 0f);
-
- double summation = 0;
- double[] rawSnapshots = sv.getRawSnapshots();
- for (int j = 0; j < rawSnapshots.length; j++) {
- //log.convertToLogWriter().info("DEBUG " + ri.getName() + " " + statName + " rawSnapshots[" + j + "] = " + rawSnapshots[j]);
- summation += rawSnapshots[j];
- }
- assertEquals(mean, summation / sv.getSnapshotsSize(), 0);
-
- combinedPuts += mostRecent;
- }
- }
- }
-
- // assert that sum of mostRecent values for all puts equals totalPuts
- assertEquals((double)totalPuts, combinedPuts, 0);
- puts.getAndAdd(totalPuts);
- }
- });
- }
-
- // validate pub values against sub values
- int totalCombinedPuts = 0;
- for (int i = 0; i < NUM_PUBS; i++) {
- final int pubIdx = i;
- final int totalPuts = pubs[pubIdx].invoke(() -> getPuts());
- assertEquals(MAX_PUTS * NUM_PUB_THREADS, totalPuts);
- totalCombinedPuts += totalPuts;
- }
- assertEquals(totalCombinedPuts, totalUpdateEvents);
- assertEquals(MAX_PUTS * NUM_PUB_THREADS * NUM_PUBS, totalCombinedPuts);
-
- // validate sub values against sub statistics against sub archive
- final int totalPuts = totalCombinedPuts;
- sub.invoke(new CacheSerializableRunnable("sub-validation") {
- @SuppressWarnings("unused")
- public void run2() throws CacheException {
- final PubSubStats statistics = subStatsRef.get();
- assertNotNull(statistics);
- final int updateEvents = statistics.getUpdateEvents();
- assertEquals(totalPuts, updateEvents);
- assertEquals(totalUpdateEvents, updateEvents);
- assertEquals(MAX_PUTS * NUM_PUB_THREADS * NUM_PUBS, updateEvents);
-
- // assert that archive file contains same values as statistics
- File archive = new File(subArchive);
- assertTrue(archive.exists());
-
- StatArchiveReader reader = null;
- try {
- reader = new StatArchiveReader(new File[]{archive}, null, false);
- } catch (IOException e) {
- fail("Failed to read " + archive);
- }
-
- double combinedUpdateEvents = 0;
-
- @SuppressWarnings("rawtypes")
- List resources = reader.getResourceInstList();
- for (@SuppressWarnings("rawtypes")
- Iterator iter = resources.iterator(); iter.hasNext();) {
- StatArchiveReader.ResourceInst ri = (StatArchiveReader.ResourceInst) iter.next();
- if (!ri.getType().getName().equals(PubSubStats.TYPE_NAME)) {
- continue;
- }
-
- StatValue[] statValues = ri.getStatValues();
- for (int i = 0; i < statValues.length; i++) {
- String statName = ri.getType().getStats()[i].getName();
- assertNotNull(statName);
-
- if (statName.equals(PubSubStats.UPDATE_EVENTS)) {
- StatValue sv = statValues[i];
- sv.setFilter(StatValue.FILTER_NONE);
-
- double mostRecent = sv.getSnapshotsMostRecent();
- double min = sv.getSnapshotsMinimum();
- double max = sv.getSnapshotsMaximum();
- double maxMinusMin = sv.getSnapshotsMaximum() - sv.getSnapshotsMinimum();
- double mean = sv.getSnapshotsAverage();
- double stdDev = sv.getSnapshotsStandardDeviation();
-
- assertEquals(mostRecent, max,0);
-
- double summation = 0;
- double[] rawSnapshots = sv.getRawSnapshots();
- for (int j = 0; j < rawSnapshots.length; j++) {
- //log.convertToLogWriter().info("DEBUG " + ri.getName() + " " + statName + " rawSnapshots[" + j + "] = " + rawSnapshots[j]);
- summation += rawSnapshots[j];
- }
- assertEquals(mean, summation / sv.getSnapshotsSize(),0);
-
- combinedUpdateEvents += mostRecent;
- }
- }
- }
- assertEquals((double)totalUpdateEvents, combinedUpdateEvents,0);
- }
- });
-
- final int updateEvents = sub.invoke(() -> readIntStat(new File(subArchive), "PubSubStats", "updateEvents"));
- assertTrue(updateEvents > 0);
- assertEquals(MAX_PUTS * NUM_PUB_THREADS * NUM_PUBS, updateEvents);
-
- int puts = 0;
- for (int pubVM = 0; pubVM < NUM_PUBS; pubVM++) {
- int currentPubVM = pubVM;
- int vmPuts = (int)pubs[pubVM].invoke(() -> readIntStat(new File(pubArchives[currentPubVM]), "PubSubStats", "puts"));
- assertTrue(vmPuts > 0);
- assertEquals(MAX_PUTS * NUM_PUB_THREADS, vmPuts);
- puts += vmPuts;
- }
- assertTrue(puts > 0);
- assertEquals(MAX_PUTS * NUM_PUB_THREADS * NUM_PUBS, puts);
-
- // use regex "testPubAndSubCustomStats"
-
- final MultipleArchiveReader reader = new MultipleArchiveReader(".*testPubAndSubCustomStats.*\\.gfs");
-
- final int combinedUpdateEvents = reader.readIntStat(PubSubStats.TYPE_NAME, PubSubStats.UPDATE_EVENTS);
- assertTrue("Failed to read updateEvents stat values", combinedUpdateEvents > 0);
-
- final int combinedPuts = reader.readIntStat(PubSubStats.TYPE_NAME, PubSubStats.PUTS);
- assertTrue("Failed to read puts stat values", combinedPuts > 0);
-
- assertTrue("updateEvents is " + combinedUpdateEvents + " but puts is " + combinedPuts,
- combinedUpdateEvents == combinedPuts);
- }
-
- static int readIntStat(File archive, String typeName, String statName) throws IOException {
- final MultipleArchiveReader reader = new MultipleArchiveReader(archive);
- return reader.readIntStat(typeName, statName);
- }
-
- public static void main(String[] args) throws Exception {
- if (args.length == 2) {
- final String statType = args[0];
- final String statName = args[1];
-
- final MultipleArchiveReader reader = new MultipleArchiveReader();
- final int value = reader.readIntStat(statType, statName);
- System.out.println(statType + "#" + statName + "=" + value);
-
- } else if (args.length == 3) {
- final String archiveName = args[0];
- final String statType = args[1];
- final String statName = args[2];
-
- final File archive = new File(archiveName).getAbsoluteFile();
- assertTrue("File " + archive + " does not exist!", archive.exists());
- assertTrue(archive + " exists but is not a file!", archive.isFile());
-
- final MultipleArchiveReader reader = new MultipleArchiveReader(archive);
- final int value = reader.readIntStat(statType, statName);
- System.out.println(archive + ": " + statType + "#" + statName + "=" + value);
-
- } else if (args.length == 4) {
- final String statType1 = args[0];
- final String statName1 = args[1];
- final String statType2 = args[2];
- final String statName2 = args[3];
-
- final MultipleArchiveReader reader = new MultipleArchiveReader();
- final int value1 = reader.readIntStat(statType1, statName1);
- final int value2 = reader.readIntStat(statType2, statName2);
-
- assertTrue(statType1 + "#" + statName1 + "=" + value1
- + " does not equal " + statType2 + "#" + statName2 + "=" + value2,
- value1 == value2);
- } else {
- assertEquals("Miminum two args are required: statType statName", 2, args.length);
- }
- }
-
- /**
- * @since GemFire 7.0
- */
- static class PubSubStats {
-
- private static final String TYPE_NAME = "PubSubStats";
- private static final String TYPE_DESCRIPTION = "Statistics for StatisticsDUnitTest with Pub/Sub.";
-
- private static final String INSTANCE_PREFIX = "pubSubStats_";
-
- private static final String PUTS = "puts";
- private static final String PUT_TIME = "putTime";
-
- private static final String UPDATE_EVENTS = "updateEvents";
-
- private static StatisticsType createType(StatisticsFactory f) {
- StatisticsTypeFactory stf = StatisticsTypeFactoryImpl.singleton();
- StatisticsType type = stf.createType(
- TYPE_NAME,
- TYPE_DESCRIPTION,
- createDescriptors(f));
- return type;
- }
-
- private static StatisticDescriptor[] createDescriptors(StatisticsFactory f) {
- boolean largerIsBetter = true;
- return new StatisticDescriptor[] {
- f.createIntCounter
- (
- PUTS,
- "Number of puts completed.",
- "operations",
- largerIsBetter
- ),
- f.createLongCounter
- (
- PUT_TIME,
- "Total time spent doing puts.",
- "nanoseconds",
- !largerIsBetter
- ),
- f.createIntCounter
- (
- UPDATE_EVENTS,
- "Number of update events.",
- "events",
- largerIsBetter
- )
- };
- }
-
- private final Statistics statistics;
-
- PubSubStats(StatisticsFactory f, String name, int id) {
- this.statistics = f.createAtomicStatistics(
- createType(f), INSTANCE_PREFIX + "_" + name, id);
- }
-
- Statistics statistics() {
- return this.statistics;
- }
-
- void close() {
- this.statistics.close();
- }
-
- int getUpdateEvents() {
- return statistics().getInt(UPDATE_EVENTS);
- }
-
- void incUpdateEvents() {
- incUpdateEvents(1);
- }
-
- void incUpdateEvents(int amount) {
- incStat(UPDATE_EVENTS, amount);
- }
-
- int getPuts() {
- return statistics().getInt(PUTS);
- }
-
- void incPuts() {
- incPuts(1);
- }
-
- void incPuts(int amount) {
- incStat(PUTS, amount);
- }
-
- void incPutTime(long amount) {
- incStat(PUT_TIME, amount);
- }
-
- long startPut() {
- return NanoTimer.getTime();
- }
-
- void endPut(long start) {
- endPut(start, 1);
- }
-
- void endPut(long start, int amount) {
- long elapsed = NanoTimer.getTime() - start;
- incPuts(amount);
- incPutTime(elapsed);
- }
-
- private void incStat(String statName, int intValue) {
- statistics().incInt(statName, intValue);
- }
-
- private void incStat(String statName, long longValue) {
- statistics().incLong(statName, longValue);
- }
- }
-
- /**
- * @since GemFire 7.0
- */
- static class UpdateListener extends CacheListenerAdapter<String, Number> {
-
- private final PubSubStats statistics;
-
- UpdateListener(PubSubStats statistics) {
- this.statistics = statistics;
- }
-
- @Override
- public void afterUpdate(EntryEvent<String, Number> event) {
- this.statistics.incUpdateEvents( 1 );
- }
- }
-
- /**
- * @since GemFire 7.0
- */
- static class RegionMembershipListener extends RegionMembershipListenerAdapter<String, Number> {
-
- private final List<DistributedMember> members = new ArrayList<DistributedMember>();
-
- int size() {
- return this.members.size();
- }
-
- List<DistributedMember> getMembers() {
- return Collections.unmodifiableList(new ArrayList<DistributedMember>(this.members));
- }
-
- boolean containsId(DistributedMember member) {
- for (DistributedMember peer : getMembers()) {
- if (peer.getId().equals(member.getId())) {
- return true;
- }
- }
- return false;
- }
-
- boolean contains(DistributedMember member) {
- return this.members.contains(member);
- }
-
- String debugContains(DistributedMember member) {
- StringBuffer sb = new StringBuffer();
- for (DistributedMember peer : getMembers()) {
- if (!peer.equals(member)) {
- InternalDistributedMember peerIDM = (InternalDistributedMember)peer;
- InternalDistributedMember memberIDM = (InternalDistributedMember)member;
- sb.append("peer port=").append(peerIDM.getPort()).append(" ");
- sb.append("member port=").append(memberIDM.getPort()).append(" ");
- }
- }
- return sb.toString();
- }
-
- @Override
- public void initialMembers(Region<String, Number> region, DistributedMember[] initialMembers) {
- for (int i = 0; i < initialMembers.length; i++) {
- this.members.add(initialMembers[i]);
- }
- }
-
- @Override
- public void afterRemoteRegionCreate(RegionEvent<String, Number> event) {
- this.members.add(event.getDistributedMember());
- }
-
- @Override
- public void afterRemoteRegionDeparture(RegionEvent<String, Number> event) {
- this.members.remove(event.getDistributedMember());
- }
-
- @Override
- public void afterRemoteRegionCrash(RegionEvent<String, Number> event) {
- this.members.remove(event.getDistributedMember());
- }
- }
-
- static class MultipleArchiveReader {
-
- private final File dir;
- private final String regex;
-
- MultipleArchiveReader(File dir, String regex) {
- this.dir = dir;
- this.regex = regex;
- }
-
- MultipleArchiveReader(File dir) {
- this.dir = dir;
- this.regex = null;
- }
-
- MultipleArchiveReader(String regex) {
- this(new File(System.getProperty("user.dir")).getAbsoluteFile(), regex);
- }
-
- MultipleArchiveReader() {
- this(new File(System.getProperty("user.dir")).getAbsoluteFile(), null);
- }
-
- int readIntStat(String typeName, String statName) throws IOException {
- // directory (maybe directories) with one or more archives
- if (this.dir.exists() && this.dir.isDirectory()) {
- final List<File> archives = findFilesWithSuffix(this.dir, this.regex, ".gfs");
- return readIntStatFromArchives(archives, typeName, statName);
-
- // one archive file
- } else if (this.dir.exists() && this.dir.isFile()) {
- final List<File> archives = new ArrayList<File>();
- archives.add(this.dir);
- return readIntStatFromArchives(archives, typeName, statName);
-
- // failure
- } else {
- throw new IllegalStateException(this.dir + " does not exist!");
- }
- }
-
- private int readIntStatFromArchives(List<File> archives, String typeName, String statName) throws IOException {
- final StatValue[] statValues = readStatValues(archives, typeName, statName);
- assertNotNull("statValues is null!", statValues);
- assertTrue("statValues is empty!", statValues.length > 0);
-
- int value = 0;
- for (int i = 0; i < statValues.length; i++) {
- statValues[i].setFilter(StatValue.FILTER_NONE);
- value += (int)statValues[i].getSnapshotsMaximum();
- }
- return value;
- }
-
- private static List<File> findFilesWithSuffix(final File dir, final String regex, final String suffix) {
- Pattern p = null;
- if (regex != null) {
- p = Pattern.compile(regex);
- }
- final Pattern pattern = p;
-
- return findFiles(
- dir,
- new FileFilter() {
- public boolean accept(File file) {
- boolean accept = true;
- if (regex != null) {
- final Matcher matcher = pattern.matcher(file.getName());
- accept = matcher.matches();
- }
- if (suffix != null) {
- accept = accept && file.getName().endsWith(suffix);
- }
- return accept;
- }
- },
- true);
- }
-
- private static List<File> findFiles(File dir, FileFilter filter, boolean recursive) {
- File[] tmpfiles = dir.listFiles(filter);
- List<File> matches;
- if (tmpfiles == null) {
- matches = new ArrayList<File>();
- } else {
- matches = new ArrayList<File>(Arrays.asList(tmpfiles));
- }
- if (recursive) {
- File[] files = dir.listFiles();
- if (files != null) {
- for (int i = 0; i < files.length; i++) {
- File file = files[i];
- if (file.isDirectory()) {
- matches.addAll(findFiles(file, filter, recursive));
- }
- }
- }
- }
- return matches;
- }
-
- private static StatValue[] readStatValues(final List<File> archives, final String typeName, final String statName) throws IOException {
- System.out.println("\nKIRK readStatValues reading archives:\n\n" + archives + "\n");
- final StatSpec statSpec = new StatSpec() {
- @Override
- public boolean archiveMatches(File value) {
- return true;
- }
- @Override
- public boolean typeMatches(String value) {
- return typeName.equals(value);
- }
- @Override
- public boolean statMatches(String value) {
- return statName.equals(value);
- }
- @Override
- public boolean instanceMatches(String textId, long numericId) {
- return true;
- }
- @Override
- public int getCombineType() {
- return StatSpec.FILE;
- }
- };
-
- final File[] archiveFiles = archives.toArray(new File[archives.size()]);
- final StatSpec[] filters = new StatSpec[] { statSpec };
- final StatArchiveReader reader = new StatArchiveReader(archiveFiles, filters, true);
- final StatValue[] values = reader.matchSpec(statSpec);
- return values;
- }
- }
-}
[16/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeImpl.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeImpl.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeImpl.java
deleted file mode 100644
index ccd4d6c..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeImpl.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-
-import java.io.*;
-import java.util.*;
-
-/**
- * Gathers together a number of {@link StatisticDescriptor statistics}
- * into one logical type.
- *
- * @see Statistics
- *
- *
- * @since GemFire 3.0
- */
-public class StatisticsTypeImpl implements StatisticsType {
-
- /** The name of this statistics type */
- private final String name;
-
- /** The description of this statistics type */
- private final String description;
-
- /** The descriptions of the statistics in id order */
- private final StatisticDescriptor[] stats;
-
- /** Maps a stat name to its StatisticDescriptor */
- private final HashMap statsMap;
-
- /** Contains the number of 32-bit statistics in this type. */
- private final int intStatCount;
-
- /** Contains the number of long statistics in this type. */
- private final int longStatCount;
-
- /** Contains the number of double statistics in this type. */
- private final int doubleStatCount;
-
- ///////////////////// Static Methods /////////////////////
-
- /**
- * @see StatisticsTypeXml#read(Reader, StatisticsTypeFactory)
- */
- public static StatisticsType[] fromXml(Reader reader,
- StatisticsTypeFactory factory)
- throws IOException {
- return (new StatisticsTypeXml()).read(reader, factory);
- }
-
- ////////////////////// Constructors //////////////////////
-
- /**
- * Creates a new <code>StatisticsType</code> with the given name,
- * description, and statistics.
- *
- * @param name
- * The name of this statistics type (for example,
- * <code>"DatabaseStatistics"</code>)
- * @param description
- * A description of this statistics type (for example,
- * "Information about the application's use of the
- * database").
- * @param stats
- * Descriptions of the individual statistics grouped together
- * in this statistics type.
- *
- * @throws NullPointerException
- * If either <code>name</code> or <code>stats</code> is
- * <code>null</code>.
- */
- public StatisticsTypeImpl(String name, String description,
- StatisticDescriptor[] stats) {
- this(name, description, stats, false);
- }
-
- /**
- * Creates a new <code>StatisticsType</code> with the given name,
- * description, and statistics.
- *
- * @param name
- * The name of this statistics type (for example,
- * <code>"DatabaseStatistics"</code>)
- * @param description
- * A description of this statistics type (for example,
- * "Information about the application's use of the
- * database").
- * @param stats
- * Descriptions of the individual statistics grouped together
- * in this statistics type.
- * @param wrapsSharedClass
- * True if this type is a wrapper around a SharedClass??.
- * False if its a dynamic type created at run time.
- *
- * @throws NullPointerException
- * If either <code>name</code> or <code>stats</code> is
- * <code>null</code>.
- */
- public StatisticsTypeImpl(String name, String description,
- StatisticDescriptor[] stats, boolean wrapsSharedClass) {
- if (name == null) {
- throw new NullPointerException(LocalizedStrings.StatisticsTypeImpl_CANNOT_HAVE_A_NULL_STATISTICS_TYPE_NAME.toLocalizedString());
- }
-
- if (stats == null) {
- throw new NullPointerException(LocalizedStrings.StatisticsTypeImpl_CANNOT_HAVE_A_NULL_STATISTIC_DESCRIPTORS.toLocalizedString());
- }
- if (stats.length > StatisticsTypeFactory.MAX_DESCRIPTORS_PER_TYPE) {
- throw new IllegalArgumentException(LocalizedStrings.StatisticsTypeImpl_THE_REQUESTED_DESCRIPTOR_COUNT_0_EXCEEDS_THE_MAXIMUM_WHICH_IS_1.toLocalizedString(new Object[] {Integer.valueOf(stats.length), Integer.valueOf(StatisticsTypeFactory.MAX_DESCRIPTORS_PER_TYPE)}));
- }
-
- this.name = name;
- this.description = description;
- this.stats = stats;
- this.statsMap = new HashMap(stats.length*2);
- int intCount = 0;
- int longCount = 0;
- int doubleCount = 0;
- for (int i=0; i < stats.length; i++) {
- StatisticDescriptorImpl sd = (StatisticDescriptorImpl)stats[i];
- if (sd.getTypeCode() == StatisticDescriptorImpl.INT) {
- if (!wrapsSharedClass) {
- sd.setId(intCount);
- }
- intCount++;
- } else if (sd.getTypeCode() == StatisticDescriptorImpl.LONG) {
- if (!wrapsSharedClass) {
- sd.setId(longCount);
- }
- longCount++;
- } else if (sd.getTypeCode() == StatisticDescriptorImpl.DOUBLE) {
- if (!wrapsSharedClass) {
- sd.setId(doubleCount);
- }
- doubleCount++;
- }
- Object previousValue = statsMap.put(stats[i].getName(), sd);
- if (previousValue != null) {
- throw new IllegalArgumentException(LocalizedStrings.StatisticsTypeImpl_DUPLICATE_STATISTICDESCRIPTOR_NAMED_0.toLocalizedString(stats[i].getName()));
- }
- }
- this.intStatCount = intCount;
- this.longStatCount = longCount;
- this.doubleStatCount = doubleCount;
- }
-
- ////////////////////// StatisticsType Methods //////////////////////
-
- public final String getName() {
- return this.name;
- }
-
- public final String getDescription() {
- return this.description;
- }
-
- public final StatisticDescriptor[] getStatistics() {
- return this.stats;
- }
-
- public final int nameToId(String name) {
- return nameToDescriptor(name).getId();
- }
-
- public final StatisticDescriptor nameToDescriptor(String name) {
- StatisticDescriptorImpl stat = (StatisticDescriptorImpl)statsMap.get(name);
- if (stat == null) {
- throw new IllegalArgumentException(LocalizedStrings.StatisticsTypeImpl_THERE_IS_NO_STATISTIC_NAMED_0.toLocalizedString(name));
- }
- return stat;
- }
-
- ////////////////////// Instance Methods //////////////////////
-
- /**
- * Gets the number of statistics in this type that are ints.
- */
- public int getIntStatCount() {
- return this.intStatCount;
- }
- /**
- * Gets the number of statistics in this type that are longs.
- */
- public int getLongStatCount() {
- return this.longStatCount;
- }
- /**
- * Gets the number of statistics that are doubles.
- */
- public int getDoubleStatCount() {
- return this.doubleStatCount;
- }
-
-// @Override
-// public String toString() {
-// return "StatisticType with " + this.stats.length + " stats";
-// }
-
- @Override
- public String toString() {
- final StringBuilder sb = new StringBuilder(getClass().getName());
- sb.append("@").append(System.identityHashCode(this)).append("{");
- sb.append("name=").append(this.name);
- sb.append(", description=").append(this.description);
- sb.append(", stats.length=").append(this.stats.length);
- sb.append("}");
- return sb.toString();
- }
-
- @Override
- public int hashCode() {
- return getName().hashCode();
- }
- @Override
- public boolean equals(Object o) {
- if (o == null) {
- return false;
- }
- if (!(o instanceof StatisticsType)) {
- return false;
- }
- StatisticsType other = (StatisticsType)o;
- if (!getName().equals(other.getName())) {
- return false;
- }
- if (!getDescription().equals(other.getDescription())) {
- return false;
- }
- StatisticDescriptor[] myStats = getStatistics();
- StatisticDescriptor[] yourStats = other.getStatistics();
- if (myStats.length != yourStats.length) {
- return false;
- }
- for (int i=0; i < myStats.length; i++) {
- if (!myStats[i].equals(yourStats[i])) {
- return false;
- }
- }
- return true;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeXml.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeXml.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeXml.java
deleted file mode 100644
index 0ce0422..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/StatisticsTypeXml.java
+++ /dev/null
@@ -1,280 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
-
-import java.io.*;
-import java.util.*;
-import javax.xml.parsers.*;
-//import javax.xml.transform.*;
-//import javax.xml.transform.dom.*;
-//import javax.xml.transform.stream.*;
-import org.w3c.dom.*;
-import org.xml.sax.*;
-
-// @todo davidw Use a SAX parser instead of DOM
-/**
- * This is an internal helper class for dealing with the
- * SessionFactory XML configuration files.
- */
-public class StatisticsTypeXml
- implements EntityResolver, ErrorHandler {
-
- /** The name of the DTD file */
- static final String DTD = "statisticsType.dtd";
-
- static final String systemId = "http://www.gemstone.com/dtd/" + DTD;
- static final String publicId =
- "-//GemStone Systems, Inc.//GemFire StatisticsType//EN";
-
- ///////////////////// Interface methods ///////////////////////
-
- /**
- * Given a publicId, attempts to resolve it to a DTD. Returns an
- * <code>InputSource</code> for the DTD.
- */
- public InputSource resolveEntity (String publicId, String systemId)
- throws SAXException {
-
- // Figure out the location for the publicId. Be tolerant of other
- // versions of the dtd
- if(publicId.equals(StatisticsTypeXml.publicId) ||
- systemId.equals(StatisticsTypeXml.systemId) ||
- systemId.endsWith(DTD)) {
-
- // Public ID for system config DTD
- String location = "/com/gemstone/gemfire/" + DTD;
- InputStream stream = ClassPathLoader.getLatest().getResourceAsStream(getClass(), location);
- if (stream != null) {
- return new InputSource(stream);
-
- } else {
- throw new SAXNotRecognizedException(LocalizedStrings.StatisticsTypeXml_DTD_NOT_FOUND_0.toLocalizedString(location));
- }
-
- } else {
- throw new SAXNotRecognizedException(LocalizedStrings.StatisticsTypeXml_INVALID_PUBLIC_ID_0.toLocalizedString(publicId));
- }
- }
-
- public void warning(SAXParseException exception) throws SAXException
- {
- // We don't want to thrown an exception. We want to log it!!
- // FIXME
-// String s = "SAX warning while working with XML";
- }
-
- public void error(SAXParseException exception) throws SAXException
- {
- throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_SAX_ERROR_WHILE_WORKING_WITH_XML.toLocalizedString(), exception);
- }
-
- public void fatalError(SAXParseException exception) throws SAXException
- {
- throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_SAX_FATAL_ERROR_WHILE_WORKING_WITH_XML.toLocalizedString(), exception);
- }
-
- ////////////////////// Parsing XML File ////////////////////////
-
- /**
- * Parses the contents of XML data and from it creates one or more
- * <code>StatisticsType</code> instances.
- */
- public StatisticsType[] read( Reader reader, StatisticsTypeFactory statFactory) {
- DocumentBuilderFactory factory =
- DocumentBuilderFactory.newInstance();
-// factory.setValidating(validate);
-
- DocumentBuilder parser = null;
- try {
- parser = factory.newDocumentBuilder();
-
- } catch (ParserConfigurationException ex) {
- throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_PARSING_XML.toLocalizedString(), ex);
- }
-
- parser.setErrorHandler(this);
- parser.setEntityResolver(this);
- Document doc;
- try {
- doc = parser.parse(new InputSource(reader));
- } catch (SAXException se) {
- throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_PARSING_XML.toLocalizedString(), se);
- } catch (IOException io) {
- throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_READING_XML_DATA.toLocalizedString(), io);
- }
-
- if (doc == null) {
- throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_READING_XML_DATA_NO_DOCUMENT.toLocalizedString());
- }
- Element root = doc.getDocumentElement();
- if (root == null) {
- throw new GemFireConfigException(LocalizedStrings.StatisticsTypeXml_FAILED_READING_XML_DATA_NO_ROOT_ELEMENT.toLocalizedString());
- }
- return extractStatistics(root, statFactory);
- }
-
- /*
- * <!ELEMENT statistics (type)+>
- */
- private StatisticsType[] extractStatistics(Element root, StatisticsTypeFactory statFactory) {
- Assert.assertTrue(root.getTagName().equals("statistics"));
-
- ArrayList types = new ArrayList();
- NodeList typeNodes = root.getElementsByTagName("type");
- for (int i = 0; i < typeNodes.getLength(); i++) {
- Element typeNode = (Element) typeNodes.item(i);
- types.add(extractType(typeNode, statFactory));
- }
- return (StatisticsType[])types.toArray(new StatisticsType[types.size()]);
- }
- /**
- * <!ELEMENT type (description?, (stat)+)>
- * <!ATTLIST type name CDATA #REQUIRED>
- */
- private StatisticsType extractType(Element typeNode, StatisticsTypeFactory statFactory) {
- Assert.assertTrue(typeNode.getTagName().equals("type"));
- Assert.assertTrue(typeNode.hasAttribute("name"));
-
- final String typeName = typeNode.getAttribute("name");
- ArrayList stats = new ArrayList();
- NodeList statNodes = typeNode.getElementsByTagName("stat");
- for (int i = 0; i < statNodes.getLength(); i++) {
- Element statNode = (Element) statNodes.item(i);
- stats.add(extractStat(statNode, statFactory));
- }
- StatisticDescriptor[] descriptors =
- (StatisticDescriptor[])stats.toArray(new StatisticDescriptor[stats.size()]);
- String description = "";
- {
- NodeList descriptionNodes = typeNode.getElementsByTagName("description");
- if (descriptionNodes.getLength() > 0) {
- // descriptionNodes will contain the both our description, if it exists,
- // and any nested stat descriptions. Ours will always be first
- Element descriptionNode = (Element) descriptionNodes.item(0);
- // but make sure the first one belongs to our node
- if (descriptionNode.getParentNode().getNodeName().equals(typeNode.getNodeName())) {
- description = extractDescription(descriptionNode);
- }
- }
- }
-
- return statFactory.createType(typeName, description, descriptors);
- }
- private final static int INT_STORAGE = 0;
- private final static int LONG_STORAGE = 1;
- private final static int DOUBLE_STORAGE = 2;
- /**
- * <!ELEMENT stat (description?, unit?)>
- * <!ATTLIST stat
- * name CDATA #REQUIRED
- * counter (true | false) #IMPLIED
- * largerBetter (true | false) #IMPLIED
- * storage (int | long | double) #IMPLIED
- * >
- */
- private StatisticDescriptor extractStat(Element statNode, StatisticsTypeFactory statFactory) {
- Assert.assertTrue(statNode.getTagName().equals("stat"));
- Assert.assertTrue(statNode.hasAttribute("name"));
-
- final String statName = statNode.getAttribute("name");
- String description = "";
- String unit = "";
- boolean isCounter = true;
- boolean largerBetter;
- int storage = INT_STORAGE;
-
- if ( statNode.hasAttribute("counter")) {
- String value = statNode.getAttribute("counter");
- Assert.assertTrue(value.equalsIgnoreCase("true") ||
- value.equalsIgnoreCase("false"));
- isCounter = Boolean.valueOf(value).booleanValue();
- }
- largerBetter = isCounter; // default
- if ( statNode.hasAttribute("largerBetter")) {
- String value = statNode.getAttribute("largerBetter");
- Assert.assertTrue(value.equalsIgnoreCase("true") ||
- value.equalsIgnoreCase("false"));
- largerBetter = Boolean.valueOf(value).booleanValue();
- }
- if ( statNode.hasAttribute("storage")) {
- String value = statNode.getAttribute("storage");
- if (value.equalsIgnoreCase("int")) {
- storage = INT_STORAGE;
- } else if (value.equalsIgnoreCase("long")) {
- storage = LONG_STORAGE;
- } else {
- Assert.assertTrue(value.equalsIgnoreCase("double"));
- storage = DOUBLE_STORAGE;
- }
- }
- {
- NodeList descriptionNodes =
- statNode.getElementsByTagName("description");
- Assert.assertTrue(descriptionNodes.getLength() <= 1);
- if (descriptionNodes.getLength() == 1) {
- Element descriptionNode = (Element) descriptionNodes.item(0);
- description = extractDescription(descriptionNode);
- }
- }
-
- {
- NodeList unitNodes =
- statNode.getElementsByTagName("unit");
- Assert.assertTrue(unitNodes.getLength() <= 1);
- if (unitNodes.getLength() == 1) {
- Element unitNode = (Element) unitNodes.item(0);
- unit = extractUnit(unitNode);
- }
- }
- if (isCounter) {
- switch (storage) {
- case INT_STORAGE: return statFactory.createIntCounter(statName, description, unit, largerBetter);
- case LONG_STORAGE: return statFactory.createLongCounter(statName, description, unit, largerBetter);
- case DOUBLE_STORAGE: return statFactory.createDoubleCounter(statName, description, unit, largerBetter);
- default: throw new RuntimeException(LocalizedStrings.StatisticsTypeXml_UNEXPECTED_STORAGE_TYPE_0.toLocalizedString(Integer.valueOf(storage)));
- }
- } else {
- switch (storage) {
- case INT_STORAGE: return statFactory.createIntGauge(statName, description, unit, largerBetter);
- case LONG_STORAGE: return statFactory.createLongGauge(statName, description, unit, largerBetter);
- case DOUBLE_STORAGE: return statFactory.createDoubleGauge(statName, description, unit, largerBetter);
- default: throw new RuntimeException(LocalizedStrings.StatisticsTypeXml_UNEXPECTED_STORAGE_TYPE_0.toLocalizedString(Integer.valueOf(storage)));
- }
- }
- }
- /**
- * <!ELEMENT description (#PCDATA)>
- */
- private String extractDescription(Element descriptionNode) {
- Assert.assertTrue(descriptionNode.getTagName().equals("description"));
- return extractText(descriptionNode);
- }
- /**
- * <!ELEMENT unit (#PCDATA)>
- */
- private String extractUnit(Element unitNode) {
- Assert.assertTrue(unitNode.getTagName().equals("unit"));
- return extractText(unitNode);
- }
- private String extractText(Element element) {
- Text text = (Text) element.getFirstChild();
- return((text == null ? "" : text.getData()));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/SystemAdmin.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/SystemAdmin.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/SystemAdmin.java
index cc03ad6..e52950f 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/SystemAdmin.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/SystemAdmin.java
@@ -26,8 +26,9 @@ import com.gemstone.gemfire.cache.persistence.PersistentID;
import com.gemstone.gemfire.distributed.DistributedMember;
import com.gemstone.gemfire.distributed.internal.*;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
-import com.gemstone.gemfire.internal.StatArchiveReader.ResourceInst;
-import com.gemstone.gemfire.internal.StatArchiveReader.StatValue;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.ResourceInst;
+import com.gemstone.gemfire.internal.statistics.StatArchiveReader.StatValue;
import com.gemstone.gemfire.internal.admin.remote.TailLogResponse;
import com.gemstone.gemfire.internal.cache.DiskStoreImpl;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
@@ -940,7 +941,7 @@ public class SystemAdmin {
return result;
}
- private static class StatSpec implements StatArchiveReader.StatSpec {
+ public static class StatSpec implements StatArchiveReader.StatSpec {
public final String cmdLineSpec;
public final String typeId;
public final String instanceId;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStats.java
deleted file mode 100644
index d7dde46..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStats.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * Statistics related to a Java VM. Currently they all come from
- * {@link java.lang.Runtime}.
- */
-public class VMStats implements VMStatsContract {
- private final static StatisticsType vmType;
- private final static int cpusId;
- private final static int freeMemoryId;
- private final static int totalMemoryId;
- private final static int maxMemoryId;
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- vmType = f.createType("VMStats",
- "Stats available on any java virtual machine.",
- new StatisticDescriptor[] {
- f.createIntGauge("cpus",
- "Number of cpus available to the java VM on its machine.",
- "cpus", true),
- f.createLongGauge("freeMemory",
- "An approximation fo the total amount of memory currently available for future allocated objects, measured in bytes.",
- "bytes", true),
- f.createLongGauge("totalMemory",
- "The total amount of memory currently available for current and future objects, measured in bytes.",
- "bytes"),
- f.createLongGauge("maxMemory",
- "The maximum amount of memory that the VM will attempt to use, measured in bytes.",
- "bytes", true)
- });
- cpusId = vmType.nameToId("cpus");
- freeMemoryId = vmType.nameToId("freeMemory");
- totalMemoryId = vmType.nameToId("totalMemory");
- maxMemoryId = vmType.nameToId("maxMemory");
- }
-
- private final Statistics vmStats;
-
-
- public VMStats(StatisticsFactory f, long id) {
- this.vmStats = f.createStatistics(vmType, "vmStats", id);
- }
-
- public void refresh() {
- Runtime rt = Runtime.getRuntime();
- this.vmStats.setInt(cpusId, rt.availableProcessors());
- this.vmStats.setLong(freeMemoryId, rt.freeMemory());
- this.vmStats.setLong(totalMemoryId, rt.totalMemory());
- this.vmStats.setLong(maxMemoryId, rt.maxMemory());
-
- }
- public void close() {
- this.vmStats.close();
- }
-
- /* (non-Javadoc)
- * @see com.gemstone.gemfire.internal.VMStatsContract#getFdsOpen()
- */
- public long getFdsOpen() {
- return -1;
- }
-
- /* (non-Javadoc)
- * @see com.gemstone.gemfire.internal.VMStatsContract#getFdLimit()
- */
- public long getFdLimit() {
- return 0;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStatsContract.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStatsContract.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStatsContract.java
deleted file mode 100644
index 238cf86..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStatsContract.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-/**
- * Describes the contract a VMStats implementation must implement.
- * <p> I named this VMStatsContract because an implementation named
- * VMStats already exists and I didn't want to rename it because
- * of the svn merge issues.
- * @see VMStatsContractFactory
- */
-public interface VMStatsContract {
- /**
- * Called by sampler when it wants the VMStats statistics values to be
- * refetched from the system.
- */
- public void refresh();
- /**
- * Called by sampler when it wants the VMStats to go away.
- */
- public void close();
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStatsContractFactory.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStatsContractFactory.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStatsContractFactory.java
deleted file mode 100644
index ff84b0e..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/VMStatsContractFactory.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.stats50.VMStats50;
-
-/**
- * Factory used to produce an instance of VMStatsContract.
- */
-public class VMStatsContractFactory {
- /**
- * Create and return a VMStatsContract.
- */
- public static VMStatsContract create(StatisticsFactory f, long id) {
- VMStatsContract result;
- try {
- result = new VMStats50(f, id);
- }
- catch (VirtualMachineError err) {
- SystemFailure.initiateFailure(err);
- // If this ever returns, rethrow the error. We're poisoned
- // now, so don't let this thread continue.
- throw err;
- }
- catch (Throwable ignore) {
- // Now that we no longer support 1.4 I'm not sure why we would get here.
- // But just in case other vm vendors don't support mxbeans I've left
- // this logic in that will create a simple VMStats instance.
- // Whenever you catch Error or Throwable, you must also
- // catch VirtualMachineError (see above). However, there is
- // _still_ a possibility that you are dealing with a cascading
- // error condition, so you also need to check to see if the JVM
- // is still usable:
- SystemFailure.checkFailure();
- //log.warning("Could not create 5.0 VMStats", ignore);
- // couldn't create the 1.5 version so create the old 1.4 version
- result = new VMStats(f, id);
- }
- return result;
- }
-
- private VMStatsContractFactory() {
- // private so no instances allowed. static methods only
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/WindowsProcessStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/WindowsProcessStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/WindowsProcessStats.java
deleted file mode 100644
index a671717..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/WindowsProcessStats.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * <P>This class provides the interface for statistics about a
- * windows operating system process that is using a GemFire system.
- */
-public class WindowsProcessStats
-{
- private final static int handlesINT = 0;
- private final static int priorityBaseINT = 1;
- private final static int threadsINT = 2;
-
- private final static int activeTimeLONG = 0;
- private final static int pageFaultsLONG = 1;
- private final static int pageFileSizeLONG = 2;
- private final static int pageFileSizePeakLONG = 3;
- private final static int privateSizeLONG = 4;
- private final static int systemTimeLONG = 5;
- private final static int userTimeLONG = 6;
- private final static int virtualSizeLONG = 7;
- private final static int virtualSizePeakLONG = 8;
- private final static int workingSetSizeLONG = 9;
- private final static int workingSetSizePeakLONG = 10;
-
- private final static StatisticsType myType;
-
- private static void checkOffset(String name, int offset) {
- int id = myType.nameToId(name);
- Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
- }
-
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- myType = f
- .createType(
- "WindowsProcessStats",
- "Statistics on a Microsoft Window's process.",
- new StatisticDescriptor[] {
- f.createIntGauge(
- "handles",
- "The total number of handles currently open by this process. This number is the sum of the handles currently open by each thread in this process.",
- "items"),
- f.createIntGauge(
- "priorityBase",
- "The current base priority of the process. Threads within a process can raise and lower their own base priority relative to the process's base priority",
- "priority"),
- f.createIntGauge(
- "threads",
- "Number of threads currently active in this process. An instruction is the basic unit of execution in a processor, and a thread is the object that executes instructions. Every running process has at least one thread.",
- "threads"),
-
- f.createLongCounter(
- "activeTime",
- "The elapsed time in milliseconds that all of the threads of this process used the processor to execute instructions. An instruction is the basic unit of execution in a computer, a thread is the object that executes instructions, and a process is the object created when a program is run. Code executed to handle some hardware interrupts and trap conditions are included in this count.",
- "milliseconds", false),
-
- f.createLongCounter(
- "pageFaults",
- "The total number of Page Faults by the threads executing in this process. A page fault occurs when a thread refers to a virtual memory page that is not in its working set in main memory. This will not cause the page to be fetched from disk if it is on the standby list and hence already in main memory, or if it is in use by another process with whom the page is shared.",
- "operations", false),
- f.createLongGauge(
- "pageFileSize",
- "The current number of bytes this process has used in the paging file(s). Paging files are used to store pages of memory used by the process that are not contained in other files. Paging files are shared by all processes, and lack of space in paging files can prevent other processes from allocating memory.",
- "bytes"),
- f.createLongGauge(
- "pageFileSizePeak",
- "The maximum number of bytes this process has used in the paging file(s). Paging files are used to store pages of memory used by the process that are not contained in other files. Paging files are shared by all processes, and lack of space in paging files can prevent other processes from allocating memory.",
- "bytes"),
- f.createLongGauge(
- "privateSize",
- "The current number of bytes this process has allocated that cannot be shared with other processes.",
- "bytes"),
- f.createLongCounter(
- "systemTime",
- "The elapsed time in milliseconds that the threads of the process have spent executing code in privileged mode. When a Windows system service is called, the service will often run in Privileged Mode to gain access to system-private data. Such data is protected from access by threads executing in user mode. Calls to the system can be explicit or implicit, such as page faults or interrupts. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of user and privileged modes. These subsystem processes provide additional protection. Therefore, some work done by Windows on behalf of your application might appear in other subsystem processes in addition to the privileged time in your process.",
- "milliseconds", false),
- f.createLongCounter(
- "userTime",
- "The elapsed time in milliseconds that this process's threads have spent executing code in user mode. Applications, environment subsystems, and integral subsystems execute in user mode. Code executing in User Mode cannot damage the integrity of the Windows Executive, Kernel, and device drivers. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of user and privileged modes. These subsystem processes provide additional protection. Therefore, some work done by Windows on behalf of your application might appear in other subsystem processes in addition to the privileged time in your process.",
- "milliseconds", false),
- f.createLongGauge(
- "virtualSize",
- "Virtual Bytes is the current size in bytes of the virtual address space the process is using. Use of virtual address space does not necessarily imply corresponding use of either disk or main memory pages. Virtual space is finite, and by using too much, the process can limit its ability to load libraries.",
- "bytes"),
- f.createLongGauge(
- "virtualSizePeak",
- "The maximum number of bytes of virtual address space the process has used at any one time. Use of virtual address space does not necessarily imply corresponding use of either disk or main memory pages. Virtual space is however finite, and by using too much, the process might limit its ability to load libraries.",
- "bytes"),
- f.createLongGauge(
- "workingSetSize",
- "The current number of bytes in the Working Set of this process. The Working Set is the set of memory pages touched recently by the threads in the process. If free memory in the computer is above a threshold, pages are left in the Working Set of a process even if they are not in use. When free memory falls below a threshold, pages are trimmed from Working Sets. If they are needed they will then be soft-faulted back into the Working Set before they are paged out out to disk.",
- "bytes"),
- f.createLongGauge(
- "workingSetSizePeak",
- "The maximum number of bytes in the Working Set of this process at any point in time. The Working Set is the set of memory pages touched recently by the threads in the process. If free memory in the computer is above a threshold, pages are left in the Working Set of a process even if they are not in use. When free memory falls below a threshold, pages are trimmed from Working Sets. If they are needed they will then be soft-faulted back into the Working Set before they leave main memory.",
- "bytes"),
-
- });
- checkOffset("handles", handlesINT);
- checkOffset("priorityBase", priorityBaseINT);
- checkOffset("threads", threadsINT);
-
- checkOffset("activeTime", activeTimeLONG);
- checkOffset("pageFaults", pageFaultsLONG);
- checkOffset("pageFileSize", pageFileSizeLONG);
- checkOffset("pageFileSizePeak", pageFileSizePeakLONG);
- checkOffset("privateSize", privateSizeLONG);
- checkOffset("systemTime", systemTimeLONG);
- checkOffset("userTime", userTimeLONG);
- checkOffset("virtualSize", virtualSizeLONG);
- checkOffset("virtualSizePeak", virtualSizePeakLONG);
- checkOffset("workingSetSize", workingSetSizeLONG);
- checkOffset("workingSetSizePeak", workingSetSizePeakLONG);
- }
-
- private WindowsProcessStats() {
- // no instances allowed
- }
- public static StatisticsType getType() {
- return myType;
- }
-
- /**
- * Returns a <code>ProcessStats</code> that wraps Windows process
- * <code>Statistics</code>.
- *
- * @since GemFire 3.5
- */
- static ProcessStats createProcessStats(final Statistics stats) {
- if (stats instanceof LocalStatisticsImpl) {
- HostStatHelper.refresh((LocalStatisticsImpl) stats);
- } // otherwise its a Dummy implementation so do nothing
- return new ProcessStats(stats) {
- @Override
- public long getProcessSize() {
- return stats.getLong(workingSetSizeLONG) / (1024*1024);
- }
- };
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/WindowsSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/WindowsSystemStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/WindowsSystemStats.java
deleted file mode 100644
index 1325fcc..0000000
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/WindowsSystemStats.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * 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 com.gemstone.gemfire.internal;
-
-import com.gemstone.gemfire.*;
-
-/**
- * <P>This class provides the interface for statistics about the
- * Windows machine a GemFire system is running on.
- */
-public class WindowsSystemStats
-{
- private final static int committedMemoryInUseINT = 0;
- private final static int eventsINT = 1;
- private final static int interruptsINT = 2;
- private final static int mutexesINT = 3;
- private final static int processesINT = 4;
- private final static int processorQueueLengthINT = 5;
- private final static int registryQuotaInUseINT = 6;
- private final static int sharedMemorySectionsINT = 7;
- private final static int semaphoresINT = 8;
- private final static int threadsINT = 9;
- private final static int dgramsReceivedINT = 10;
- private final static int dgramsNoPortINT = 11;
- private final static int dgramsReceivedErrorsINT = 12;
- private final static int dgramsSentINT = 13;
- private final static int loopbackPacketsINT = 14;
- private final static int loopbackBytesINT = 15;
- private final static int netPacketsReceivedINT = 16;
- private final static int netBytesReceivedINT = 17;
- private final static int netPacketsSentINT = 18;
- private final static int netBytesSentINT = 19;
-
-
- private final static int availableMemoryLONG = 0;
- private final static int cacheFaultsLONG = 1;
- private final static int cacheSizeLONG = 2;
- private final static int cacheSizePeakLONG = 3;
- private final static int committedMemoryLONG = 4;
- private final static int committedMemoryLimitLONG = 5;
- private final static int contextSwitchesLONG = 6;
- private final static int demandZeroFaultsLONG = 7;
- private final static int pageFaultsLONG = 8;
- private final static int pageReadsLONG = 9;
- private final static int pagesLONG = 10;
- private final static int pageWritesLONG = 11;
- private final static int pagesInputLONG = 12;
- private final static int pagesOutputLONG = 13;
- private final static int systemCallsLONG = 14;
-
- private final static int cpuActiveDOUBLE = 0;
- private final static int cpuIdleDOUBLE = 1;
- private final static int cpuInterruptDOUBLE = 2;
- private final static int cpuSystemDOUBLE = 3;
- private final static int cpuUserDOUBLE = 4;
-
- private final static StatisticsType myType;
-
- private static void checkOffset(String name, int offset) {
- int id = myType.nameToId(name);
- Assert.assertTrue(offset == id, "Expected the offset for " + name + " to be " + offset + " but it was " + id);
- }
-
- static {
- StatisticsTypeFactory f = StatisticsTypeFactoryImpl.singleton();
- myType = f.createType("WindowsSystemStats",
- "Statistics on a Microsoft Windows machine.",
- new StatisticDescriptor[] {
- f.createIntGauge("committedMemoryInUse",
- "This represents the percentage of available virtual memory in use. This is an instantaneous value, not an average.",
- "%"),
- f.createIntGauge("events",
- "The number of events in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. An event is used when two or more threads wish to synchronize execution.",
- "items"),
- f.createIntCounter("interrupts",
- "The total number of harware interrupts on the computer. Some devices that may generate interrupts are the system timer, the mouse, data communication lines, network interface cards and other peripheral devices. This counter provides an indication of how busy these devices are on a computer-wide basis.",
- "operations", false),
- f.createIntGauge("mutexes",
- "The number of mutexes in the computer at the time of data collection. This is an instantaneous count, not an average over the time interval. Mutexes are used by threads to assure only one thread is executing some section of code.",
- "items"),
- f.createIntGauge("processes",
- "The number of processes in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Each process represents the running of a program.",
- "processes"),
- f.createIntGauge("processorQueueLength",
- "The instantaneous length of the processor queue in units of threads. All processors use a single queue in which threads wait for processor cycles. This length does not include the threads that are currently executing. A sustained processor queue length greater than two generally indicates processor congestion. This is an instantaneous count, not an average over the time interval",
- "threads"),
- f.createIntGauge("registryQuotaInUse",
- "The percentage of the Total Registry Quota Allowed currently in use by the system.",
- "%"),
- f.createIntGauge("sharedMemorySections",
- "The number of sections in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. A section is a portion of virtual memory created by a process for storing data. A process may share sections with other processes.",
- "items"),
- f.createIntGauge("semaphores",
- "The number of semaphores in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. Threads use semaphores to obtain exclusive access to data structures that they share with other threads.",
- "items"),
- f.createIntGauge("threads",
- "The number of threads in the computer at the time of data collection. Notice that this is an instantaneous count, not an average over the time interval. A thread is the basic executable entity that can execute instructions in a processor.",
- "threads"),
- f.createIntCounter(
- "dgramsReceived",
- "The number of datagrams received on the VM's machine.",
- "datagrams/sec"),
- f.createIntCounter(
- "dgramsNoPort",
- "The number of incoming datagrams that were discarded due to invalid headers",
- "datagrams/sec"),
- f.createIntCounter(
- "dgramsReceivedErrors",
- "The number of received UDP datagrams that could not be delivered for reasons other than the lack of an application at the destination port",
- "datagrams"),
- f.createIntCounter(
- "dgramsSent",
- "The number of datagrams sent on the VM's machine",
- "datagrams/sec"),
-
- f.createIntCounter(
- "loopbackPackets",
- "The number of packets sent/received on the loopback interface",
- "packets"),
- f.createIntCounter(
- "loopbackBytes",
- "The number of bytes sent/received on the loopback interface",
- "bytes"),
- f.createIntCounter("netPacketsReceived",
- "The number of network packets received (total excluding loopback)",
- "packets"),
- f.createIntCounter("netBytesReceived",
- "The number of network bytes received (total excluding loopback)",
- "bytes"),
- f.createIntCounter("netPacketsSent",
- "The number of network packets sent (total excluding loopback)",
- "packets"),
- f.createIntCounter("netBytesSent",
- "The number of network bytes sent (total excluding loopback)",
- "bytes"),
-
- f.createLongGauge("availableMemory",
- "The size, in bytes, of the virtual memory currently on the Zeroed, Free, and Standby lists. Zeroed and Free memory is ready for use, with Zeroed memory cleared to zeros. Standby memory is memory removed from a process's Working Set but still available. Notice that this is an instantaneous count, not an average over the time interval.",
- "bytes", true),
- f.createLongCounter("cacheFaults",
- "Incremented whenever the Cache manager does not find a file's page in the immediate Cache and must ask the memory manager to locate the page elsewhere in memory or on the disk so that it can be loaded into the immediate Cache.",
- "operations", false),
- f.createLongGauge("cacheSize",
- "Measures the number of bytes currently in use by the system Cache. The system Cache is used to buffer data retrieved from disk or LAN. The system Cache uses memory not in use by active processes in the computer.",
- "bytes"),
- f.createLongGauge("cacheSizePeak",
- "Measures the maximum number of bytes used by the system Cache. The system Cache is used to buffer data retrieved from disk or LAN. The system Cache uses memory not in use by active processes in the computer.",
- "bytes"),
- f.createLongGauge("committedMemory",
- "The size of virtual memory, in bytes, that has been Committed (as opposed to simply reserved). Committed memory must have backing (i.e., disk) storage available, or must be assured never to need disk storage (because main memory is large enough to hold it.) Notice that this is an instantaneous count, not an average over the time interval.",
- "bytes"),
- f.createLongGauge("committedMemoryLimit",
- "The size, in bytes, of virtual memory that can be committed without having to extend the paging file(s). If the paging file(s) can be extended, this is a soft limit. Note that this value will change if the paging file is extended.",
- "bytes"),
- f.createLongCounter("contextSwitches",
- "The number of times this thread has lost the cpu to another thread. Thread switches can occur either inside of a single process or across processes. A thread switch may be caused either by one thread asking another for information, or by a thread being preempted by another, higher priority thread becoming ready to run. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of User and Privileged modes. These subsystem processes provide additional protection. Therefore, some work done by Windows on behalf of an application may appear in other subsystem processes in addition to the Privileged Time in the application. Switching to the subsystem process causes one Context Switch in the application thread. Switching back causes another Context Switch in the subsystem thread.",
- "operations", false),
- f.createLongCounter("demandZeroFaults",
- "The total number of page faults for pages that must be filled with zeros before the fault is satisfied. If the Zeroed list is not empty, the fault can be resolved by removing a page from the Zeroed list.",
- "operations", false),
- f.createLongCounter("pageFaults",
- "The total number of Page Faults by the threads executing in this process. A page fault occurs when a thread refers to a virtual memory page that is not in its working set in main memory. This will not cause the page to be fetched from disk if it is on the standby list and hence already in main memory, or if it is in use by another process with whom the page is shared.",
- "operations", false),
- f.createLongCounter("pageReads",
- "The number of page read operations done by the process since it was last started. These operations involve actual disk reads and not reads from the shared page cache",
- "operations", false),
- f.createLongCounter("pages",
- "The total number of pages read from the disk or written to the disk to resolve memory references to pages that were not in memory at the time of the reference. This is the sum of pagesInput and the pagesOutput. This counter includes paging traffic on behalf of the system Cache to access file data for applications. This value also includes the pages to/from non-cached mapped memory files. This is the primary counter to observe if you are concerned about excessive memory pressure (that is, thrashing), and the excessive paging that may result.",
- "pages", false),
- f.createLongCounter("pageWrites",
- "The number of pages written by the process since it was last started. These page writes are actual disk writes and not just writes into the shared page cache. Unless a large data load is in process, the number should be low for all processes except the Stone's AIO page server process.",
- "operations", false),
- f.createLongCounter("pagesInput",
- "The total number of pages read from the disk to resolve memory references to pages that were not in memory at the time of the reference. This counter includes paging traffic on behalf of the system Cache to access file data for applications. This is an important counter to observe if you are concerned about excessive memory pressure (that is, thrashing), and the excessive paging that may result",
- "pages", false),
- f.createLongCounter("pagesOutput",
- "A count of the total number of pages that are written to disk because the pages have been modified in main memory",
- "pages", false),
- f.createLongCounter("systemCalls",
- "The total number of calls to Windows system service routines on the computer. These routines perform all of the basic scheduling and synchronization of activities on the computer, and provide access to non-graphical devices, memory management, and name space management.",
- "operations"),
-
-
-
- f.createDoubleGauge("cpuActive",
- "The percentage of time spent doing useful work by all processors. On a multi-processor system, if all processors are always busy this is 100%.",
- "%"),
- f.createDoubleGauge("cpuIdle",
- "The percentage of time the machine's processors spent idle.",
- "%", true),
- f.createDoubleGauge("cpuInterrupt",
- "The percentage of time spent receiving and servicing interrupts on all the processors on the machine. This value is an indirect indicator of the activity of devices that generate interrupts, such as the system clock, the mouse, disk drivers, data communication lines, network interface cards and other peripheral devices. These devices normally interrupt the processor when they have completed a task or require attention. Normal thread execution is suspended during interrupts. Most system clocks interrupt the processor every 10 milliseconds, creating a background of interrupt activity. ",
- "%"),
- f.createDoubleGauge("cpuSystem",
- "The percentage of time spent in privileged mode by all processors. On a multi-processor system, if all processors are always in privileged mode this is 100%. When a Windows system service is called, the service will often run in privileged mode in order to gain access to system-private data. Such data is protected from access by threads executing in user mode. Calls to the system may be explicit, or they may be implicit such as when a page fault or an interrupt occurs. Unlike some early operating systems, Windows uses process boundaries for subsystem protection in addition to the traditional protection of user and privileged modes. These subsystem processes provide additional protection. Therefore, some work done by Windows on behalf of an application may appear in other subsystem processes in addition to the cpuSystem in the application process.",
- "%"),
- f.createDoubleGauge("cpuUser",
- "The percentage of time spent executing code in user mode on all the processor's on the machine.",
- "%")
- });
- checkOffset("committedMemoryInUse", committedMemoryInUseINT);
- checkOffset("events", eventsINT);
- checkOffset("interrupts", interruptsINT);
- checkOffset("mutexes", mutexesINT);
- checkOffset("processes", processesINT);
- checkOffset("processorQueueLength", processorQueueLengthINT);
- checkOffset("registryQuotaInUse", registryQuotaInUseINT);
- checkOffset("sharedMemorySections", sharedMemorySectionsINT);
- checkOffset("semaphores", semaphoresINT);
- checkOffset("threads", threadsINT);
- checkOffset("dgramsReceived", dgramsReceivedINT);
- checkOffset("dgramsNoPort", dgramsNoPortINT);
- checkOffset("dgramsReceivedErrors", dgramsReceivedErrorsINT);
- checkOffset("dgramsSent", dgramsSentINT);
-
- checkOffset("loopbackPackets", loopbackPacketsINT);
- checkOffset("loopbackBytes", loopbackBytesINT);
- checkOffset("netPacketsReceived", netPacketsReceivedINT);
- checkOffset("netBytesReceived", netBytesReceivedINT);
- checkOffset("netPacketsSent", netPacketsSentINT);
- checkOffset("netBytesSent", netBytesSentINT);
-
- checkOffset("availableMemory", availableMemoryLONG);
- checkOffset("cacheFaults", cacheFaultsLONG);
- checkOffset("cacheSize", cacheSizeLONG);
- checkOffset("cacheSizePeak", cacheSizePeakLONG);
- checkOffset("committedMemory", committedMemoryLONG);
- checkOffset("committedMemoryLimit", committedMemoryLimitLONG);
- checkOffset("contextSwitches", contextSwitchesLONG);
- checkOffset("demandZeroFaults", demandZeroFaultsLONG);
- checkOffset("pageFaults", pageFaultsLONG);
- checkOffset("pageReads", pageReadsLONG);
- checkOffset("pages", pagesLONG);
- checkOffset("pageWrites", pageWritesLONG);
- checkOffset("pagesInput", pagesInputLONG);
- checkOffset("pagesOutput", pagesOutputLONG);
- checkOffset("systemCalls", systemCallsLONG);
-
- checkOffset("cpuActive", cpuActiveDOUBLE);
- checkOffset("cpuIdle", cpuIdleDOUBLE);
- checkOffset("cpuInterrupt", cpuInterruptDOUBLE);
- checkOffset("cpuSystem", cpuSystemDOUBLE);
- checkOffset("cpuUser", cpuUserDOUBLE);
- }
-
- private WindowsSystemStats() {
- // no instances allowed
- }
- public static StatisticsType getType() {
- return myType;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AddStatListenerResponse.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AddStatListenerResponse.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AddStatListenerResponse.java
index 7ea19f5..078798f 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AddStatListenerResponse.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AddStatListenerResponse.java
@@ -19,12 +19,12 @@
package com.gemstone.gemfire.internal.admin.remote;
//import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.*;
//import com.gemstone.gemfire.internal.admin.*;
import com.gemstone.gemfire.distributed.internal.*;
import java.io.*;
//import java.util.*;
import com.gemstone.gemfire.distributed.internal.membership.*;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
/**
* A message that is sent to a particular distribution manager to
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AdminConsoleDisconnectMessage.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AdminConsoleDisconnectMessage.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AdminConsoleDisconnectMessage.java
index 2f8d336..a1d3680 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AdminConsoleDisconnectMessage.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/AdminConsoleDisconnectMessage.java
@@ -28,7 +28,7 @@ import com.gemstone.gemfire.DataSerializer;
import com.gemstone.gemfire.distributed.internal.DistributionManager;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.PooledDistributionMessage;
-import com.gemstone.gemfire.internal.GemFireStatSampler;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.gemfire.internal.logging.log4j.AlertAppender;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/CancelStatListenerResponse.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/CancelStatListenerResponse.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/CancelStatListenerResponse.java
index d338b70..a223524 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/CancelStatListenerResponse.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/CancelStatListenerResponse.java
@@ -19,13 +19,13 @@
package com.gemstone.gemfire.internal.admin.remote;
//import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.*;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
//import com.gemstone.gemfire.internal.admin.*;
import com.gemstone.gemfire.distributed.internal.*;
import java.io.*;
//import java.util.*;
import com.gemstone.gemfire.distributed.internal.membership.*;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
/**
* A message that is sent to a particular distribution manager to
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/RemoteStat.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/RemoteStat.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/RemoteStat.java
index cdc2b88..6127e45 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/RemoteStat.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/RemoteStat.java
@@ -18,8 +18,8 @@
package com.gemstone.gemfire.internal.admin.remote;
import com.gemstone.gemfire.*;
-import com.gemstone.gemfire.internal.*;
import com.gemstone.gemfire.internal.admin.*;
+import com.gemstone.gemfire.internal.statistics.StatisticDescriptorImpl;
//import java.util.*;
import java.io.*;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/package.html
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/package.html b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/package.html
index a2fef69..a47f53d 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/package.html
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/admin/remote/package.html
@@ -34,7 +34,7 @@ relationships between the various classes in this package.</P>
<H2>Statistics</H2>
<code>StatListener</code>s are assigned a {@link
-com.gemstone.gemfire.internal.GemFireStatSampler#addListener} unique
+com.gemstone.gemfire.internal.statistics.GemFireStatSampler#addListener} unique
id} in the remote VM.</code>
</BODY>
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/CachePerfStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/CachePerfStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/CachePerfStats.java
index 72a850d..532bafa 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/CachePerfStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/CachePerfStats.java
@@ -21,6 +21,7 @@ import com.gemstone.gemfire.*;
import com.gemstone.gemfire.internal.*;
import com.gemstone.gemfire.distributed.internal.PoolStatHelper;
import com.gemstone.gemfire.distributed.internal.QueueStatHelper;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* CachePerfStats tracks statistics about GemFire cache performance.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskDirectoryStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskDirectoryStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskDirectoryStats.java
index 21a7b26..a0d7022 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskDirectoryStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskDirectoryStats.java
@@ -19,7 +19,7 @@ package com.gemstone.gemfire.internal.cache;
import com.gemstone.gemfire.*;
//import com.gemstone.gemfire.internal.NanoTimer;
//import com.gemstone.gemfire.cache.Region;
-import com.gemstone.gemfire.internal.*;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* GemFire statistics about Disk Directories
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskRegionStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskRegionStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskRegionStats.java
index ae9b0a9..014fd6f 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskRegionStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskRegionStats.java
@@ -21,7 +21,7 @@ import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* GemFire statistics about a {@link DiskRegion}.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskStoreStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskStoreStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskStoreStats.java
index db505b9..e5f4bb2 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskStoreStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/DiskStoreStats.java
@@ -18,8 +18,8 @@ package com.gemstone.gemfire.internal.cache;
import com.gemstone.gemfire.*;
//import com.gemstone.gemfire.cache.Region;
-import com.gemstone.gemfire.internal.*;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* GemFire statistics about a {@link DiskStoreImpl}.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PartitionedRegionStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PartitionedRegionStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PartitionedRegionStats.java
index 04d432f..c6f1243 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PartitionedRegionStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PartitionedRegionStats.java
@@ -27,7 +27,7 @@ import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.cache.Region;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* Represents a statistics type that can be archived to vsd. Loading of this
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PoolStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PoolStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PoolStats.java
index 2161de7..e53b61c 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PoolStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/PoolStats.java
@@ -18,7 +18,7 @@ package com.gemstone.gemfire.internal.cache;
import com.gemstone.gemfire.*;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import static com.gemstone.gemfire.distributed.ConfigurationProperties.LOCATORS;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/HeapMemoryMonitor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/HeapMemoryMonitor.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/HeapMemoryMonitor.java
index bc83335..eeaad42 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/HeapMemoryMonitor.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/HeapMemoryMonitor.java
@@ -22,10 +22,10 @@ import com.gemstone.gemfire.cache.CacheClosedException;
import com.gemstone.gemfire.cache.query.internal.QueryMonitor;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
-import com.gemstone.gemfire.internal.GemFireStatSampler;
-import com.gemstone.gemfire.internal.LocalStatListener;
+import com.gemstone.gemfire.internal.statistics.GemFireStatSampler;
+import com.gemstone.gemfire.internal.statistics.LocalStatListener;
import com.gemstone.gemfire.internal.SetUtils;
-import com.gemstone.gemfire.internal.StatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsImpl;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.control.InternalResourceManager.ResourceType;
import com.gemstone.gemfire.internal.cache.control.MemoryThresholds.MemoryState;
@@ -759,7 +759,7 @@ public void stopMonitoring() {
class LocalHeapStatListener implements LocalStatListener {
/* (non-Javadoc)
- * @see com.gemstone.gemfire.internal.LocalStatListener#statValueChanged(double)
+ * @see com.gemstone.gemfire.internal.statistics.LocalStatListener#statValueChanged(double)
*/
@Override
@SuppressWarnings("synthetic-access")
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/ResourceManagerStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/ResourceManagerStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/ResourceManagerStats.java
index d54e7c4..3281273 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/ResourceManagerStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/control/ResourceManagerStats.java
@@ -23,7 +23,7 @@ import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.distributed.internal.PoolStatHelper;
import com.gemstone.gemfire.distributed.internal.QueueStatHelper;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* Contains methods for manipulating resource manager statistics.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionServiceStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionServiceStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionServiceStats.java
index e62d800..b4ad43b 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionServiceStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionServiceStats.java
@@ -22,8 +22,8 @@ import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
-import com.gemstone.gemfire.internal.DummyStatisticsImpl;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.DummyStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
public class FunctionServiceStats {
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionStats.java
index 0e7687a..88a8b10 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/execute/FunctionStats.java
@@ -20,9 +20,8 @@ import com.gemstone.gemfire.*;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
import com.gemstone.gemfire.distributed.internal.DistributionStats;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
-import com.gemstone.gemfire.internal.DummyStatisticsImpl;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
-import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
+import com.gemstone.gemfire.internal.statistics.DummyStatisticsImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
public class FunctionStats {
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/ha/HARegionQueueStats.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/ha/HARegionQueueStats.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/ha/HARegionQueueStats.java
index e7b74d1..150c080 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/ha/HARegionQueueStats.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/ha/HARegionQueueStats.java
@@ -21,7 +21,7 @@ import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
/**
* This class tracks GemFire statistics related to a {@link HARegionQueue}.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/HeapLRUCapacityController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/HeapLRUCapacityController.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/HeapLRUCapacityController.java
index 7bf2d1f..a2a7be1 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/HeapLRUCapacityController.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/HeapLRUCapacityController.java
@@ -25,7 +25,7 @@ import com.gemstone.gemfire.cache.EvictionAlgorithm;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.util.ObjectSizer;
import com.gemstone.gemfire.distributed.internal.DistributionConfig;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.*;
import com.gemstone.gemfire.internal.cache.control.InternalResourceManager;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/LRUCapacityController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/LRUCapacityController.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/LRUCapacityController.java
index 0e5afab..ffbc4ad 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/LRUCapacityController.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/LRUCapacityController.java
@@ -18,7 +18,7 @@ package com.gemstone.gemfire.internal.cache.lru;
import com.gemstone.gemfire.*;
import com.gemstone.gemfire.cache.*;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.*;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/MemLRUCapacityController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/MemLRUCapacityController.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/MemLRUCapacityController.java
index d1634b4..6cfa582 100644
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/MemLRUCapacityController.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/lru/MemLRUCapacityController.java
@@ -29,7 +29,7 @@ import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.util.ObjectSizer;
import com.gemstone.gemfire.internal.ClassPathLoader;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.AbstractLRURegionMap.CDValueWrapper;
import com.gemstone.gemfire.internal.cache.CachedDeserializableFactory;
import com.gemstone.gemfire.internal.cache.Token;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifier.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifier.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifier.java
index edf3a94..6fd4560 100755
--- a/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifier.java
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/cache/tier/sockets/CacheClientNotifier.java
@@ -81,7 +81,7 @@ import com.gemstone.gemfire.distributed.internal.MessageWithReply;
import com.gemstone.gemfire.distributed.internal.ReplyMessage;
import com.gemstone.gemfire.distributed.internal.ReplyProcessor21;
import com.gemstone.gemfire.internal.ClassLoadUtil;
-import com.gemstone.gemfire.internal.DummyStatisticsFactory;
+import com.gemstone.gemfire.internal.statistics.DummyStatisticsFactory;
import com.gemstone.gemfire.internal.InternalDataSerializer;
import com.gemstone.gemfire.internal.InternalInstantiator;
import com.gemstone.gemfire.internal.SocketCloser;
[23/24] incubator-geode git commit: GEODE-1781: exclude
LinuxProcFsStatistics$CPU from AnaylzeSerializableJUnitTest
Posted by kl...@apache.org.
GEODE-1781: exclude LinuxProcFsStatistics$CPU from AnaylzeSerializableJUnitTest
Project: http://git-wip-us.apache.org/repos/asf/incubator-geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-geode/commit/55c5df5e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-geode/tree/55c5df5e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-geode/diff/55c5df5e
Branch: refs/heads/feature/GEODE-1781-02
Commit: 55c5df5e4cd6228be1617fb1e92d8d955a703b08
Parents: 7dc1ce6
Author: Kirk Lund <kl...@apache.org>
Authored: Tue Aug 16 09:25:33 2016 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Wed Aug 17 15:44:52 2016 -0700
----------------------------------------------------------------------
.../resources/com/gemstone/gemfire/codeAnalysis/excludedClasses.txt | 1 +
1 file changed, 1 insertion(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/55c5df5e/geode-core/src/test/resources/com/gemstone/gemfire/codeAnalysis/excludedClasses.txt
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/com/gemstone/gemfire/codeAnalysis/excludedClasses.txt b/geode-core/src/test/resources/com/gemstone/gemfire/codeAnalysis/excludedClasses.txt
index 9d880f5..ddacf99 100644
--- a/geode-core/src/test/resources/com/gemstone/gemfire/codeAnalysis/excludedClasses.txt
+++ b/geode-core/src/test/resources/com/gemstone/gemfire/codeAnalysis/excludedClasses.txt
@@ -118,6 +118,7 @@ com/gemstone/gemfire/internal/security/IntegratedSecurityService
com/gemstone/gemfire/internal/security/IntegratedSecurityService$SerializationProxy
com/gemstone/gemfire/internal/security/SecurableComponent
com/gemstone/gemfire/internal/security/SecurityService
+com/gemstone/gemfire/internal/statistics/platform/LinuxProcFsStatistics$CPU
com/gemstone/org/apache/logging/log4j/core/config/xml/GemFireXmlConfiguration
com/gemstone/org/apache/logging/log4j/core/config/xml/GemFireXmlConfiguration$ErrorType
com/gemstone/gemfire/internal/ra/GFConnectionFactoryImpl
[13/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java
new file mode 100644
index 0000000..12637bc
--- /dev/null
+++ b/geode-core/src/main/java/com/gemstone/gemfire/internal/statistics/StatArchiveReader.java
@@ -0,0 +1,3339 @@
+/*
+ * 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 com.gemstone.gemfire.internal.statistics;
+
+import com.gemstone.gemfire.GemFireIOException;
+import com.gemstone.gemfire.InternalGemFireException;
+import com.gemstone.gemfire.internal.Assert;
+import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
+import com.gemstone.gemfire.internal.logging.DateFormatter;
+
+import java.io.BufferedInputStream;
+import java.io.DataInputStream;
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.text.DateFormat;
+import java.text.NumberFormat;
+import java.text.SimpleDateFormat;
+import java.util.AbstractList;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.SimpleTimeZone;
+import java.util.TimeZone;
+import java.util.zip.GZIPInputStream;
+
+/**
+ * StatArchiveReader provides APIs to read statistic snapshots from an archive
+ * file.
+ */
+public class StatArchiveReader implements StatArchiveFormat {
+
+ protected static final NumberFormat nf = NumberFormat.getNumberInstance();
+ static {
+ nf.setMaximumFractionDigits(2);
+ nf.setGroupingUsed(false);
+ }
+
+ private final StatArchiveFile[] archives;
+ private boolean dump;
+ private boolean closed = false;
+
+ /**
+ * Creates a StatArchiveReader that will read the named archive file.
+ * @param autoClose if its <code>true</code> then the reader will close
+ * input files as soon as it finds their end.
+ * @throws IOException if <code>archiveName</code> could not be opened
+ * read, or closed.
+ */
+ public StatArchiveReader(File[] archiveNames, ValueFilter[] filters, boolean autoClose)
+ throws IOException
+ {
+ this.archives = new StatArchiveFile[archiveNames.length];
+ this.dump = Boolean.getBoolean("StatArchiveReader.dumpall");
+ for (int i=0; i < archiveNames.length; i++) {
+ this.archives[i] = new StatArchiveFile(this, archiveNames[i], dump, filters);
+ }
+
+ update(false, autoClose);
+
+ if (this.dump || Boolean.getBoolean("StatArchiveReader.dump")) {
+ this.dump(new PrintWriter(System.out));
+ }
+ }
+
+ /**
+ * Creates a StatArchiveReader that will read the named archive file.
+ * @throws IOException if <code>archiveName</code> could not be opened
+ * read, or closed.
+ */
+ public StatArchiveReader(String archiveName) throws IOException {
+ this(new File[]{new File(archiveName)}, null, false);
+ }
+
+ /**
+ * Returns an array of stat values that match the specified spec.
+ * If nothing matches then an empty array is returned.
+ */
+ public StatValue[] matchSpec(StatSpec spec) {
+ if (spec.getCombineType() == StatSpec.GLOBAL) {
+ StatValue[] allValues = matchSpec(new RawStatSpec(spec));
+ if (allValues.length == 0) {
+ return allValues;
+ } else {
+ ComboValue cv = new ComboValue(allValues);
+ // need to save this in reader's combo value list
+ return new StatValue[]{cv};
+ }
+ } else {
+ List l = new ArrayList();
+ StatArchiveReader.StatArchiveFile[] archives = getArchives();
+ for (int i=0; i < archives.length; i++) {
+ StatArchiveFile f = archives[i];
+ if (spec.archiveMatches(f.getFile())) {
+ f.matchSpec(spec, l);
+ }
+ }
+ StatValue[] result = new StatValue[l.size()];
+ return (StatValue[])l.toArray(result);
+ }
+ }
+
+ /**
+ * Checks to see if any archives have changed since the StatArchiverReader
+ * instance was created or last updated. If an archive has additional
+ * samples then those are read the resource instances maintained by the
+ * reader are updated.
+ * <p>Once closed a reader can no longer be updated.
+ * @return true if update read some new data.
+ * @throws IOException if an archive could not be opened
+ * read, or closed.
+ */
+ public boolean update() throws IOException {
+ return update(true, false);
+ }
+ private boolean update(boolean doReset, boolean autoClose) throws IOException {
+ if (this.closed) {
+ return false;
+ }
+ boolean result = false;
+ StatArchiveReader.StatArchiveFile[] archives = getArchives();
+ for (int i=0; i < archives.length; i++) {
+ StatArchiveFile f = archives[i];
+ if (f.update(doReset)) {
+ result = true;
+ }
+ if (autoClose) {
+ f.close();
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Returns an unmodifiable list of all the {@link ResourceInst}
+ * this reader contains.
+ */
+ public List getResourceInstList() {
+ return new ResourceInstList();
+ }
+
+ public StatArchiveFile[] getArchives() {
+ return this.archives;
+ }
+
+ /**
+ * Closes all archives.
+ */
+ public void close() throws IOException {
+ if (!this.closed) {
+ StatArchiveReader.StatArchiveFile[] archives = getArchives();
+ for (int i=0; i < archives.length; i++) {
+ StatArchiveFile f = archives[i];
+ f.close();
+ }
+ this.closed = true;
+ }
+ }
+
+ private int getMemoryUsed() {
+ int result = 0;
+ StatArchiveReader.StatArchiveFile[] archives = getArchives();
+ for (int i=0; i < archives.length; i++) {
+ StatArchiveFile f = archives[i];
+ result += f.getMemoryUsed();
+ }
+ return result;
+ }
+
+ private void dump(PrintWriter stream) {
+ StatArchiveReader.StatArchiveFile[] archives = getArchives();
+ for (int i=0; i < archives.length; i++) {
+ StatArchiveFile f = archives[i];
+ f.dump(stream);
+ }
+ }
+
+ protected static double bitsToDouble(int type, long bits) {
+ switch (type) {
+ case BOOLEAN_CODE:
+ case BYTE_CODE:
+ case CHAR_CODE:
+ case WCHAR_CODE:
+ case SHORT_CODE:
+ case INT_CODE:
+ case LONG_CODE:
+ return bits;
+ case FLOAT_CODE:
+ return Float.intBitsToFloat((int)bits);
+ case DOUBLE_CODE:
+ return Double.longBitsToDouble(bits);
+ default:
+ throw new InternalGemFireException(LocalizedStrings.StatArchiveReader_UNEXPECTED_TYPECODE_0.toLocalizedString(Integer.valueOf(type)));
+ }
+ }
+
+ /**
+ * Simple utility to read and dump statistic archive.
+ */
+ public static void main(String args[]) throws IOException {
+ String archiveName = null;
+ if (args.length > 1) {
+ System.err.println("Usage: [archiveName]");
+ System.exit(1);
+ } else if (args.length == 1) {
+ archiveName = args[0];
+ } else {
+ archiveName = "statArchive.gfs";
+ }
+ StatArchiveReader reader = new StatArchiveReader(archiveName);
+ System.out.println("DEBUG: memory used = " + reader.getMemoryUsed());
+ reader.close();
+ }
+
+ /**
+ * Wraps an instance of StatSpec but alwasy returns a combine type of NONE.
+ */
+ private static class RawStatSpec implements StatSpec {
+ private final StatSpec spec;
+ RawStatSpec(StatSpec wrappedSpec) {
+ this.spec = wrappedSpec;
+ }
+ public int getCombineType() {
+ return StatSpec.NONE;
+ }
+ public boolean typeMatches(String typeName) {
+ return spec.typeMatches(typeName);
+ }
+ public boolean statMatches(String statName) {
+ return spec.statMatches(statName);
+ }
+ public boolean instanceMatches(String textId, long numericId) {
+ return spec.instanceMatches(textId, numericId);
+ }
+ public boolean archiveMatches(File archive) {
+ return spec.archiveMatches(archive);
+ }
+ }
+
+ private class ResourceInstList extends AbstractList {
+ protected ResourceInstList() {
+ // nothing needed.
+ }
+ @Override
+ public Object get(int idx) {
+ int archiveIdx = 0;
+ StatArchiveReader.StatArchiveFile[] archives = getArchives();
+ for (int i=0; i < archives.length; i++) {
+ StatArchiveFile f = archives[i];
+ if (idx < (archiveIdx + f.resourceInstSize)) {
+ return f.resourceInstTable[idx - archiveIdx];
+ }
+ archiveIdx += f.resourceInstSize;
+ }
+ return null;
+ }
+ @Override
+ public int size() {
+ int result = 0;
+ StatArchiveReader.StatArchiveFile[] archives = getArchives();
+ for (int i=0; i < archives.length; i++) {
+ result += archives[i].resourceInstSize;
+ }
+ return result;
+ }
+ }
+
+ /**
+ * Describes a single statistic.
+ */
+ public static class StatDescriptor {
+ private boolean loaded;
+ private String name;
+ private final int offset;
+ private final boolean isCounter;
+ private final boolean largerBetter;
+ private final byte typeCode;
+ private String units;
+ private String desc;
+
+ protected void dump(PrintWriter stream) {
+ stream.println(" " + name + ": type=" + typeCode + " offset=" + offset
+ + (isCounter? " counter" : "")
+ + " units=" + units
+ + " largerBetter=" + largerBetter
+ + " desc=" + desc);
+ }
+
+ protected StatDescriptor(String name, int offset, boolean isCounter,
+ boolean largerBetter,
+ byte typeCode, String units, String desc) {
+ this.loaded = true;
+ this.name = name;
+ this.offset = offset;
+ this.isCounter = isCounter;
+ this.largerBetter = largerBetter;
+ this.typeCode = typeCode;
+ this.units = units;
+ this.desc = desc;
+ }
+ public boolean isLoaded() {
+ return this.loaded;
+ }
+ void unload() {
+ this.loaded = false;
+ this.name = null;
+ this.units = null;
+ this.desc = null;
+ }
+ /**
+ * Returns the type code of this statistic.
+ * It will be one of the following values:
+ * <ul>
+ * <li> {@link #BOOLEAN_CODE}
+ * <li> {@link #WCHAR_CODE}
+ * <li> {@link #CHAR_CODE}
+ * <li> {@link #BYTE_CODE}
+ * <li> {@link #SHORT_CODE}
+ * <li> {@link #INT_CODE}
+ * <li> {@link #LONG_CODE}
+ * <li> {@link #FLOAT_CODE}
+ * <li> {@link #DOUBLE_CODE}
+ * </ul>
+ */
+ public byte getTypeCode() {
+ return this.typeCode;
+ }
+ /**
+ * Returns the name of this statistic.
+ */
+ public String getName() {
+ return this.name;
+ }
+ /**
+ * Returns true if this statistic's value will always increase.
+ */
+ public boolean isCounter() {
+ return this.isCounter;
+ }
+ /**
+ * Returns true if larger values indicate better performance.
+ */
+ public boolean isLargerBetter() {
+ return this.largerBetter;
+ }
+ /**
+ * Returns a string that describes the units this statistic measures.
+ */
+ public String getUnits() {
+ return this.units;
+ }
+ /**
+ * Returns a textual description of this statistic.
+ */
+ public String getDescription() {
+ return this.desc;
+ }
+ /**
+ * Returns the offset of this stat in its type.
+ */
+ public int getOffset() {
+ return this.offset;
+ }
+ }
+
+ public static interface StatValue {
+ /**
+ * {@link StatArchiveReader.StatValue} filter that causes the
+ * statistic values to be unfiltered. This causes the raw values
+ * written to the archive to be used.
+ * <p>This is the default filter for non-counter statistics.
+ * To determine if a statistic is not a counter use {@link StatArchiveReader.StatDescriptor#isCounter}. */
+ public static final int FILTER_NONE = 0;
+ /**
+ * {@link StatArchiveReader.StatValue} filter that causes the
+ * statistic values to be filtered to reflect how often they
+ * change per second. Since the difference between two samples is
+ * used to calculate the value this causes the {@link StatArchiveReader.StatValue}
+ * to have one less sample than {@link #FILTER_NONE}. The instance
+ * time stamp that does not have a per second value is the
+ * instance's first time stamp {@link
+ * StatArchiveReader.ResourceInst#getFirstTimeMillis}.
+ * <p>This is the default filter for counter statistics.
+ * To determine if a statistic is a counter use {@link StatArchiveReader.StatDescriptor#isCounter}. */
+ public static final int FILTER_PERSEC = 1;
+ /**
+ * {@link StatArchiveReader.StatValue} filter that causes the
+ * statistic values to be filtered to reflect how much they
+ * changed between sample periods. Since the difference between
+ * two samples is used to calculate the value this causes the
+ * {@link StatArchiveReader.StatValue} to have one less sample than {@link
+ * #FILTER_NONE}. The instance time stamp that does not have a per
+ * second value is the instance's first time stamp {@link
+ * StatArchiveReader.ResourceInst#getFirstTimeMillis}.
+ */
+ public static final int FILTER_PERSAMPLE = 2;
+ /**
+ * Creates and returns a trimmed version of this stat value.
+ * Any samples taken before <code>startTime</code> and after
+ * <code>endTime</code> are discarded from the resulting value.
+ * Set a time parameter to <code>-1</code> to not trim that side.
+ */
+ public StatValue createTrimmed(long startTime, long endTime);
+ /**
+ * Returns true if value has data that has been trimmed off it
+ * by a start timestamp.
+ */
+ public boolean isTrimmedLeft();
+ /**
+ * Gets the {@link StatArchiveReader.ResourceType type} of the
+ * resources that this value belongs to.
+ */
+ public ResourceType getType();
+ /**
+ * Gets the {@link StatArchiveReader.ResourceInst resources} that this value
+ * belongs to.
+ */
+ public ResourceInst[] getResources();
+ /**
+ * Returns an array of timestamps for each unfiltered snapshot in this value.
+ * Each returned time stamp is the number of millis since
+ * midnight, Jan 1, 1970 UTC.
+ */
+ public long[] getRawAbsoluteTimeStamps();
+ /**
+ * Returns an array of timestamps for each unfiltered snapshot in this value.
+ * Each returned time stamp is the number of millis since
+ * midnight, Jan 1, 1970 UTC.
+ * The resolution is seconds.
+ */
+ public long[] getRawAbsoluteTimeStampsWithSecondRes();
+ /**
+ * Returns an array of doubles containing the unfiltered value of this
+ * statistic for each point in time that it was sampled.
+ */
+ public double[] getRawSnapshots();
+ /**
+ * Returns an array of doubles containing the filtered value of this
+ * statistic for each point in time that it was sampled.
+ */
+ public double[] getSnapshots();
+ /**
+ * Returns the number of samples taken of this statistic's value.
+ */
+ public int getSnapshotsSize();
+ /**
+ * Returns the smallest of all the samples taken of this statistic's value.
+ */
+ public double getSnapshotsMinimum();
+ /**
+ * Returns the largest of all the samples taken of this statistic's value.
+ */
+ public double getSnapshotsMaximum();
+ /**
+ * Returns the average of all the samples taken of this statistic's value.
+ */
+ public double getSnapshotsAverage();
+ /**
+ * Returns the standard deviation of all the samples taken of this statistic's value.
+ */
+ public double getSnapshotsStandardDeviation();
+ /**
+ * Returns the most recent value of all the samples taken of this statistic's value.
+ */
+ public double getSnapshotsMostRecent();
+ /**
+ * Returns true if sample whose value was different from previous values
+ * has been added to this StatValue since the last time this method was
+ * called.
+ */
+ public boolean hasValueChanged();
+ /**
+ * Returns the current filter used to calculate this statistic's values.
+ * It will be one of these values:
+ * <ul>
+ * <li> {@link #FILTER_NONE}
+ * <li> {@link #FILTER_PERSAMPLE}
+ * <li> {@link #FILTER_PERSEC}
+ * </ul>
+ */
+ public int getFilter();
+ /**
+ * Sets the current filter used to calculate this statistic's values.
+ * The default filter is {@link #FILTER_NONE} unless the statistic
+ * is a counter, {@link StatArchiveReader.StatDescriptor#isCounter},
+ * in which case its {@link #FILTER_PERSEC}.
+ * @param filter It must be one of these values:
+ * <ul>
+ * <li> {@link #FILTER_NONE}
+ * <li> {@link #FILTER_PERSAMPLE}
+ * <li> {@link #FILTER_PERSEC}
+ * </ul>
+ * @throws IllegalArgumentException if <code>filter</code> is not a valid filter constant.
+ */
+ public void setFilter(int filter);
+ /**
+ * Returns a description of this statistic.
+ */
+ public StatDescriptor getDescriptor();
+ }
+
+ protected static abstract class AbstractValue implements StatValue {
+ protected StatDescriptor descriptor;
+ protected int filter;
+
+ protected long startTime = -1;
+ protected long endTime = -1;
+
+ protected boolean statsValid = false;
+ protected int size;
+ protected double min;
+ protected double max;
+ protected double avg;
+ protected double stddev;
+ protected double mostRecent;
+
+ public void calcStats() {
+ if (!statsValid) {
+ getSnapshots();
+ }
+ }
+
+ public int getSnapshotsSize() {
+ calcStats();
+ return this.size;
+ }
+ public double getSnapshotsMinimum() {
+ calcStats();
+ return this.min;
+ }
+ public double getSnapshotsMaximum() {
+ calcStats();
+ return this.max;
+ }
+ public double getSnapshotsAverage() {
+ calcStats();
+ return this.avg;
+ }
+ public double getSnapshotsStandardDeviation() {
+ calcStats();
+ return this.stddev;
+ }
+ public double getSnapshotsMostRecent() {
+ calcStats();
+ return this.mostRecent;
+ }
+ public StatDescriptor getDescriptor() {
+ return this.descriptor;
+ }
+ public int getFilter() {
+ return this.filter;
+ }
+
+ public void setFilter(int filter) {
+ if (filter != this.filter) {
+ if (filter != FILTER_NONE
+ && filter != FILTER_PERSEC
+ && filter != FILTER_PERSAMPLE) {
+ throw new IllegalArgumentException(LocalizedStrings.StatArchiveReader_FILTER_VALUE_0_MUST_BE_1_2_OR_3
+ .toLocalizedString(
+ new Object[] {
+ Integer.valueOf(filter),
+ Integer.valueOf(FILTER_NONE),
+ Integer.valueOf(FILTER_PERSEC),
+ Integer.valueOf(FILTER_PERSAMPLE)}));
+ }
+ this.filter = filter;
+ this.statsValid = false;
+ }
+ }
+
+ /**
+ * Calculates each stat given the result of calling getSnapshots
+ */
+ protected void calcStats(double[] values) {
+ if (statsValid) {
+ return;
+ }
+ size = values.length;
+ if (size == 0) {
+ min = 0.0;
+ max = 0.0;
+ avg = 0.0;
+ stddev = 0.0;
+ mostRecent = 0.0;
+ } else {
+ min = values[0];
+ max = values[0];
+ mostRecent = values[values.length-1];
+ double total = values[0];
+ for (int i=1; i < size; i++) {
+ total += values[i];
+ if (values[i] < min) {
+ min = values[i];
+ } else if (values[i] > max) {
+ max = values[i];
+ }
+ }
+ avg = total / size;
+ stddev = 0.0;
+ if (size > 1) {
+ for (int i=0; i < size; i++) {
+ double dv = values[i] - avg;
+ stddev += (dv*dv);
+ }
+ stddev /= (size - 1);
+ stddev = Math.sqrt(stddev);
+ }
+ }
+ statsValid = true;
+ }
+
+ /**
+ * Returns a string representation of this object.
+ */
+ @Override
+ public String toString() {
+ calcStats();
+ StringBuffer result = new StringBuffer();
+ result.append(getDescriptor().getName());
+ String units = getDescriptor().getUnits();
+ if (units != null && units.length() > 0) {
+ result.append(' ').append(units);
+ }
+ if (filter == FILTER_PERSEC) {
+ result.append("/sec");
+ } else if (filter == FILTER_PERSAMPLE) {
+ result.append("/sample");
+ }
+ result.append(": samples=")
+ .append(getSnapshotsSize());
+ if (startTime != -1) {
+ result.append(" startTime=\"")
+ .append(new Date(startTime))
+ .append("\"");
+ }
+ if (endTime != -1) {
+ result.append(" endTime=\"")
+ .append(new Date(endTime))
+ .append("\"");
+ }
+ result.append(" min=")
+ .append(nf.format(min));
+ result.append(" max=")
+ .append(nf.format(max));
+ result.append(" average=")
+ .append(nf.format(avg));
+ result.append(" stddev=")
+ .append(nf.format(stddev));
+ result.append(" last=") // for bug 42532
+ .append(nf.format(mostRecent));
+ return result.toString();
+ }
+ }
+
+ /**
+ * A ComboValue is a value that is the logical combination of
+ * a set of other stat values.
+ * <p> For now ComboValue has a simple implementation that does not
+ * suppport updates.
+ */
+ private static class ComboValue extends AbstractValue {
+ private final ResourceType type;
+ private final StatValue[] values;
+ /**
+ * Creates a ComboValue by adding all the specified values together.
+ */
+ ComboValue(List valueList) {
+ this((StatValue[])valueList.toArray(new StatValue[valueList.size()]));
+ }
+ /**
+ * Creates a ComboValue by adding all the specified values together.
+ */
+ ComboValue(StatValue[] values) {
+ this.values = values;
+ this.filter = this.values[0].getFilter();
+ String typeName = this.values[0].getType().getName();
+ String statName = this.values[0].getDescriptor().getName();
+ int bestTypeIdx = 0;
+ for (int i=1; i < this.values.length; i++) {
+ if (this.filter != this.values[i].getFilter()) {
+ /* I'm not sure why this would happen.
+ * If it really can happen then this code should change
+ * the filter since a client has no way to select values
+ * based on the filter.
+ */
+ throw new IllegalArgumentException(LocalizedStrings.StatArchiveReader_CANT_COMBINE_VALUES_WITH_DIFFERENT_FILTERS.toLocalizedString());
+ }
+ if (!typeName.equals(this.values[i].getType().getName())) {
+ throw new IllegalArgumentException(LocalizedStrings.StatArchiveReader_CANT_COMBINE_VALUES_WITH_DIFFERENT_TYPES.toLocalizedString());
+ }
+ if (!statName.equals(this.values[i].getDescriptor().getName())) {
+ throw new IllegalArgumentException(LocalizedStrings.StatArchiveReader_CANT_COMBINE_DIFFERENT_STATS.toLocalizedString());
+ }
+ if (this.values[i].getDescriptor().isCounter()) {
+ // its a counter which is not the default
+ if (!this.values[i].getDescriptor().isLargerBetter()) {
+ // this guy has non-defaults for both use him
+ bestTypeIdx = i;
+ } else if (this.values[bestTypeIdx].getDescriptor().isCounter()
+ == this.values[bestTypeIdx].getDescriptor().isLargerBetter()) {
+ // as long as we haven't already found a guy with defaults
+ // make this guy the best type
+ bestTypeIdx = i;
+ }
+ } else {
+ // its a gauge, see if it has a non-default largerBetter
+ if (this.values[i].getDescriptor().isLargerBetter()) {
+ // as long as we haven't already found a guy with defaults
+ if (this.values[bestTypeIdx].getDescriptor().isCounter()
+ == this.values[bestTypeIdx].getDescriptor().isLargerBetter()) {
+ // make this guy the best type
+ bestTypeIdx = i;
+ }
+ }
+ }
+ }
+ this.type = this.values[bestTypeIdx].getType();
+ this.descriptor = this.values[bestTypeIdx].getDescriptor();
+ }
+ private ComboValue(ComboValue original, long startTime, long endTime) {
+ this.startTime = startTime;
+ this.endTime = endTime;
+ this.type = original.getType();
+ this.descriptor = original.getDescriptor();
+ this.filter = original.getFilter();
+ this.values = new StatValue[original.values.length];
+ for (int i=0; i < this.values.length; i++) {
+ this.values[i] = original.values[i].createTrimmed(startTime, endTime);
+ }
+ }
+ public StatValue createTrimmed(long startTime, long endTime) {
+ if (startTime == this.startTime && endTime == this.endTime) {
+ return this;
+ } else {
+ return new ComboValue(this, startTime, endTime);
+ }
+ }
+ public ResourceType getType() {
+ return this.type;
+ }
+ public ResourceInst[] getResources() {
+ Set set = new HashSet();
+ for (int i=0; i < values.length; i++) {
+ set.addAll(Arrays.asList(values[i].getResources()));
+ }
+ ResourceInst[] result = new ResourceInst[set.size()];
+ return (ResourceInst[])set.toArray(result);
+ }
+ public boolean hasValueChanged() {
+ return true;
+ }
+
+ public static boolean closeEnough(long v1, long v2, long delta) {
+ return (v1 == v2) || ((Math.abs(v1-v2)/2) <= delta);
+ }
+ /**
+ * Return true if v is closer to prev.
+ * Return false if v is closer to next.
+ * Return true if v is the same distance from both.
+ */
+ public static boolean closer(long v, long prev, long next) {
+ return Math.abs(v-prev) <= Math.abs(v-next);
+ }
+
+
+ /**
+ * Return true if the current ts must be inserted instead of
+ * being mapped to the tsAtInsertPoint
+ */
+ private static boolean mustInsert(int nextIdx, long[] valueTimeStamps, long tsAtInsertPoint) {
+ return (nextIdx < valueTimeStamps.length)
+ && (valueTimeStamps[nextIdx] <= tsAtInsertPoint);
+ }
+
+ public long[] getRawAbsoluteTimeStampsWithSecondRes() {
+ return getRawAbsoluteTimeStamps();
+ }
+
+ public long[] getRawAbsoluteTimeStamps() {
+ if (values.length == 0) {
+ return new long[0];
+ }
+// for (int i=0; i < values.length; i++) {
+// System.out.println("DEBUG: inst# " + i + " has "
+// + values[i].getRawAbsoluteTimeStamps().length
+// + " timestamps");
+// }
+ long[] valueTimeStamps = values[0].getRawAbsoluteTimeStamps();
+ int tsCount = valueTimeStamps.length + 1;
+ long[] ourTimeStamps = new long[(tsCount*2) + 1];
+ System.arraycopy(valueTimeStamps, 0, ourTimeStamps, 0, valueTimeStamps.length);
+ // Note we add a MAX sample to make the insert logic simple
+ ourTimeStamps[valueTimeStamps.length] = Long.MAX_VALUE;
+ for (int i=1; i < values.length; i++) {
+ valueTimeStamps = values[i].getRawAbsoluteTimeStamps();
+ if (valueTimeStamps.length == 0) {
+ continue;
+ }
+ int ourIdx = 0;
+ int j=0;
+ long tsToInsert = valueTimeStamps[0] - 1000; // default to 1 second
+ if (valueTimeStamps.length > 1) {
+ tsToInsert = valueTimeStamps[0] - (valueTimeStamps[1] - valueTimeStamps[0]);
+ }
+ // tsToInsert is now initialized to a value that we can pretend
+ // was the previous timestamp inserted.
+ while (j < valueTimeStamps.length) {
+ long timeDelta = (valueTimeStamps[j] - tsToInsert) / 2;
+ tsToInsert = valueTimeStamps[j];
+ long tsAtInsertPoint = ourTimeStamps[ourIdx];
+ while (tsToInsert > tsAtInsertPoint
+ && !closeEnough(tsToInsert, tsAtInsertPoint, timeDelta)) {
+// System.out.println("DEBUG: skipping " + ourIdx + " because it was not closeEnough");
+ ourIdx++;
+ tsAtInsertPoint = ourTimeStamps[ourIdx];
+ }
+ if (closeEnough(tsToInsert, tsAtInsertPoint, timeDelta)
+ && !mustInsert(j+1, valueTimeStamps, tsAtInsertPoint)) {
+ // It was already in our list so just go to the next one
+ j++;
+ ourIdx++; // never put the next timestamp at this index
+ while (!closer(tsToInsert, ourTimeStamps[ourIdx-1], ourTimeStamps[ourIdx])
+ && !mustInsert(j, valueTimeStamps, ourTimeStamps[ourIdx])) {
+// System.out.println("DEBUG: skipping mergeTs[" + (ourIdx-1) + "]="
+// + tsAtInsertPoint + " because it was closer to the next one");
+ ourIdx++; // it is closer to the next one so skip forward on more
+ }
+ } else {
+ // its not in our list so add it
+ int endRunIdx=j+1;
+ while (endRunIdx < valueTimeStamps.length
+ && valueTimeStamps[endRunIdx] < tsAtInsertPoint
+ && !closeEnough(valueTimeStamps[endRunIdx], tsAtInsertPoint, timeDelta)) {
+ endRunIdx++;
+ }
+ int numToCopy = endRunIdx - j;
+// System.out.println("DEBUG: tsToInsert=" + tsToInsert
+// + " tsAtInsertPoint=" + tsAtInsertPoint
+// + " timeDelta=" + timeDelta
+// + " vDelta=" + (Math.abs(tsToInsert-tsAtInsertPoint)/2)
+// + " numToCopy=" + numToCopy);
+// if (j > 0) {
+// System.out.println("DEBUG: prevTsToInsert=" + valueTimeStamps[j-1]);
+// }
+// if (ourIdx > 0) {
+// System.out.println("DEBUG ourTimeStamps[" + (ourIdx-1) + "]=" + ourTimeStamps[ourIdx-1]);
+// }
+
+// if (numToCopy > 1) {
+// System.out.println("DEBUG: endRunTs=" + valueTimeStamps[endRunIdx-1]);
+// }
+ if (tsCount+numToCopy > ourTimeStamps.length) {
+ // grow our timestamp array
+ long[] tmp = new long[(tsCount+numToCopy)*2];
+ System.arraycopy(ourTimeStamps, 0, tmp, 0, tsCount);
+ ourTimeStamps = tmp;
+ }
+ // make room for insert
+ System.arraycopy(ourTimeStamps, ourIdx,
+ ourTimeStamps, ourIdx+numToCopy,
+ tsCount-ourIdx);
+ // insert the elements
+ if (numToCopy == 1) {
+ ourTimeStamps[ourIdx] = valueTimeStamps[j];
+ } else {
+ System.arraycopy(valueTimeStamps, j,
+ ourTimeStamps, ourIdx,
+ numToCopy);
+ }
+ ourIdx += numToCopy;
+ tsCount += numToCopy;
+ // skip over all inserted elements
+ j += numToCopy;
+ }
+// System.out.println("DEBUG: inst #" + i
+// + " valueTs[" + (j-1) + "]=" + tsToInsert
+// + " found/inserted at"
+// + " mergeTs[" + (ourIdx-1) + "]=" + ourTimeStamps[ourIdx-1]);
+ }
+ }
+// for (int i=0; i < tsCount; i++) {
+// System.out.println("DEBUG: mergedTs[" + i + "]=" + ourTimeStamps[i]);
+// if (i > 0 && ourTimeStamps[i] <= ourTimeStamps[i-1]) {
+// System.out.println("DEBUG: ERROR ts was not greater than previous");
+// }
+// }
+ // Now make one more pass over all the timestamps and make sure they
+ // will all fit into the current merged timestamps in ourTimeStamps
+// boolean changed;
+// do {
+// changed = false;
+// for (int i=0; i < values.length; i++) {
+// valueTimeStamps = values[i].getRawAbsoluteTimeStamps();
+// if (valueTimeStamps.length == 0) {
+// continue;
+// }
+// int ourIdx = 0;
+// for (int j=0; j < valueTimeStamps.length; j++) {
+// while ((ourIdx < (tsCount-1))
+// && !isClosest(valueTimeStamps[j], ourTimeStamps, ourIdx)) {
+// ourIdx++;
+// }
+// if (ourIdx == (tsCount-1)) {
+// // we are at the end so we need to append all our remaining stamps [j..valueTimeStamps.length-1]
+// // and then reappend the Long.MAX_VALUE that
+// // is currently at tsCount-1
+// int numToCopy = valueTimeStamps.length - j;
+// if (tsCount+numToCopy > ourTimeStamps.length) {
+// // grow our timestamp array
+// long[] tmp = new long[tsCount+numToCopy+1];
+// System.arraycopy(ourTimeStamps, 0, tmp, 0, tsCount);
+// ourTimeStamps = tmp;
+// }
+// System.arraycopy(valueTimeStamps, j,
+// ourTimeStamps, ourIdx,
+// numToCopy);
+// tsCount += numToCopy;
+// ourTimeStamps[tsCount-1] = Long.MAX_VALUE;
+// //changed = true;
+// System.out.println("DEBUG: had to add " + numToCopy
+// + " timestamps for inst#" + i + " starting at index " + j + " starting with ts=" + valueTimeStamps[j]);
+// break; // our of the for j loop since we just finished off this guy
+// } else {
+// ourIdx++;
+// }
+// }
+// }
+// } while (changed);
+ // remove the max ts we added
+ tsCount--;
+ {
+ int startIdx = 0;
+ int endIdx = tsCount-1;
+ if (startTime != -1) {
+// for (int i=0; i < tsCount; i++) {
+// if (ourTimeStamps[i] >= startTime) {
+// break;
+// }
+// startIdx++;
+// }
+ Assert.assertTrue(ourTimeStamps[startIdx] >= startTime);
+ }
+ if (endTime != -1) {
+// endIdx = startIdx-1;
+// for (int i=startIdx; i < tsCount; i++) {
+// if (ourTimeStamps[i] >= endTime) {
+// break;
+// }
+// endIdx++;
+// }
+ Assert.assertTrue(endIdx == startIdx-1 || ourTimeStamps[endIdx] < endTime);
+ }
+ tsCount = (endIdx-startIdx) + 1;
+
+ // shrink and trim our timestamp array
+ long[] tmp = new long[tsCount];
+ System.arraycopy(ourTimeStamps, startIdx, tmp, 0, tsCount);
+ ourTimeStamps = tmp;
+ }
+ return ourTimeStamps;
+ }
+ public double[] getRawSnapshots() {
+ return getRawSnapshots(getRawAbsoluteTimeStamps());
+ }
+ /**
+ * Returns true if the timeStamp at curIdx is the one that ts is
+ * the closest to.
+ * We know that timeStamps[curIdx-1], if it exists, was not the closest.
+ */
+ private static boolean isClosest(long ts, long[] timeStamps, int curIdx) {
+ if (curIdx >= (timeStamps.length - 1)) {
+ // curIdx is the last one so it must be the closest
+ return true;
+ }
+ if (ts == timeStamps[curIdx]) {
+ return true;
+ }
+ return closer(ts, timeStamps[curIdx], timeStamps[curIdx+1]);
+ }
+
+ public boolean isTrimmedLeft() {
+ for (int i=0; i < this.values.length; i++) {
+ if (this.values[i].isTrimmedLeft()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private double[] getRawSnapshots(long[] ourTimeStamps) {
+ double[] result = new double[ourTimeStamps.length];
+// System.out.println("DEBUG: producing " + result.length + " values");
+ if (result.length > 0) {
+ for (int i=0; i < values.length; i++) {
+ long[] valueTimeStamps = values[i].getRawAbsoluteTimeStamps();
+ double[] valueSnapshots = values[i].getRawSnapshots();
+ double currentValue = 0.0;
+ int curIdx = 0;
+ if (values[i].isTrimmedLeft() && valueSnapshots.length > 0) {
+ currentValue = valueSnapshots[0];
+ }
+// System.out.println("DEBUG: inst#" + i + " has " + valueSnapshots.length + " values");
+ for (int j=0; j < valueSnapshots.length; j++) {
+// System.out.println("DEBUG: Doing v with"
+// + " vTs[" + j + "]=" + valueTimeStamps[j]
+// + " at mergeTs[" + curIdx + "]=" + ourTimeStamps[curIdx]);
+ while (!isClosest(valueTimeStamps[j], ourTimeStamps, curIdx)) {
+ if (descriptor.isCounter()) {
+ result[curIdx] += currentValue;
+ }
+// System.out.println("DEBUG: skipping curIdx=" + curIdx
+// + " valueTimeStamps[" + j + "]=" + valueTimeStamps[j]
+// + " ourTimeStamps[" + curIdx + "]=" + ourTimeStamps[curIdx]
+// + " ourTimeStamps[" + (curIdx+1) + "]=" + ourTimeStamps[curIdx+1]);
+
+ curIdx++;
+ }
+ if (curIdx >= result.length) {
+ // Add this to workaround bug 30288
+ int samplesSkipped = valueSnapshots.length - j;
+ StringBuffer msg = new StringBuffer(100);
+ msg.append("WARNING: dropping last ");
+ if (samplesSkipped == 1) {
+ msg.append("sample because it");
+ } else {
+ msg.append(samplesSkipped).append(" samples because they");
+ }
+ msg.append(" could not fit in the merged result.");
+ System.out.println(msg.toString());
+ break;
+ }
+ currentValue = valueSnapshots[j];
+ result[curIdx] += currentValue;
+ curIdx++;
+ }
+ if (descriptor.isCounter()) {
+ for (int j=curIdx; j < result.length; j++) {
+ result[j] += currentValue;
+ }
+ }
+ }
+ }
+ return result;
+ }
+ public double[] getSnapshots() {
+ double[] result;
+ if (filter != FILTER_NONE) {
+ long[] timestamps = getRawAbsoluteTimeStamps();
+ double[] snapshots = getRawSnapshots(timestamps);
+ if (snapshots.length <= 1) {
+ return new double[0];
+ }
+ result = new double[snapshots.length - 1];
+ for (int i=0; i < result.length; i++) {
+ double valueDelta = snapshots[i+1] - snapshots[i];
+ if (filter == FILTER_PERSEC) {
+ long timeDelta = timestamps[i+1] - timestamps[i];
+ result[i] = valueDelta / (timeDelta / 1000.0);
+// if (result[i] > valueDelta) {
+// System.out.println("DEBUG: timeDelta was " + timeDelta + " ms.");
+// System.out.println("DEBUG: valueDelta was " + valueDelta);
+// System.out.println("DEBUG: valueDelta/sec was " + result[i]);
+// }
+ } else {
+ result[i] = valueDelta;
+ }
+ }
+ } else {
+ result = getRawSnapshots();
+ }
+ calcStats(result);
+ return result;
+ }
+ }
+
+ /**
+ * Provides the value series related to a single statistics.
+ */
+ private static class SimpleValue extends AbstractValue {
+ private final ResourceInst resource;
+
+ private boolean useNextBits = false;
+ private long nextBits;
+ private final BitSeries series;
+ private boolean valueChangeNoticed = false;
+
+
+ public StatValue createTrimmed(long startTime, long endTime) {
+ if (startTime == this.startTime && endTime == this.endTime) {
+ return this;
+ } else {
+ return new SimpleValue(this, startTime, endTime);
+ }
+ }
+
+ protected SimpleValue(ResourceInst resource, StatDescriptor sd) {
+ this.resource = resource;
+ if (sd.isCounter()) {
+ this.filter = FILTER_PERSEC;
+ } else {
+ this.filter = FILTER_NONE;
+ }
+ this.descriptor = sd;
+ this.series = new BitSeries();
+ this.statsValid = false;
+ }
+
+ private SimpleValue(SimpleValue in, long startTime, long endTime) {
+ this.startTime = startTime;
+ this.endTime = endTime;
+ this.useNextBits = in.useNextBits;
+ this.nextBits = in.nextBits;
+ this.resource = in.resource;
+ this.series = in.series;
+ this.descriptor = in.descriptor;
+ this.filter = in.filter;
+ this.statsValid = false;
+ this.valueChangeNoticed = true;
+ }
+
+ public ResourceType getType() {
+ return this.resource.getType();
+ }
+
+ public ResourceInst[] getResources() {
+ return new ResourceInst[] {this.resource};
+ }
+
+ public boolean isTrimmedLeft() {
+ return getStartIdx() != 0;
+ }
+
+ private int getStartIdx() {
+ int startIdx = 0;
+ if (startTime != -1) {
+ long startTimeStamp = startTime - resource.getTimeBase();
+ long[] timestamps = resource.getAllRawTimeStamps();
+ for (int i=resource.getFirstTimeStampIdx();
+ i < resource.getFirstTimeStampIdx() + series.getSize();
+ i++) {
+ if (timestamps[i] >= startTimeStamp) {
+ break;
+ }
+ startIdx++;
+ }
+ }
+ return startIdx;
+ }
+ private int getEndIdx(int startIdx) {
+ int endIdx = series.getSize()-1;
+ if (endTime != -1) {
+ long endTimeStamp = endTime - resource.getTimeBase();
+ long[] timestamps = resource.getAllRawTimeStamps();
+ endIdx = startIdx-1;
+ for (int i=resource.getFirstTimeStampIdx()+startIdx;
+ i < resource.getFirstTimeStampIdx() + series.getSize();
+ i++) {
+ if (timestamps[i] >= endTimeStamp) {
+ break;
+ }
+ endIdx++;
+ }
+ Assert.assertTrue(endIdx == startIdx-1 || timestamps[endIdx] < endTimeStamp);
+ }
+ return endIdx;
+ }
+ public double[] getSnapshots() {
+ double[] result;
+ int startIdx = getStartIdx();
+ int endIdx = getEndIdx(startIdx);
+ int resultSize=(endIdx-startIdx) + 1;
+
+ if (filter != FILTER_NONE && resultSize > 1) {
+ long[] timestamps = null;
+ if (filter == FILTER_PERSEC) {
+ timestamps = resource.getAllRawTimeStamps();
+ }
+ result = new double[resultSize-1];
+ int tsIdx = resource.getFirstTimeStampIdx()+startIdx;
+ double[] values = series.getValuesEx(descriptor.getTypeCode(), startIdx, resultSize);
+ for (int i=0; i < result.length; i++) {
+ double valueDelta = values[i+1] - values[i];
+ if (filter == FILTER_PERSEC) {
+ double timeDelta = (timestamps[tsIdx+i+1] - timestamps[tsIdx+i]); // millis
+ valueDelta /= (timeDelta / 1000); // per second
+ }
+ result[i] = valueDelta;
+ }
+ } else {
+ result = series.getValuesEx(descriptor.getTypeCode(), startIdx, resultSize);
+ }
+ calcStats(result);
+ return result;
+ }
+
+ public double[] getRawSnapshots() {
+ int startIdx = getStartIdx();
+ int endIdx = getEndIdx(startIdx);
+ int resultSize=(endIdx-startIdx) + 1;
+ return series.getValuesEx(descriptor.getTypeCode(), startIdx, resultSize);
+ }
+
+ public long[] getRawAbsoluteTimeStampsWithSecondRes() {
+ long[] result = getRawAbsoluteTimeStamps();
+ for (int i=0; i < result.length; i++) {
+ result[i] += 500;
+ result[i] /= 1000;
+ result[i] *= 1000;
+ }
+ return result;
+ }
+
+ public long[] getRawAbsoluteTimeStamps() {
+ int startIdx = getStartIdx();
+ int endIdx = getEndIdx(startIdx);
+ int resultSize=(endIdx-startIdx) + 1;
+ if (resultSize <= 0) {
+ return new long[0];
+ } else {
+ long[] result = new long[resultSize];
+ long[] timestamps = resource.getAllRawTimeStamps();
+ int tsIdx = resource.getFirstTimeStampIdx()+startIdx;
+ long base = resource.getTimeBase();
+ for (int i=0; i < resultSize; i++) {
+ result[i] = base + timestamps[tsIdx+i];
+ }
+ return result;
+ }
+ }
+
+ public boolean hasValueChanged() {
+ if (valueChangeNoticed) {
+ valueChangeNoticed = false;
+ return true;
+ } else {
+ return false;
+ }
+ }
+ protected int getMemoryUsed() {
+ int result = 0;
+ if (series != null) {
+ result += series.getMemoryUsed();
+ }
+ return result;
+ }
+
+ protected void dump(PrintWriter stream) {
+ calcStats();
+ stream.print(" " + descriptor.getName() + "=");
+ stream.print("[size=" + getSnapshotsSize()
+ + " min=" + nf.format(min)
+ + " max=" + nf.format(max)
+ + " avg=" + nf.format(avg)
+ + " stddev=" + nf.format(stddev) + "]");
+ if (Boolean.getBoolean("StatArchiveReader.dumpall")) {
+ series.dump(stream);
+ } else {
+ stream.println();
+ }
+ }
+
+ protected void shrink() {
+ this.series.shrink();
+ }
+
+ protected void initialValue(long v) {
+ this.series.initialBits(v);
+ }
+ protected void prepareNextBits(long bits) {
+ useNextBits = true;
+ nextBits = bits;
+ }
+ protected void addSample() {
+ statsValid = false;
+ if (useNextBits) {
+ useNextBits = false;
+ series.addBits(nextBits);
+ valueChangeNoticed = true;
+ } else {
+ series.addBits(0);
+ }
+ }
+ }
+
+ private static abstract class BitInterval {
+ /** Returns number of items added to values */
+ abstract int fill(double[] values, int valueOffset, int typeCode, int skipCount);
+ abstract void dump(PrintWriter stream);
+ abstract boolean attemptAdd(long addBits, long addInterval, int addCount);
+ int getMemoryUsed() {
+ return 0;
+ }
+
+ protected int count;
+
+ public final int getSampleCount() {
+ return this.count;
+ }
+
+ static BitInterval create(long bits, long interval, int count) {
+ if (interval == 0) {
+ if (bits <= Integer.MAX_VALUE && bits >= Integer.MIN_VALUE) {
+ return new BitZeroIntInterval((int)bits, count);
+ } else {
+ return new BitZeroLongInterval(bits, count);
+ }
+ } else if (count <= 3) {
+ if (interval <= Byte.MAX_VALUE && interval >= Byte.MIN_VALUE) {
+ return new BitExplicitByteInterval(bits, interval, count);
+ } else if (interval <= Short.MAX_VALUE && interval >= Short.MIN_VALUE) {
+ return new BitExplicitShortInterval(bits, interval, count);
+ } else if (interval <= Integer.MAX_VALUE && interval >= Integer.MIN_VALUE) {
+ return new BitExplicitIntInterval(bits, interval, count);
+ } else {
+ return new BitExplicitLongInterval(bits, interval, count);
+ }
+ } else {
+ boolean smallBits = false;
+ boolean smallInterval = false;
+ if (bits <= Integer.MAX_VALUE && bits >= Integer.MIN_VALUE) {
+ smallBits = true;
+ }
+ if (interval <= Integer.MAX_VALUE && interval >= Integer.MIN_VALUE) {
+ smallInterval = true;
+ }
+ if (smallBits) {
+ if (smallInterval) {
+ return new BitNonZeroIntIntInterval((int)bits, (int)interval, count);
+ } else {
+ return new BitNonZeroIntLongInterval((int)bits, interval, count);
+ }
+ } else {
+ if (smallInterval) {
+ return new BitNonZeroLongIntInterval(bits, (int)interval, count);
+ } else {
+ return new BitNonZeroLongLongInterval(bits, interval, count);
+ }
+ }
+ }
+ }
+ }
+
+ private static abstract class BitNonZeroInterval extends BitInterval {
+ @Override
+ int getMemoryUsed() {
+ return super.getMemoryUsed() + 4;
+ }
+ abstract long getBits();
+ abstract long getInterval();
+
+ @Override
+ int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
+ int fillcount = values.length - valueOffset; // space left in values
+ int maxCount = count - skipCount; // maximum values this interval can produce
+ if (fillcount > maxCount) {
+ fillcount = maxCount;
+ }
+ long base = getBits();
+ long interval = getInterval();
+ base += skipCount * interval;
+ for (int i=0; i < fillcount; i++) {
+ values[valueOffset+i] = bitsToDouble(typeCode, base);
+ base += interval;
+ }
+ return fillcount;
+ }
+
+ @Override
+ void dump(PrintWriter stream) {
+ stream.print(getBits());
+ if (count > 1) {
+ long interval = getInterval();
+ if (interval != 0) {
+ stream.print("+=" + interval);
+ }
+ stream.print("r" + count);
+ }
+ }
+ BitNonZeroInterval(int count) {
+ this.count = count;
+ }
+ @Override
+ boolean attemptAdd(long addBits, long addInterval, int addCount) {
+ // addCount >= 2; count >= 2
+ if (addInterval == getInterval()) {
+ if (addBits == (getBits() + (addInterval * (count-1)))) {
+ count += addCount;
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ private static class BitNonZeroIntIntInterval extends BitNonZeroInterval {
+ int bits;
+ int interval;
+
+ @Override
+ int getMemoryUsed() {
+ return super.getMemoryUsed() + 8;
+ }
+ @Override
+ long getBits() {
+ return this.bits;
+ }
+ @Override
+ long getInterval() {
+ return this.interval;
+ }
+
+ BitNonZeroIntIntInterval(int bits, int interval, int count) {
+ super(count);
+ this.bits = bits;
+ this.interval = interval;
+ }
+ }
+
+ private static class BitNonZeroIntLongInterval extends BitNonZeroInterval {
+ int bits;
+ long interval;
+
+ @Override
+ int getMemoryUsed() {
+ return super.getMemoryUsed() + 12;
+ }
+ @Override
+ long getBits() {
+ return this.bits;
+ }
+ @Override
+ long getInterval() {
+ return this.interval;
+ }
+
+ BitNonZeroIntLongInterval(int bits, long interval, int count) {
+ super(count);
+ this.bits = bits;
+ this.interval = interval;
+ }
+ }
+
+ private static class BitNonZeroLongIntInterval extends BitNonZeroInterval {
+ long bits;
+ int interval;
+
+ @Override
+ int getMemoryUsed() {
+ return super.getMemoryUsed() + 12;
+ }
+ @Override
+ long getBits() {
+ return this.bits;
+ }
+ @Override
+ long getInterval() {
+ return this.interval;
+ }
+
+ BitNonZeroLongIntInterval(long bits, int interval, int count) {
+ super(count);
+ this.bits = bits;
+ this.interval = interval;
+ }
+ }
+
+ private static class BitNonZeroLongLongInterval extends BitNonZeroInterval {
+ long bits;
+ long interval;
+
+ @Override
+ int getMemoryUsed() {
+ return super.getMemoryUsed() + 16;
+ }
+ @Override
+ long getBits() {
+ return this.bits;
+ }
+ @Override
+ long getInterval() {
+ return this.interval;
+ }
+
+ BitNonZeroLongLongInterval(long bits, long interval, int count) {
+ super(count);
+ this.bits = bits;
+ this.interval = interval;
+ }
+ }
+
+ private static abstract class BitZeroInterval extends BitInterval {
+ @Override
+ int getMemoryUsed() {
+ return super.getMemoryUsed() + 4;
+ }
+ abstract long getBits();
+
+ @Override
+ int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
+ int fillcount = values.length - valueOffset; // space left in values
+ int maxCount = count - skipCount; // maximum values this interval can produce
+ if (fillcount > maxCount) {
+ fillcount = maxCount;
+ }
+ double value = bitsToDouble(typeCode, getBits());
+ for (int i=0; i < fillcount; i++) {
+ values[valueOffset+i] = value;
+ }
+ return fillcount;
+ }
+
+ @Override
+ void dump(PrintWriter stream) {
+ stream.print(getBits());
+ if (count > 1) {
+ stream.print("r" + count);
+ }
+ }
+ BitZeroInterval(int count) {
+ this.count = count;
+ }
+ @Override
+ boolean attemptAdd(long addBits, long addInterval, int addCount) {
+ // addCount >= 2; count >= 2
+ if (addInterval == 0 && addBits == getBits()) {
+ count += addCount;
+ return true;
+ }
+ return false;
+ }
+ }
+
+ private static class BitZeroIntInterval extends BitZeroInterval {
+ int bits;
+
+ @Override
+ int getMemoryUsed() {
+ return super.getMemoryUsed() + 4;
+ }
+ @Override
+ long getBits() {
+ return bits;
+ }
+ BitZeroIntInterval(int bits, int count) {
+ super(count);
+ this.bits = bits;
+ }
+ }
+
+ private static class BitZeroLongInterval extends BitZeroInterval {
+ long bits;
+
+ @Override
+ int getMemoryUsed() {
+ return super.getMemoryUsed() + 8;
+ }
+ @Override
+ long getBits() {
+ return bits;
+ }
+ BitZeroLongInterval(long bits, int count) {
+ super(count);
+ this.bits = bits;
+ }
+ }
+
+ private static class BitExplicitByteInterval extends BitInterval {
+ long firstValue;
+ long lastValue;
+ byte[] bitIntervals = null;
+
+ @Override
+ int getMemoryUsed() {
+ int result = super.getMemoryUsed() + 4 + 8 + 8 + 4;
+ if (bitIntervals != null) {
+ result += bitIntervals.length;
+ }
+ return result;
+ }
+ @Override
+ int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
+ int fillcount = values.length - valueOffset; // space left in values
+ int maxCount = count - skipCount; // maximum values this interval can produce
+ if (fillcount > maxCount) {
+ fillcount = maxCount;
+ }
+ long bitValue = firstValue;
+ for (int i=0; i < skipCount; i++) {
+ bitValue += bitIntervals[i];
+ }
+ for (int i=0; i < fillcount; i++) {
+ bitValue += bitIntervals[skipCount+i];
+ values[valueOffset+i] = bitsToDouble(typeCode, bitValue);
+ }
+ return fillcount;
+ }
+
+ @Override
+ void dump(PrintWriter stream) {
+ stream.print("(byteIntervalCount=" + count + " start=" + firstValue);
+ for (int i=0; i < count; i++) {
+ if (i != 0) {
+ stream.print(", ");
+ }
+ stream.print(bitIntervals[i]);
+ }
+ stream.print(")");
+ }
+ BitExplicitByteInterval(long bits, long interval, int addCount) {
+ count = addCount;
+ firstValue = bits;
+ lastValue = bits + (interval * (addCount-1));
+ bitIntervals = new byte[count*2];
+ bitIntervals[0] = 0;
+ for (int i=1; i < count; i++) {
+ bitIntervals[i] = (byte)interval;
+ }
+ }
+ @Override
+ boolean attemptAdd(long addBits, long addInterval, int addCount) {
+ // addCount >= 2; count >= 2
+ if (addCount <= 11) {
+ if (addInterval <= Byte.MAX_VALUE && addInterval >= Byte.MIN_VALUE) {
+ long firstInterval = addBits - lastValue;
+ if (firstInterval <= Byte.MAX_VALUE && firstInterval >= Byte.MIN_VALUE) {
+ lastValue = addBits + (addInterval * (addCount-1));
+ if ((count + addCount) >= bitIntervals.length) {
+ byte[] tmp = new byte[(count+addCount)*2];
+ System.arraycopy(bitIntervals, 0, tmp, 0, bitIntervals.length);
+ bitIntervals = tmp;
+ }
+ bitIntervals[count++] = (byte)firstInterval;
+ for (int i=1; i < addCount; i++) {
+ bitIntervals[count++] = (byte)addInterval;
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ }
+
+ private static class BitExplicitShortInterval extends BitInterval {
+ long firstValue;
+ long lastValue;
+ short[] bitIntervals = null;
+
+ @Override
+ int getMemoryUsed() {
+ int result = super.getMemoryUsed() + 4 + 8 + 8 + 4;
+ if (bitIntervals != null) {
+ result += bitIntervals.length * 2;
+ }
+ return result;
+ }
+
+ @Override
+ int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
+ int fillcount = values.length - valueOffset; // space left in values
+ int maxCount = count - skipCount; // maximum values this interval can produce
+ if (fillcount > maxCount) {
+ fillcount = maxCount;
+ }
+ long bitValue = firstValue;
+ for (int i=0; i < skipCount; i++) {
+ bitValue += bitIntervals[i];
+ }
+ for (int i=0; i < fillcount; i++) {
+ bitValue += bitIntervals[skipCount+i];
+ values[valueOffset+i] = bitsToDouble(typeCode, bitValue);
+ }
+ return fillcount;
+ }
+
+ @Override
+ void dump(PrintWriter stream) {
+ stream.print("(shortIntervalCount=" + count + " start=" + firstValue);
+ for (int i=0; i < count; i++) {
+ if (i != 0) {
+ stream.print(", ");
+ }
+ stream.print(bitIntervals[i]);
+ }
+ stream.print(")");
+ }
+ BitExplicitShortInterval(long bits, long interval, int addCount) {
+ count = addCount;
+ firstValue = bits;
+ lastValue = bits + (interval * (addCount-1));
+ bitIntervals = new short[count*2];
+ bitIntervals[0] = 0;
+ for (int i=1; i < count; i++) {
+ bitIntervals[i] = (short)interval;
+ }
+ }
+ @Override
+ boolean attemptAdd(long addBits, long addInterval, int addCount) {
+ // addCount >= 2; count >= 2
+ if (addCount <= 6) {
+ if (addInterval <= Short.MAX_VALUE && addInterval >= Short.MIN_VALUE) {
+ long firstInterval = addBits - lastValue;
+ if (firstInterval <= Short.MAX_VALUE && firstInterval >= Short.MIN_VALUE) {
+ lastValue = addBits + (addInterval * (addCount-1));
+ if ((count + addCount) >= bitIntervals.length) {
+ short[] tmp = new short[(count+addCount)*2];
+ System.arraycopy(bitIntervals, 0, tmp, 0, bitIntervals.length);
+ bitIntervals = tmp;
+ }
+ bitIntervals[count++] = (short)firstInterval;
+ for (int i=1; i < addCount; i++) {
+ bitIntervals[count++] = (short)addInterval;
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ }
+
+ private static class BitExplicitIntInterval extends BitInterval {
+ long firstValue;
+ long lastValue;
+ int[] bitIntervals = null;
+
+ @Override
+ int getMemoryUsed() {
+ int result = super.getMemoryUsed() + 4 + 8 + 8 + 4;
+ if (bitIntervals != null) {
+ result += bitIntervals.length * 4;
+ }
+ return result;
+ }
+
+ @Override
+ int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
+ int fillcount = values.length - valueOffset; // space left in values
+ int maxCount = count - skipCount; // maximum values this interval can produce
+ if (fillcount > maxCount) {
+ fillcount = maxCount;
+ }
+ long bitValue = firstValue;
+ for (int i=0; i < skipCount; i++) {
+ bitValue += bitIntervals[i];
+ }
+ for (int i=0; i < fillcount; i++) {
+ bitValue += bitIntervals[skipCount+i];
+ values[valueOffset+i] = bitsToDouble(typeCode, bitValue);
+ }
+ return fillcount;
+ }
+
+ @Override
+ void dump(PrintWriter stream) {
+ stream.print("(intIntervalCount=" + count + " start=" + firstValue);
+ for (int i=0; i < count; i++) {
+ if (i != 0) {
+ stream.print(", ");
+ }
+ stream.print(bitIntervals[i]);
+ }
+ stream.print(")");
+ }
+ BitExplicitIntInterval(long bits, long interval, int addCount) {
+ count = addCount;
+ firstValue = bits;
+ lastValue = bits + (interval * (addCount-1));
+ bitIntervals = new int[count*2];
+ bitIntervals[0] = 0;
+ for (int i=1; i < count; i++) {
+ bitIntervals[i] = (int)interval;
+ }
+ }
+ @Override
+ boolean attemptAdd(long addBits, long addInterval, int addCount) {
+ // addCount >= 2; count >= 2
+ if (addCount <= 4) {
+ if (addInterval <= Integer.MAX_VALUE && addInterval >= Integer.MIN_VALUE) {
+ long firstInterval = addBits - lastValue;
+ if (firstInterval <= Integer.MAX_VALUE && firstInterval >= Integer.MIN_VALUE) {
+ lastValue = addBits + (addInterval * (addCount-1));
+ if ((count + addCount) >= bitIntervals.length) {
+ int[] tmp = new int[(count+addCount)*2];
+ System.arraycopy(bitIntervals, 0, tmp, 0, bitIntervals.length);
+ bitIntervals = tmp;
+ }
+ bitIntervals[count++] = (int)firstInterval;
+ for (int i=1; i < addCount; i++) {
+ bitIntervals[count++] = (int)addInterval;
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+ }
+
+ private static class BitExplicitLongInterval extends BitInterval {
+ long[] bitArray = null;
+
+ @Override
+ int getMemoryUsed() {
+ int result = super.getMemoryUsed() + 4 + 4;
+ if (bitArray != null) {
+ result += bitArray.length * 8;
+ }
+ return result;
+ }
+
+ @Override
+ int fill(double[] values, int valueOffset, int typeCode, int skipCount) {
+ int fillcount = values.length - valueOffset; // space left in values
+ int maxCount = count - skipCount; // maximum values this interval can produce
+ if (fillcount > maxCount) {
+ fillcount = maxCount;
+ }
+ for (int i=0; i < fillcount; i++) {
+ values[valueOffset+i] = bitsToDouble(typeCode, bitArray[skipCount+i]);
+ }
+ return fillcount;
+ }
+
+ @Override
+ void dump(PrintWriter stream) {
+ stream.print("(count=" + count + " ");
+ for (int i=0; i < count; i++) {
+ if (i != 0) {
+ stream.print(", ");
+ }
+ stream.print(bitArray[i]);
+ }
+ stream.print(")");
+ }
+ BitExplicitLongInterval(long bits, long interval, int addCount) {
+ count = addCount;
+ bitArray = new long[count*2];
+ for (int i=0; i < count; i++) {
+ bitArray[i] = bits;
+ bits += interval;
+ }
+ }
+ @Override
+ boolean attemptAdd(long addBits, long addInterval, int addCount) {
+ // addCount >= 2; count >= 2
+ if (addCount <= 3) {
+ if ((count + addCount) >= bitArray.length) {
+ long[] tmp = new long[(count+addCount)*2];
+ System.arraycopy(bitArray, 0, tmp, 0, bitArray.length);
+ bitArray = tmp;
+ }
+ for (int i=0; i < addCount; i++) {
+ bitArray[count++] = addBits;
+ addBits += addInterval;
+ }
+ return true;
+ }
+ return false;
+ }
+ }
+
+ private static class BitSeries {
+ int count; // number of items in this series
+ long currentStartBits;
+ long currentEndBits;
+ long currentInterval;
+ int currentCount;
+ int intervalIdx; // index of most recent BitInterval
+ BitInterval intervals[];
+
+ /**
+ * Returns the amount of memory used to implement this series.
+ */
+ protected int getMemoryUsed() {
+ int result = 4 + 8 + 8 + 8 + 4 + 4 + 4;
+ if (intervals != null) {
+ result += 4 * intervals.length;
+ for (int i=0; i <= intervalIdx; i++) {
+ result += intervals[i].getMemoryUsed();
+ }
+ }
+ return result;
+ }
+
+ public double[] getValues(int typeCode) {
+ return getValuesEx(typeCode, 0, getSize());
+ }
+ /**
+ * Gets the first "resultSize" values of this series
+ * skipping over the first "samplesToSkip" ones.
+ * The first value in a series is at index 0.
+ * The maximum result size can be obtained by calling "getSize()".
+ */
+ public double[] getValuesEx(int typeCode, int samplesToSkip, int resultSize) {
+ double[] result = new double[resultSize];
+ int firstInterval = 0;
+ int idx = 0;
+ while (samplesToSkip > 0
+ && firstInterval <= intervalIdx
+ && intervals[firstInterval].getSampleCount() <= samplesToSkip) {
+ samplesToSkip -= intervals[firstInterval].getSampleCount();
+ firstInterval++;
+ }
+ for (int i=firstInterval; i <= intervalIdx; i++) {
+ idx += intervals[i].fill(result, idx, typeCode, samplesToSkip);
+ samplesToSkip = 0;
+ }
+ if (currentCount != 0) {
+ idx += BitInterval.create(currentStartBits, currentInterval, currentCount).fill(result, idx, typeCode, samplesToSkip);
+ }
+ // assert
+ if (idx != resultSize) {
+ throw new InternalGemFireException(LocalizedStrings.StatArchiveReader_GETVALUESEX_DIDNT_FILL_THE_LAST_0_ENTRIES_OF_ITS_RESULT.toLocalizedString(Integer.valueOf(resultSize-idx)));
+ }
+ return result;
+ }
+
+ void dump(PrintWriter stream) {
+ stream.print("[size=" + count + " intervals=" + (intervalIdx+1)
+ + " memused=" + getMemoryUsed() + " ");
+ for (int i=0; i <= intervalIdx; i++) {
+ if (i != 0) {
+ stream.print(", ");
+ }
+ intervals[i].dump(stream);
+ }
+ if (currentCount != 0) {
+ if (intervalIdx != -1) {
+ stream.print(", ");
+ }
+ BitInterval.create(currentStartBits, currentInterval, currentCount).dump(stream);
+ }
+ stream.println("]");
+ }
+
+ BitSeries() {
+ count = 0;
+ currentStartBits = 0;
+ currentEndBits = 0;
+ currentInterval = 0;
+ currentCount = 0;
+ intervalIdx = -1;
+ intervals = null;
+ }
+
+ void initialBits(long bits) {
+ this.currentEndBits = bits;
+ }
+
+ int getSize() {
+ return this.count;
+ }
+
+ void addBits(long deltaBits) {
+ long bits = currentEndBits + deltaBits;
+ if (currentCount == 0) {
+ currentStartBits = bits;
+ currentCount = 1;
+ } else if (currentCount == 1) {
+ currentInterval = deltaBits;
+ currentCount++;
+ } else if (deltaBits == currentInterval) {
+ currentCount++;
+ } else {
+ // we need to move currentBits into a BitInterval
+ if (intervalIdx == -1) {
+ intervals = new BitInterval[2];
+ intervalIdx = 0;
+ intervals[0] = BitInterval.create(currentStartBits, currentInterval, currentCount);
+ } else {
+ if (!intervals[intervalIdx].attemptAdd(currentStartBits, currentInterval, currentCount)) {
+ // wouldn't fit in current bit interval so add a new one
+ intervalIdx++;
+ if (intervalIdx >= intervals.length) {
+ BitInterval[] tmp = new BitInterval[intervals.length * 2];
+ System.arraycopy(intervals, 0, tmp, 0, intervals.length);
+ intervals = tmp;
+ }
+ intervals[intervalIdx] = BitInterval.create(currentStartBits, currentInterval, currentCount);
+ }
+ }
+ // now start a new currentBits
+ currentStartBits = bits;
+ currentCount = 1;
+ }
+ currentEndBits = bits;
+ count++;
+ }
+ /**
+ * Free up any unused memory
+ */
+ void shrink() {
+ if (intervals != null) {
+ int currentSize = intervalIdx+1;
+ if (currentSize < intervals.length) {
+ BitInterval[] tmp = new BitInterval[currentSize];
+ System.arraycopy(intervals, 0, tmp, 0, currentSize);
+ intervals = tmp;
+ }
+ }
+ }
+ }
+
+ private static class TimeStampSeries {
+ static private final int GROW_SIZE = 256;
+ int count; // number of items in this series
+ long base; // millis since midnight, Jan 1, 1970 UTC.
+ long[] timeStamps = new long[GROW_SIZE]; // elapsed millis from base
+
+ void dump(PrintWriter stream) {
+ stream.print("[size=" + count);
+ for (int i=0; i < count; i++) {
+ if (i != 0) {
+ stream.print(", ");
+ stream.print(timeStamps[i]-timeStamps[i-1]);
+ } else {
+ stream.print(" " + timeStamps[i]);
+ }
+ }
+ stream.println("]");
+ }
+
+ void shrink() {
+ if (count < timeStamps.length) {
+ long[] tmp = new long[count];
+ System.arraycopy(timeStamps, 0, tmp, 0, count);
+ timeStamps = tmp;
+ }
+ }
+
+ TimeStampSeries() {
+ count = 0;
+ base = 0;
+ }
+
+ void setBase(long base) {
+ this.base = base;
+ }
+
+ int getSize() {
+ return this.count;
+ }
+
+ void addTimeStamp(int ts) {
+ if (count >= timeStamps.length) {
+ long[] tmp = new long[timeStamps.length + GROW_SIZE];
+ System.arraycopy(timeStamps, 0, tmp, 0, timeStamps.length);
+ timeStamps = tmp;
+ }
+ if (count != 0) {
+ timeStamps[count] = timeStamps[count-1] + ts;
+ } else {
+ timeStamps[count] = ts;
+ }
+ count++;
+ }
+
+ long getBase() {
+ return this.base;
+ }
+ /** Provides direct access to underlying data.
+ * Do not modify contents and use getSize() to keep from reading
+ * past end of array.
+ */
+ long[] getRawTimeStamps() {
+ return this.timeStamps;
+ }
+ long getMilliTimeStamp(int idx) {
+ return this.base + this.timeStamps[idx];
+ }
+ /**
+ * Returns an array of time stamp values the first of which
+ * has the specified index.
+ * Each returned time stamp is the number of millis since
+ * midnight, Jan 1, 1970 UTC.
+ */
+ double[] getTimeValuesSinceIdx(int idx) {
+ int resultSize = this.count - idx;
+ double[] result = new double[resultSize];
+ for (int i=0; i < resultSize; i++) {
+ result[i] = getMilliTimeStamp(idx+i);
+ }
+ return result;
+ }
+ }
+
+ /**
+ * Defines a statistic resource type. Each resource instance must be
+ * of a single type. The type defines what statistics each instance
+ * of it will support. The type also has a description of itself.
+ */
+ public static class ResourceType {
+ private boolean loaded;
+// private final int id;
+ private final String name;
+ private String desc;
+ private final StatDescriptor[] stats;
+ private Map descriptorMap;
+
+ public void dump(PrintWriter stream) {
+ if (loaded) {
+ stream.println(name + ": " + desc);
+ for (int i=0; i < stats.length; i++) {
+ stats[i].dump(stream);
+ }
+ }
+ }
+
+ protected ResourceType(int id, String name, int statCount) {
+ this.loaded = false;
+// this.id = id;
+ this.name = name;
+ this.desc = null;
+ this.stats = new StatDescriptor[statCount];
+ this.descriptorMap = null;
+ }
+
+ protected ResourceType(int id, String name, String desc, int statCount) {
+ this.loaded = true;
+// this.id = id;
+ this.name = name;
+ this.desc = desc;
+ this.stats = new StatDescriptor[statCount];
+ this.descriptorMap = new HashMap();
+ }
+ public boolean isLoaded() {
+ return this.loaded;
+ }
+ /**
+ * Frees up any resources no longer needed after the archive file is closed.
+ * Returns true if this guy is no longer needed.
+ */
+ protected boolean close() {
+ if (isLoaded()) {
+ for (int i=0; i < stats.length; i++) {
+ if (stats[i] != null) {
+ if (!stats[i].isLoaded()) {
+ stats[i] = null;
+ }
+ }
+ }
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ void unload() {
+ this.loaded = false;
+ this.desc = null;
+ for (int i=0; i < this.stats.length; i++) {
+ this.stats[i].unload();
+ }
+ this.descriptorMap.clear();
+ this.descriptorMap = null;
+ }
+
+ protected void addStatDescriptor(StatArchiveFile archive, int offset, String name, boolean isCounter,
+ boolean largerBetter,
+ byte typeCode, String units, String desc) {
+ StatDescriptor descriptor = new StatDescriptor(name, offset, isCounter, largerBetter, typeCode, units, desc);
+ this.stats[offset] = descriptor;
+ if (archive.loadStatDescriptor(descriptor, this)) {
+ descriptorMap.put(name, descriptor);
+ }
+ }
+
+// private int getId() {
+// return this.id;
+// }
+ /**
+ * Returns the name of this resource type.
+ */
+ public String getName() {
+ return this.name;
+ }
+ /**
+ * Returns an array of descriptors for each statistic this resource
+ * type supports.
+ */
+ public StatDescriptor[] getStats() {
+ return this.stats;
+ }
+ /**
+ * Gets a stat descriptor contained in this type given the stats name.
+ * @param name the name of the stat to find in the current type
+ * @return the descriptor that matches the name or null if the type
+ * does not have a stat of the given name
+ */
+ public StatDescriptor getStat(String name) {
+ return (StatDescriptor)descriptorMap.get(name);
+ }
+ /**
+ * Returns a description of this resource type.
+ */
+ public String getDescription() {
+ return this.desc;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+ return true;
+ if (obj == null)
+ return false;
+ if (getClass() != obj.getClass())
+ return false;
+ ResourceType other = (ResourceType) obj;
+ if (name == null) {
+ if (other.name != null)
+ return false;
+ } else if (!name.equals(other.name))
+ return false;
+ return true;
+ }
+ }
+
+ /**
+ * Describes some global information about the archive.
+ */
+ public static class ArchiveInfo {
+ private final StatArchiveFile archive;
+ private final byte archiveVersion;
+ private final long startTimeStamp; // in milliseconds
+ private final long systemStartTimeStamp; // in milliseconds
+ private final int timeZoneOffset;
+ private final String timeZoneName;
+ private final String systemDirectory;
+ private final long systemId;
+ private final String productVersion;
+ private final String os;
+ private final String machine;
+
+ public ArchiveInfo(StatArchiveFile archive, byte archiveVersion,
+ long startTimeStamp, long systemStartTimeStamp,
+ int timeZoneOffset,String timeZoneName,
+ String systemDirectory, long systemId,
+ String productVersion, String os, String machine) {
+ this.archive = archive;
+ this.archiveVersion = archiveVersion;
+ this.startTimeStamp = startTimeStamp;
+ this.systemStartTimeStamp = systemStartTimeStamp;
+ this.timeZoneOffset = timeZoneOffset;
+ this.timeZoneName = timeZoneName;
+ this.systemDirectory = systemDirectory;
+ this.systemId = systemId;
+ this.productVersion = productVersion;
+ this.os = os;
+ this.machine = machine;
+ archive.setTimeZone(getTimeZone());
+ }
+
+ /**
+ * Returns the difference, measured in milliseconds, between the time
+ * the archive file was create and midnight, January 1, 1970 UTC.
+ */
+ public long getStartTimeMillis() {
+ return this.startTimeStamp;
+ }
+ /**
+ * Returns the difference, measured in milliseconds, between the time
+ * the archived system was started and midnight, January 1, 1970 UTC.
+ */
+ public long getSystemStartTimeMillis() {
+ return this.systemStartTimeStamp;
+ }
+ /**
+ * Returns a numeric id of the archived system. It can be used in
+ * conjunction with the {@link #getSystemStartTimeMillis} to
+ * uniquely identify an archived system.
+ */
+ public long getSystemId() {
+ return this.systemId;
+ }
+ /**
+ * Returns a string describing the operating system the archive was
+ * written on.
+ */
+ public String getOs() {
+ return this.os;
+ }
+ /**
+ * Returns a string describing the machine the archive was
+ * written on.
+ */
+ public String getMachine() {
+ return this.machine;
+ }
+ /**
+ * Returns the time zone used when the archive was created.
+ * This can be used to print timestamps in the same time zone
+ * that was in effect when the archive was created.
+ */
+ public TimeZone getTimeZone() {
+ TimeZone result = TimeZone.getTimeZone(this.timeZoneName);
+ if (result.getRawOffset() != this.timeZoneOffset) {
+ result = new SimpleTimeZone(this.timeZoneOffset, this.timeZoneName);
+ }
+ return result;
+ }
+ /**
+ * Returns a string containing the version of the product that wrote
+ * this archive.
+ */
+ public String getProductVersion() {
+ return this.productVersion;
+ }
+ /**
+ * Returns a numeric code that represents the format version used to
+ * encode the archive as a stream of bytes.
+ */
+ public int getArchiveFormatVersion() {
+ return this.archiveVersion;
+ }
+ /**
+ * Returns a string describing the system that this archive recorded.
+ */
+ public String getSystem() {
+ return this.systemDirectory;
+ }
+ /**
+ * Return the name of the file this archive was stored in or
+ * an empty string if the archive was not stored in a file.
+ */
+ public String getArchiveFileName() {
+ if (this.archive != null) {
+ return this.archive.getFile().getPath();
+ } else {
+ return "";
+ }
+ }
+
+ /**
+ * Returns a string representation of this object.
+ */
+ @Override
+ public String toString() {
+ StringWriter sw = new StringWriter();
+ this.dump(new PrintWriter(sw));
+ return sw.toString();
+ }
+
+ protected void dump(PrintWriter stream) {
+ if (archive != null) {
+ stream.println("archive=" + archive.getFile());
+ }
+ stream.println("archiveVersion=" + archiveVersion);
+ if (archive != null) {
+ stream.println("startDate=" + archive.formatTimeMillis(startTimeStamp));
+ }
+ // stream.println("startTimeStamp=" + startTimeStamp +" tz=" + timeZoneName + " tzOffset=" + timeZoneOffset);
+ // stream.println("timeZone=" + getTimeZone().getDisplayName());
+ stream.println("systemDirectory=" + systemDirectory);
+ if (archive != null) {
+ stream.println("systemStartDate=" + archive.formatTimeMillis(systemStartTimeStamp));
+ }
+ stream.println("systemId=" + systemId);
+ stream.println("productVersion=" + productVersion);
+ stream.println("osInfo=" + os);
+ stream.println("machineInfo=" + machine);
+ }
+ }
+
+ /**
+ * Defines a single instance of a resource type.
+ */
+ public static class ResourceInst {
+ private final boolean loaded;
+ private final StatArchiveFile archive;
+// private final int uniqueId;
+ private final ResourceType type;
+ private final String name;
+ private final long id;
+ private boolean active = true;
+ private final SimpleValue[] values;
+ private int firstTSidx = -1;
+ private int lastTSidx = -1;
+
+ /**
+ * Returns the approximate amount of memory used to implement this object.
+ */
+ protected int getMemoryUsed() {
+ int result = 0;
+ if (values != null) {
+ for (int i=0; i < values.length; i++) {
+ result += this.values[i].getMemoryUsed();
+ }
+ }
+ return result;
+ }
+
+ public StatArchiveReader getReader() {
+ return archive.getReader();
+ }
+ /**
+ * Returns a string representation of this object.
+ */
+ @Override
+ public String toString() {
+ StringBuffer result = new StringBuffer();
+ result.append(name)
+ .append(", ")
+ .append(id)
+ .append(", ")
+ .append(type.getName())
+ .append(": \"")
+ .append(archive.formatTimeMillis(getFirstTimeMillis()))
+ .append('\"');
+ if (!active) {
+ result.append(" inactive");
+ }
+ result.append(" samples="+ getSampleCount());
+ return result.toString();
+ }
+ /**
+ * Returns the number of times this resource instance has been sampled.
+ */
+ public int getSampleCount() {
+ if (active) {
+ return archive.getTimeStamps().getSize() - firstTSidx;
+ } else {
+ return (lastTSidx+1) - firstTSidx;
+ }
+ }
+
+ public StatArchiveFile getArchive() {
+ return this.archive;
+ }
+
+ protected void dump(PrintWriter stream) {
+ stream.println(name + ":"
+ + " file=" + getArchive().getFile()
+ + " id=" + id
+ + (active? "" : " deleted")
+ + " start=" + archive.formatTimeMillis(getFirstTimeMillis()));
+ for (int i=0; i < values.length; i++) {
+ values[i].dump(stream);
+ }
+ }
+
+ protected ResourceInst(StatArchiveFile archive, int uniqueId, String name, long id, ResourceType type, boolean loaded) {
+ this.loaded = loaded;
+ this.archive = archive;
+// this.uniqueId = uniqueId;
+ this.name = name;
+ this.id = id;
+ Assert.assertTrue(type != null);
+ this.type = type;
+ if (loaded) {
+ StatDescriptor[] stats = type.getStats();
+ this.values = new SimpleValue[stats.length];
+ for (int i=0; i < stats.length; i++) {
+ if (archive.loadStat(stats[i], this)) {
+ this.values[i] = new SimpleValue(this, stats[i]);
+ } else {
+ this.values[i] = null;
+ }
+ }
+ } else {
+ this.values = null;
+ }
+ }
+
+ void matchSpec(StatSpec spec, List matchedValues) {
+ if (spec.typeMatches(this.type.getName())) {
+ if (spec.instanceMatches(this.getName(), this.getId())) {
+ for (int statIdx=0; statIdx < values.length; statIdx++) {
+ if (values[statIdx] != null) {
+ if (spec.statMatches(values[statIdx].getDescriptor().getName())) {
+ matchedValues.add(values[statIdx]);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ protected void initialValue(int statOffset, long v) {
+ if (this.values != null && this.values[statOffset] != null) {
+ this.values[statOffset].initialValue(v);
+ }
+ }
+ /**
+ * Returns true if sample was added.
+ */
+ protected boolean addValueSample(int statOffset, long statDeltaBits) {
+ if (this.values != null && this.values[statOffset] != null) {
+ this.values[statOffset].prepareNextBits(statDeltaBits);
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ public boolean isLoaded() {
+ return this.loaded;
+ }
+
+ /**
+ * Frees up any resources no longer needed after the archive file is closed.
+ * Returns true if this guy is no longer needed.
+ */
+ protected boolean close() {
+ if (isLoaded()) {
+ for (int i=0; i < values.length; i++) {
+ if (values[i] != null) {
+ values[i].shrink();
+ }
+ }
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+ protected int getFirstTimeStampIdx() {
+ return this.firstTSidx;
+ }
+ protected long[] getAllRawTimeStamps() {
+ return archive.getTimeStamps().getRawTimeStamps();
+ }
+ protected long getTimeBase() {
+ return archive.getTimeStamps().getBase();
+ }
+ /**
+ * Returns an array of doubles containing the timestamps at which
+ * this instances samples where taken. Each of these timestamps
+ * is the difference, measured in milliseconds, between the sample
+ * time and midnight, January 1, 1970 UTC.
+ * Although these values are double they can safely be converted
+ * to <code>long</code> with no loss of information.
+ */
+ public double[] getSnapshotTimesMillis() {
+ return archive.getTimeStamps().getTimeValuesSinceIdx(firstTSidx);
+ }
+ /**
+ * Returns an array of statistic value descriptors. Each element
+ * of the array describes the corresponding statistic this instance
+ * supports. The <code>StatValue</code> instances can be used to
+ * obtain the actual sampled values of the instances statistics.
+ */
+ public StatValue[] getStatValues() {
+ return this.values;
+ }
+ /**
+ * Gets the value of the stat in the current instance given the stat name.
+ * @param name the name of the stat to find in the current instance
+ * @return the value that matches the name or null if the instance
+ * does not have a stat of the given name
+ *
+ */
+ public StatValue getStatValue(String name) {
+ StatValue result = null;
+ StatDescriptor desc = getType().getStat(name);
+ if (desc != null) {
+ result = values[desc.getOffset()];
+ }
+ return result;
+ }
+
+ /**
+ * Returns the name of this instance.
+ */
+ public String getName() {
+ return this.name;
+ }
+ /**
+ * Returns the id of this instance.
+ */
+ public long getId() {
+ return this.id;
+ }
+ /**
+ * Returns the difference, measured in milliseconds, between the time
+ * of the instance's first sample and midnight, January 1, 1970 UTC.
+ */
+ public long getFirstTimeMillis() {
+ return archive.getTimeStamps().getMilliTimeStamp(firstTSidx);
+ }
+ /**
+ * Returns resource type of this instance.
+ */
+ public ResourceType getType() {
+ return this.type;
+ }
+ protected void makeInactive() {
+ this.active = false;
+ lastTSidx = archive.getTimeStamps().getSize() - 1;
+ close(); // this frees up unused memory now that no more samples
+ }
+ /**
+ * Returns true if archive might still have future samples for this instance.
+ */
+ public boolean isActive() {
+ return this.active;
+ }
+ protected void addTimeStamp() {
+ if (this.loaded) {
+ if (firstTSidx == -1) {
+ firstTSidx = archive.getTimeStamps().getSize() - 1;
+ }
+ for (int i=0; i < values.length; i++) {
+ if (values[i] != null) {
+ values[i].addSample();
+ }
+ }
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + (int) (id ^ (id >>> 32));
+ result = prime * result + ((name == null) ? 0 : name.hashCode());
+ result = prime * result + ((type == null) ? 0 : type.hashCode());
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj)
+
<TRUNCATED>
[02/24] incubator-geode git commit: GEODE-1781: refactor internal
statistics classes
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/internal/stats50/AtomicStatsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/internal/stats50/AtomicStatsJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/internal/stats50/AtomicStatsJUnitTest.java
index 1fc1d23..b87db46 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/internal/stats50/AtomicStatsJUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/internal/stats50/AtomicStatsJUnitTest.java
@@ -21,7 +21,7 @@ import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.distributed.DistributedSystem;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/java/com/gemstone/gemfire/management/bean/stats/MemberLevelStatsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/com/gemstone/gemfire/management/bean/stats/MemberLevelStatsJUnitTest.java b/geode-core/src/test/java/com/gemstone/gemfire/management/bean/stats/MemberLevelStatsJUnitTest.java
index dcbbaca..5ad58dc 100644
--- a/geode-core/src/test/java/com/gemstone/gemfire/management/bean/stats/MemberLevelStatsJUnitTest.java
+++ b/geode-core/src/test/java/com/gemstone/gemfire/management/bean/stats/MemberLevelStatsJUnitTest.java
@@ -32,7 +32,7 @@ import com.gemstone.gemfire.distributed.internal.DistributionStats;
import com.gemstone.gemfire.distributed.internal.locks.DLockStats;
import com.gemstone.gemfire.internal.NanoTimer;
import com.gemstone.gemfire.internal.OSProcess;
-import com.gemstone.gemfire.internal.VMStatsContract;
+import com.gemstone.gemfire.internal.statistics.VMStatsContract;
import com.gemstone.gemfire.internal.cache.CachePerfStats;
import com.gemstone.gemfire.internal.cache.DiskStoreStats;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/resources/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest_testWriteAfterSamplingBegins_expected.gfs
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest_testWriteAfterSamplingBegins_expected.gfs b/geode-core/src/test/resources/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest_testWriteAfterSamplingBegins_expected.gfs
deleted file mode 100644
index 7fc8265..0000000
Binary files a/geode-core/src/test/resources/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest_testWriteAfterSamplingBegins_expected.gfs and /dev/null differ
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/resources/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest_testWriteWhenSamplingBegins_expected.gfs
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest_testWriteWhenSamplingBegins_expected.gfs b/geode-core/src/test/resources/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest_testWriteWhenSamplingBegins_expected.gfs
deleted file mode 100644
index 15a01b0..0000000
Binary files a/geode-core/src/test/resources/com/gemstone/gemfire/internal/StatArchiveWriterReaderJUnitTest_testWriteWhenSamplingBegins_expected.gfs and /dev/null differ
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderJUnitTest_testWriteAfterSamplingBegins_expected.gfs
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderJUnitTest_testWriteAfterSamplingBegins_expected.gfs b/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderJUnitTest_testWriteAfterSamplingBegins_expected.gfs
new file mode 100644
index 0000000..ccd20b2
Binary files /dev/null and b/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderJUnitTest_testWriteAfterSamplingBegins_expected.gfs differ
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderJUnitTest_testWriteWhenSamplingBegins_expected.gfs
----------------------------------------------------------------------
diff --git a/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderJUnitTest_testWriteWhenSamplingBegins_expected.gfs b/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderJUnitTest_testWriteWhenSamplingBegins_expected.gfs
new file mode 100644
index 0000000..fd1e77a
Binary files /dev/null and b/geode-core/src/test/resources/com/gemstone/gemfire/internal/statistics/StatArchiveWriterReaderJUnitTest_testWriteWhenSamplingBegins_expected.gfs differ
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-cq/src/main/java/com/gemstone/gemfire/cache/query/internal/cq/CqServiceVsdStats.java
----------------------------------------------------------------------
diff --git a/geode-cq/src/main/java/com/gemstone/gemfire/cache/query/internal/cq/CqServiceVsdStats.java b/geode-cq/src/main/java/com/gemstone/gemfire/cache/query/internal/cq/CqServiceVsdStats.java
index 3327909..d1a703c 100644
--- a/geode-cq/src/main/java/com/gemstone/gemfire/cache/query/internal/cq/CqServiceVsdStats.java
+++ b/geode-cq/src/main/java/com/gemstone/gemfire/cache/query/internal/cq/CqServiceVsdStats.java
@@ -23,15 +23,13 @@ import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.query.CqException;
import com.gemstone.gemfire.cache.query.CqQuery;
import com.gemstone.gemfire.cache.query.internal.DefaultQueryService;
import com.gemstone.gemfire.internal.NanoTimer;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
import com.gemstone.gemfire.internal.cache.FilterProfile;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
-import com.gemstone.gemfire.internal.cache.LocalRegion;
import com.gemstone.gemfire.internal.logging.LogService;
/**
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/LuceneIndexStats.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/LuceneIndexStats.java b/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/LuceneIndexStats.java
index 4f89fa7..220ae0e 100644
--- a/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/LuceneIndexStats.java
+++ b/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/LuceneIndexStats.java
@@ -28,7 +28,7 @@ import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
import com.gemstone.gemfire.internal.CopyOnWriteHashSet;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
public class LuceneIndexStats {
// statistics type
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/filesystem/FileSystemStats.java
----------------------------------------------------------------------
diff --git a/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/filesystem/FileSystemStats.java b/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/filesystem/FileSystemStats.java
index ee66850..e6bbf0d 100644
--- a/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/filesystem/FileSystemStats.java
+++ b/geode-lucene/src/main/java/com/gemstone/gemfire/cache/lucene/internal/filesystem/FileSystemStats.java
@@ -26,7 +26,7 @@ import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.StatisticsType;
import com.gemstone.gemfire.StatisticsTypeFactory;
-import com.gemstone.gemfire.internal.StatisticsTypeFactoryImpl;
+import com.gemstone.gemfire.internal.statistics.StatisticsTypeFactoryImpl;
public class FileSystemStats {
private static final StatisticsType statsType;
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/11507012/geode-rebalancer/src/test/java/com/gemstone/gemfire/cache/util/AutoBalancerIntegrationJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-rebalancer/src/test/java/com/gemstone/gemfire/cache/util/AutoBalancerIntegrationJUnitTest.java b/geode-rebalancer/src/test/java/com/gemstone/gemfire/cache/util/AutoBalancerIntegrationJUnitTest.java
index 5ab8d0e..cbd57eb 100755
--- a/geode-rebalancer/src/test/java/com/gemstone/gemfire/cache/util/AutoBalancerIntegrationJUnitTest.java
+++ b/geode-rebalancer/src/test/java/com/gemstone/gemfire/cache/util/AutoBalancerIntegrationJUnitTest.java
@@ -23,7 +23,7 @@ import com.gemstone.gemfire.cache.util.AutoBalancer.GeodeCacheFacade;
import com.gemstone.gemfire.distributed.DistributedLockService;
import com.gemstone.gemfire.distributed.internal.InternalDistributedSystem;
import com.gemstone.gemfire.distributed.internal.locks.DLockService;
-import com.gemstone.gemfire.internal.HostStatSampler;
+import com.gemstone.gemfire.internal.statistics.HostStatSampler;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.test.junit.categories.IntegrationTest;
import org.junit.After;