This is an automated email from the ASF dual-hosted git repository.
liubao pushed a commit to branch 2.8.x
in repository https://gitbox.apache.org/repos/asf/servicecomb-java-chassis.git
The following commit(s) were added to refs/heads/2.8.x by this push:
new 3ccd557b3 [#2670]use java system api to retrieve CPU usage (#4098)
3ccd557b3 is described below
commit 3ccd557b38195733f35561050bdc2166c6ece374
Author: liubao68 <[email protected]>
AuthorDate: Wed Dec 6 16:32:21 2023 +0800
[#2670]use java system api to retrieve CPU usage (#4098)
---
.../metrics/core/meter/os/CpuMeter.java | 48 ++----
.../core/meter/os/cpu/AbstractCpuUsage.java | 65 -------
.../metrics/core/meter/os/cpu/CpuUtils.java | 183 --------------------
.../metrics/core/meter/os/cpu/OsCpuUsage.java | 52 ------
.../metrics/core/meter/os/cpu/ProcessCpuUsage.java | 55 ------
.../metrics/core/TestOsMeterInitializer.java | 55 ++----
.../metrics/core/meter/os/TestCpuMeter.java | 188 +++++----------------
.../metrics/core/meter/os/TestOsMeter.java | 59 ++-----
8 files changed, 81 insertions(+), 624 deletions(-)
diff --git
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/CpuMeter.java
b/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/CpuMeter.java
index 587c11419..72416123a 100644
---
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/CpuMeter.java
+++
b/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/CpuMeter.java
@@ -16,55 +16,33 @@
*/
package org.apache.servicecomb.metrics.core.meter.os;
+import java.lang.management.ManagementFactory;
import java.util.List;
-import org.apache.servicecomb.metrics.core.meter.os.cpu.OsCpuUsage;
-import org.apache.servicecomb.metrics.core.meter.os.cpu.ProcessCpuUsage;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
+import com.google.common.annotations.VisibleForTesting;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
+import com.sun.management.OperatingSystemMXBean;
public class CpuMeter {
- private static final Logger LOGGER = LoggerFactory.getLogger(CpuMeter.class);
+ private OperatingSystemMXBean osBean =
ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
- // read from /proc/stat
- private final OsCpuUsage allCpuUsage;
+ private final Id allCpuUsage;
- // read from /proc/self/stat /proc/uptime
- private final ProcessCpuUsage processCpuUsage;
+ private final Id processCpuUsage;
public CpuMeter(Id id) {
- allCpuUsage = new OsCpuUsage(id.withTag(OsMeter.OS_TYPE,
OsMeter.OS_TYPE_ALL_CPU));
- processCpuUsage = new ProcessCpuUsage(id.withTag(OsMeter.OS_TYPE,
OsMeter.OS_TYPE_PROCESS_CPU));
-
- //must refresh all first
- update();
- allCpuUsage.setUsage(0);
- processCpuUsage.setUsage(0);
+ allCpuUsage = id.withTag(OsMeter.OS_TYPE, OsMeter.OS_TYPE_ALL_CPU);
+ processCpuUsage = id.withTag(OsMeter.OS_TYPE, OsMeter.OS_TYPE_PROCESS_CPU);
}
public void calcMeasurements(List<Measurement> measurements, long msNow) {
- update();
- measurements.add(new Measurement(allCpuUsage.getId(), msNow,
allCpuUsage.getUsage()));
- measurements.add(new Measurement(processCpuUsage.getId(), msNow,
processCpuUsage.getUsage()));
- }
-
- public void update() {
- try {
- allCpuUsage.update();
- processCpuUsage.update();
- } catch (Throwable e) {
- LOGGER.error("Failed to update usage", e);
- }
- }
-
- public OsCpuUsage getAllCpuUsage() {
- return allCpuUsage;
+ measurements.add(new Measurement(allCpuUsage, msNow,
osBean.getSystemCpuLoad()));
+ measurements.add(new Measurement(processCpuUsage, msNow,
osBean.getProcessCpuLoad()));
}
- public ProcessCpuUsage getProcessCpuUsage() {
- return processCpuUsage;
+ @VisibleForTesting
+ public void setOsBean(OperatingSystemMXBean bean) {
+ this.osBean = bean;
}
}
diff --git
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/AbstractCpuUsage.java
b/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/AbstractCpuUsage.java
deleted file mode 100644
index 375a64875..000000000
---
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/AbstractCpuUsage.java
+++ /dev/null
@@ -1,65 +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 org.apache.servicecomb.metrics.core.meter.os.cpu;
-
-import com.netflix.spectator.api.Id;
-
-public abstract class AbstractCpuUsage {
-
- protected Id id;
-
- protected double usage;
-
- protected int cpuCount = Runtime.getRuntime().availableProcessors();
-
- static class Period {
- double last;
-
- double period;
-
- void update(double current) {
- period = current - last;
- last = current;
- }
- }
-
- public AbstractCpuUsage(Id id) {
- this.id = id;
- }
-
- public Id getId() {
- return id;
- }
-
- public double getUsage() {
- return usage;
- }
-
- public void setUsage(double usage) {
- this.usage = usage;
- }
-
- protected void updateUsage(double periodBusy, double periodTotal, boolean
irixMode) {
- usage = periodTotal == 0 ? 0 : periodBusy / periodTotal;
- if (usage > 1) {
- usage = 1;
- }
- if (irixMode) {
- usage *= cpuCount;
- }
- }
-}
diff --git
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/CpuUtils.java
b/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/CpuUtils.java
deleted file mode 100644
index 75eb83d9d..000000000
---
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/CpuUtils.java
+++ /dev/null
@@ -1,183 +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 org.apache.servicecomb.metrics.core.meter.os.cpu;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.charset.StandardCharsets;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.io.Files;
-
-public final class CpuUtils {
- private static final Logger LOGGER = LoggerFactory.getLogger(CpuUtils.class);
-
- public static final File PROC_STAT = new File("/proc/stat");
-
- public static final File UPTIME = new File("/proc/uptime");
-
- public static final File SELF_PROCESS = new File("/proc/self/stat");
-
- private CpuUtils() {
- }
-
- public static String[] readAndSplitFirstLine(File file) throws IOException {
- return Files.asCharSource(file,
StandardCharsets.UTF_8).readFirstLine().trim().split("\\s+");
- }
-
- public static double summary(String[] stats, int start, int len) {
- double total = 0;
- for (int idx = start; idx < start + len; idx++) {
- total += Double.parseDouble(stats[idx]);
- }
- return total;
- }
-
- public static double readProcSelfBusy() throws IOException {
- String[] stats = readAndSplitFirstLine(SELF_PROCESS);
- return summary(stats, 13, 2);
- }
-
- public static double readProcStatTotal() throws IOException {
- String[] stats = readAndSplitFirstLine(PROC_STAT);
- return summary(stats, 1, 8);
- }
-
- public static double readUptimeTotal() throws IOException {
- String[] uptime = readAndSplitFirstLine(UPTIME);
- return Double.parseDouble(uptime[0]);
- }
-
- private static boolean isBetween(long x, long lower, long upper) {
- return lower <= x && x <= upper;
- }
-
- /**
- * unit of /proc/uptime is seconds
- * unit of /proc/self/stat is jiffies
- * hence, we should calculate userHZ to get process cpu rate
- *
- * @return userHZ
- */
- public static int calcHertz() {
- double up1, up2, seconds;
- double jiffies;
-
- for (; ; ) {
- try {
- up1 = readUptimeTotal();
- jiffies = readProcStatTotal();
- up2 = readUptimeTotal();
- } catch (Throwable e) {
- LOGGER.error("Failed to calc hertz, should never happened, try
again.", e);
- continue;
- }
-
- if (0 == (long) ((up2 - up1) * 1000.0 / up1)) {
- break;
- }
- }
-
- seconds = (up1 + up2) / 2;
- long hz = Math.round(jiffies / seconds /
Runtime.getRuntime().availableProcessors());
- /* S/390 (sometimes) */
- if (isBetween(hz, 9, 11)) {
- return 10;
- }
-
- /* user-mode Linux */
- if (isBetween(hz, 18, 22)) {
- return 20;
- }
-
- /* ia64 emulator */
- if (isBetween(hz, 30, 34)) {
- return 32;
- }
-
- if (isBetween(hz, 48, 52)) {
- return 50;
- }
-
- if (isBetween(hz, 58, 61)) {
- return 60;
- }
-
- /* StrongARM /Shark */
- if (isBetween(hz, 62, 65)) {
- return 64;
- }
-
- /* normal Linux */
- if (isBetween(hz, 95, 105)) {
- return 100;
- }
-
- /* MIPS, ARM */
- if (isBetween(hz, 124, 132)) {
- return 128;
- }
-
- /* normal << 1 */
- if (isBetween(hz, 195, 204)) {
- return 200;
- }
-
- if (isBetween(hz, 247, 252)) {
- return 250;
- }
-
- if (isBetween(hz, 253, 260)) {
- return 256;
- }
-
- /* normal << 2 */
- if (isBetween(hz, 393, 408)) {
- return 400;
- }
-
- /* SMP WinNT */
- if (isBetween(hz, 410, 600)) {
- return 500;
- }
-
- /* normal << 3 */
- if (isBetween(hz, 790, 808)) {
- return 800;
- }
-
- /* ARM */
- if (isBetween(hz, 990, 1010)) {
- return 1000;
- }
-
- /* Alpha, ia64 */
- if (isBetween(hz, 1015, 1035)) {
- return 1024;
- }
-
- /* Alpha */
- if (isBetween(hz, 1180, 1220)) {
- return 1200;
- }
-
- LOGGER.warn("Unknown HZ value! ({}) Assume {}.\n", hz, 100);
- return 100;
- }
-}
diff --git
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/OsCpuUsage.java
b/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/OsCpuUsage.java
deleted file mode 100644
index 364ca10b4..000000000
---
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/OsCpuUsage.java
+++ /dev/null
@@ -1,52 +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 org.apache.servicecomb.metrics.core.meter.os.cpu;
-
-import java.io.IOException;
-
-import com.netflix.spectator.api.Id;
-
-/*
- * unit : 1 jiffies
- * more details :
- * http://man7.org/linux/man-pages/man5/proc.5.html
- * CMD : /proc/stat
- * cpu 2445171 599297 353967 24490633 11242 0 10780 2993
0 0
- * cpu user nice system idle iowait irq softirq stealstolen
guest guest_nice
- * 0 1 2 3 4 5 6 7 8
9 10
- * total = user + nice + system + idle + iowait + irq + softirq + stealstolen
- * busy = total - idle
- */
-public class OsCpuUsage extends AbstractCpuUsage {
-
- private final Period total = new Period();
-
- private final Period idle = new Period();
-
- public OsCpuUsage(Id id) {
- super(id);
- }
-
- public void update() throws IOException {
- String[] stats = CpuUtils.readAndSplitFirstLine(CpuUtils.PROC_STAT);
- long currentIdle = Long.parseLong(stats[4]);
- double totalCpu = CpuUtils.summary(stats, 1, 8);
- idle.update(currentIdle);
- total.update(totalCpu);
- updateUsage(total.period - idle.period, total.period, false);
- }
-}
diff --git
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/ProcessCpuUsage.java
b/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/ProcessCpuUsage.java
deleted file mode 100644
index 00ec8cb5e..000000000
---
a/metrics/metrics-core/src/main/java/org/apache/servicecomb/metrics/core/meter/os/cpu/ProcessCpuUsage.java
+++ /dev/null
@@ -1,55 +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 org.apache.servicecomb.metrics.core.meter.os.cpu;
-
-import java.io.IOException;
-
-import com.netflix.spectator.api.Id;
-
-/*
- * unit : 1 jiffies
- * more details :
- * http://man7.org/linux/man-pages/man5/proc.5.html
- * CMD : /proc/[pid]/stat
- * 6754 (kubelet) S 1 995 995 0 -1 4202752 193281
592501546 0 12 1152076 907044 87991 113319 ..
- * pid comm state ppid pgrp session tty_nr tpgid flags minflt
cminflt majflt cmajflt utime stime cutime cstime
- * 0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
- * busy = utime + stime
- * CMD: /proc/uptime
- * total = uptime[0] * cpuNum * userHZ
- *
- */
-public class ProcessCpuUsage extends AbstractCpuUsage {
-
- private final Period busy = new Period();
-
- private final Period total = new Period();
-
- private final int userHZ = CpuUtils.calcHertz();
-
- public ProcessCpuUsage(Id id) {
- super(id);
- }
-
- public void update() throws IOException {
- double processBusy = CpuUtils.readProcSelfBusy();
- double uptime = CpuUtils.readUptimeTotal();
- busy.update(processBusy);
- total.update(uptime * userHZ * cpuCount);
- updateUsage(busy.period, total.period, true);
- }
-}
diff --git
a/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/TestOsMeterInitializer.java
b/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/TestOsMeterInitializer.java
index 83bc88bc2..d9ca5fa2e 100644
---
a/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/TestOsMeterInitializer.java
+++
b/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/TestOsMeterInitializer.java
@@ -17,8 +17,6 @@
package org.apache.servicecomb.metrics.core;
import java.io.File;
-import java.lang.management.ManagementFactory;
-import java.lang.management.RuntimeMXBean;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
@@ -29,21 +27,21 @@ import
org.apache.servicecomb.foundation.metrics.registry.GlobalRegistry;
import org.apache.servicecomb.metrics.core.meter.os.CpuMeter;
import org.apache.servicecomb.metrics.core.meter.os.NetMeter;
import org.apache.servicecomb.metrics.core.meter.os.OsMeter;
-import org.apache.servicecomb.metrics.core.meter.os.cpu.CpuUtils;
import org.apache.servicecomb.metrics.core.meter.os.net.InterfaceUsage;
import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.mockito.Mockito;
import com.google.common.eventbus.EventBus;
-import com.google.common.io.Files;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.ManualClock;
+import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Registry;
+import com.sun.management.OperatingSystemMXBean;
-import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
import mockit.Mocked;
-import org.junit.jupiter.api.Assertions;
public class TestOsMeterInitializer {
GlobalRegistry globalRegistry = new GlobalRegistry(new ManualClock());
@@ -54,49 +52,19 @@ public class TestOsMeterInitializer {
EventBus eventBus;
@Test
- public void init(@Mocked Runtime runtime, @Mocked RuntimeMXBean mxBean) {
+ public void init() {
List<String> list = new ArrayList<>();
list.add("13 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1");
list.add("useless");
list.add("eth0: 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0");
- new MockUp<Files>() {
- //Files.readFirstLine
- @Mock
- public String readFirstLine(File file, Charset encoding) {
- return list.get(0);
- }
- };
+
new MockUp<FileUtils>() {
@Mock
public List<String> readLines(File file, Charset encoding) {
return list;
}
};
- new MockUp<CpuUtils>() {
- @Mock
- public int calcHertz() {
- return 100;
- }
- };
- new MockUp<ManagementFactory>() {
- @Mock
- RuntimeMXBean getRuntimeMXBean() {
- return mxBean;
- }
- };
- new MockUp<Runtime>() {
- @Mock
- public Runtime getRuntime() {
- return runtime;
- }
- };
- new Expectations() {
- {
- runtime.availableProcessors();
- result = 2;
- }
- };
globalRegistry.add(registry);
OsMetersInitializer osMetersInitializer = new OsMetersInitializer();
osMetersInitializer.setOsLinux(true);
@@ -106,10 +74,15 @@ public class TestOsMeterInitializer {
Assertions.assertNotNull(osMeter.getCpuMeter());
Assertions.assertNotNull(osMeter.getNetMeter());
CpuMeter cpuMeter = osMeter.getCpuMeter();
+ OperatingSystemMXBean systemMXBean =
Mockito.mock(OperatingSystemMXBean.class);
+ Mockito.when(systemMXBean.getSystemCpuLoad()).thenReturn(0.2);
+ Mockito.when(systemMXBean.getProcessCpuLoad()).thenReturn(0.1);
+ cpuMeter.setOsBean(systemMXBean);
NetMeter netMeter = osMeter.getNetMeter();
- Assertions.assertEquals(0.0, cpuMeter.getProcessCpuUsage().getUsage(),
0.0);
-
- Assertions.assertEquals(0.0, cpuMeter.getAllCpuUsage().getUsage(), 0.0);
+ List<Measurement> measurements = new ArrayList<>();
+ cpuMeter.calcMeasurements(measurements, 0);
+ Assertions.assertEquals(0.2, measurements.get(0).value(), 0.0);
+ Assertions.assertEquals(0.1, measurements.get(1).value(), 0.0);
Map<String, InterfaceUsage> interfaceInfoMap =
netMeter.getInterfaceUsageMap();
Assertions.assertEquals(1, interfaceInfoMap.size());
diff --git
a/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/meter/os/TestCpuMeter.java
b/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/meter/os/TestCpuMeter.java
index 8295bdcee..1d73f20cc 100644
---
a/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/meter/os/TestCpuMeter.java
+++
b/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/meter/os/TestCpuMeter.java
@@ -16,177 +16,75 @@
*/
package org.apache.servicecomb.metrics.core.meter.os;
-import java.io.File;
import java.io.IOException;
-import java.lang.management.ManagementFactory;
-import java.lang.management.RuntimeMXBean;
-import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
-import org.apache.servicecomb.metrics.core.meter.os.cpu.CpuUtils;
import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.mockito.Mockito;
-import com.google.common.io.CharSource;
-import com.google.common.io.Files;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Measurement;
+import com.sun.management.OperatingSystemMXBean;
-import mockit.Expectations;
-import mockit.Mock;
-import mockit.MockUp;
import mockit.Mocked;
-import org.junit.jupiter.api.Assertions;
public class TestCpuMeter {
@Test
- public void testRefreshCpuSuccess(@Mocked Id id, @Mocked Runtime runtime,
@Mocked RuntimeMXBean mxBean,
- @Mocked CharSource charSource) throws IOException {
- new MockUp<Files>() {
- @Mock
- public CharSource asCharSource(File file, Charset encoding) {
- return charSource;
- }
- };
- new MockUp<ManagementFactory>() {
- @Mock
- RuntimeMXBean getRuntimeMXBean() {
- return mxBean;
- }
- };
- new MockUp<CpuUtils>() {
- @Mock
- public int calcHertz() {
- return 4;
- }
- };
- new MockUp<Runtime>() {
- @Mock
- public Runtime getRuntime() {
- return runtime;
- }
- };
- new Expectations() {
- {
- runtime.availableProcessors();
- result = 2;
- charSource.readFirstLine();
- result = "1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1";
- }
- };
+ public void testRefreshCpuSuccess(@Mocked Id id) throws IOException {
+
CpuMeter cpuMeter = new CpuMeter(id);
- Assertions.assertEquals(0.0, cpuMeter.getAllCpuUsage().getUsage(), 0.0);
- Assertions.assertEquals(0.0, cpuMeter.getProcessCpuUsage().getUsage(),
0.0);
-
- new Expectations() {
- {
- charSource.readFirstLine();
- result = "2 2 2 2 2 2 2 2 2 0 0 2 2 2 2 2 2 2 2 2 2";
- }
- };
- cpuMeter.update();
-
- Assertions.assertEquals(0.875, cpuMeter.getAllCpuUsage().getUsage(), 0.0);
- Assertions.assertEquals(0.5, cpuMeter.getProcessCpuUsage().getUsage(),
0.0);
+ OperatingSystemMXBean systemMXBean =
Mockito.mock(OperatingSystemMXBean.class);
+ Mockito.when(systemMXBean.getSystemCpuLoad()).thenReturn(0.2);
+ Mockito.when(systemMXBean.getProcessCpuLoad()).thenReturn(0.1);
+ cpuMeter.setOsBean(systemMXBean);
+ List<Measurement> measurements = new ArrayList<>();
+ cpuMeter.calcMeasurements(measurements, 0);
+
+ Assertions.assertEquals(0.2, measurements.get(0).value(), 0.0);
+ Assertions.assertEquals(0.1, measurements.get(1).value(), 0.0);
+
+ Mockito.when(systemMXBean.getSystemCpuLoad()).thenReturn(0.875);
+ Mockito.when(systemMXBean.getProcessCpuLoad()).thenReturn(0.5);
+ measurements = new ArrayList<>();
+ cpuMeter.calcMeasurements(measurements, 0);
+
+ Assertions.assertEquals(0.875, measurements.get(0).value(), 0.0);
+ Assertions.assertEquals(0.5, measurements.get(1).value(), 0.0);
}
@Test
- public void testRefreshError(@Mocked Id id, @Mocked Runtime runtime, @Mocked
RuntimeMXBean mxBean,
- @Mocked CharSource charSource) throws IOException {
-
- new MockUp<Files>() {
- @Mock
- public CharSource asCharSource(File file, Charset encoding) {
- return charSource;
- }
- };
- new MockUp<CpuUtils>() {
- @Mock
- public int calcHertz() {
- return 4;
- }
- };
- new MockUp<ManagementFactory>() {
- @Mock
- RuntimeMXBean getRuntimeMXBean() {
- return mxBean;
- }
- };
- new MockUp<Runtime>() {
- @Mock
- public Runtime getRuntime() {
- return runtime;
- }
- };
- new Expectations() {
- {
- runtime.availableProcessors();
- result = 2;
- charSource.readFirstLine();
- result = "1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1";
- }
- };
+ public void testRefreshError(@Mocked Id id) throws IOException {
+
CpuMeter cpuMeter = new CpuMeter(id);
- Assertions.assertEquals(0.0, cpuMeter.getAllCpuUsage().getUsage(), 0.0);
- Assertions.assertEquals(0.0, cpuMeter.getProcessCpuUsage().getUsage(),
0.0);
- new Expectations() {
- {
- charSource.readFirstLine();
- result = "1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1";
- }
- };
- cpuMeter.update();
-
- Assertions.assertEquals(0.0, cpuMeter.getAllCpuUsage().getUsage(), 0.0);
- Assertions.assertEquals(0.0, cpuMeter.getProcessCpuUsage().getUsage(),
0.0);
+ OperatingSystemMXBean systemMXBean =
Mockito.mock(OperatingSystemMXBean.class);
+ Mockito.when(systemMXBean.getSystemCpuLoad()).thenReturn(0.2);
+ Mockito.when(systemMXBean.getProcessCpuLoad()).thenReturn(0.1);
+ cpuMeter.setOsBean(systemMXBean);
+ List<Measurement> measurements = new ArrayList<>();
+ cpuMeter.calcMeasurements(measurements, 0);
+
+ Assertions.assertEquals(0.2, measurements.get(0).value(), 0.0);
+ Assertions.assertEquals(0.1, measurements.get(1).value(), 0.0);
+
+ cpuMeter.calcMeasurements(measurements, 0);
+
+ Assertions.assertEquals(0.2, measurements.get(0).value(), 0.0);
+ Assertions.assertEquals(0.1, measurements.get(1).value(), 0.0);
}
@Test
- public void testCalcMeasurements(@Mocked Id id, @Mocked Runtime runtime,
@Mocked RuntimeMXBean mxBean,
- @Mocked CharSource charSource) throws IOException {
+ public void testCalcMeasurements(@Mocked Id id) throws IOException {
List<Measurement> measurements = new ArrayList<>();
- new MockUp<Files>() {
- @Mock
- public CharSource asCharSource(File file, Charset encoding) {
- return charSource;
- }
- };
- new MockUp<CpuUtils>() {
- @Mock
- public int calcHertz() {
- return 4;
- }
- };
- new MockUp<ManagementFactory>() {
- @Mock
- RuntimeMXBean getRuntimeMXBean() {
- return mxBean;
- }
- };
- new MockUp<Runtime>() {
- @Mock
- public Runtime getRuntime() {
- return runtime;
- }
- };
- new Expectations() {
- {
- runtime.availableProcessors();
- result = 2;
- charSource.readFirstLine();
- result = "1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1";
- }
- };
CpuMeter cpuMeter = new CpuMeter(id);
+ OperatingSystemMXBean systemMXBean =
Mockito.mock(OperatingSystemMXBean.class);
+ Mockito.when(systemMXBean.getSystemCpuLoad()).thenReturn(0.875);
+ Mockito.when(systemMXBean.getProcessCpuLoad()).thenReturn(0.5);
+ cpuMeter.setOsBean(systemMXBean);
- new Expectations() {
- {
- charSource.readFirstLine();
- result = "2 2 2 2 2 2 2 2 2 0 0 2 2 2 2 2 2 2 2 2 2";
- }
- };
cpuMeter.calcMeasurements(measurements, 0);
Assertions.assertEquals(2, measurements.size());
Measurement measurement = measurements.get(0);
diff --git
a/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/meter/os/TestOsMeter.java
b/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/meter/os/TestOsMeter.java
index 375627d9b..4aaeedc59 100644
---
a/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/meter/os/TestOsMeter.java
+++
b/metrics/metrics-core/src/test/java/org/apache/servicecomb/metrics/core/meter/os/TestOsMeter.java
@@ -19,36 +19,30 @@ package org.apache.servicecomb.metrics.core.meter.os;
import java.io.File;
import java.io.IOException;
-import java.lang.management.ManagementFactory;
-import java.lang.management.RuntimeMXBean;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
-import org.apache.servicecomb.metrics.core.meter.os.cpu.CpuUtils;
import org.junit.Test;
+import org.junit.jupiter.api.Assertions;
+import org.mockito.Mockito;
import com.google.common.collect.Lists;
-import com.google.common.io.CharSource;
-import com.google.common.io.Files;
import com.netflix.spectator.api.DefaultRegistry;
import com.netflix.spectator.api.ManualClock;
import com.netflix.spectator.api.Measurement;
import com.netflix.spectator.api.Registry;
+import com.sun.management.OperatingSystemMXBean;
-import mockit.Expectations;
import mockit.Mock;
import mockit.MockUp;
-import mockit.Mocked;
-import org.junit.jupiter.api.Assertions;
public class TestOsMeter {
Registry registry = new DefaultRegistry(new ManualClock());
@Test
- public void testCalcMeasurement(@Mocked Runtime runtime, @Mocked
RuntimeMXBean mxBean,
- @Mocked CharSource charSource) throws IOException {
+ public void testCalcMeasurement() throws IOException {
List<String> list = new ArrayList<>();
list.add("useless");
list.add("useless");
@@ -59,49 +53,18 @@ public class TestOsMeter {
return list;
}
};
- new MockUp<CpuUtils>() {
- @Mock
- public int calcHertz() {
- return 4;
- }
- };
- new MockUp<Files>() {
- @Mock
- public CharSource asCharSource(File file, Charset encoding) {
- return charSource;
- }
- };
- new MockUp<ManagementFactory>() {
- @Mock
- RuntimeMXBean getRuntimeMXBean() {
- return mxBean;
- }
- };
- new MockUp<Runtime>() {
- @Mock
- public Runtime getRuntime() {
- return runtime;
- }
- };
- new Expectations() {
- {
- runtime.availableProcessors();
- result = 2;
- charSource.readFirstLine();
- result = "1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1";
- }
- };
+
OsMeter osMeter = new OsMeter(registry);
list.clear();
list.add("useless");
list.add("useless");
list.add("eth0: 1 1 0 0 0 0 0 1 1 1
1 0 0 0 0 0");
- new Expectations() {
- {
- charSource.readFirstLine();
- result = "2 2 2 2 2 2 2 2 2 0 0 2 2 2 2 2 2 2 2 2 2";
- }
- };
+
+ OperatingSystemMXBean systemMXBean =
Mockito.mock(OperatingSystemMXBean.class);
+ Mockito.when(systemMXBean.getSystemCpuLoad()).thenReturn(0.875);
+ Mockito.when(systemMXBean.getProcessCpuLoad()).thenReturn(0.5);
+ osMeter.getCpuMeter().setOsBean(systemMXBean);
+
osMeter.calcMeasurements(1, 1);
ArrayList<Measurement> measurements =
Lists.newArrayList(osMeter.measure());
Assertions.assertEquals(6, measurements.size());