View Javadoc
1   /*
2    * Copyright 2022-2023 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.driver.windows.perfmon;
6   
7   import java.util.Locale;
8   
9   import org.slf4j.Logger;
10  import org.slf4j.LoggerFactory;
11  
12  import com.sun.jna.platform.win32.Advapi32Util;
13  import com.sun.jna.platform.win32.WinReg;
14  
15  import oshi.annotation.concurrent.ThreadSafe;
16  import oshi.util.GlobalConfig;
17  import oshi.util.Util;
18  
19  /**
20   * Tests whether performance counters are disabled
21   */
22  @ThreadSafe
23  public final class PerfmonDisabled {
24  
25      private static final Logger LOG = LoggerFactory.getLogger(PerfmonDisabled.class);
26  
27      public static final boolean PERF_OS_DISABLED = isDisabled(GlobalConfig.OSHI_OS_WINDOWS_PERFOS_DIABLED, "PerfOS");
28      public static final boolean PERF_PROC_DISABLED = isDisabled(GlobalConfig.OSHI_OS_WINDOWS_PERFPROC_DIABLED,
29              "PerfProc");
30      public static final boolean PERF_DISK_DISABLED = isDisabled(GlobalConfig.OSHI_OS_WINDOWS_PERFDISK_DIABLED,
31              "PerfDisk");
32  
33      /**
34       * Everything in this class is static, never instantiate it
35       */
36      private PerfmonDisabled() {
37          throw new AssertionError();
38      }
39  
40      private static boolean isDisabled(String config, String service) {
41          String perfDisabled = GlobalConfig.get(config);
42          // If null or empty, check registry
43          if (Util.isBlank(perfDisabled)) {
44              String key = String.format(Locale.ROOT, "SYSTEM\\CurrentControlSet\\Services\\%s\\Performance", service);
45              String value = "Disable Performance Counters";
46              // If disabled in registry, log warning and return
47              if (Advapi32Util.registryValueExists(WinReg.HKEY_LOCAL_MACHINE, key, value)) {
48                  Object disabled = Advapi32Util.registryGetValue(WinReg.HKEY_LOCAL_MACHINE, key, value);
49                  if (disabled instanceof Integer) {
50                      if ((Integer) disabled > 0) {
51                          LOG.warn("{} counters are disabled and won't return data: {}\\\\{}\\\\{} > 0.", service,
52                                  "HKEY_LOCAL_MACHINE", key, value);
53                          return true;
54                      }
55                  } else {
56                      LOG.warn(
57                              "Invalid registry value type detected for {} counters. Should be REG_DWORD. Ignoring: {}\\\\{}\\\\{}.",
58                              service, "HKEY_LOCAL_MACHINE", key, value);
59                  }
60              }
61              return false;
62          }
63          // If not null or empty, parse as boolean
64          return Boolean.parseBoolean(perfDisabled);
65      }
66  }