View Javadoc
1   /*
2    * Copyright 2020-2022 The OSHI Project Contributors
3    * SPDX-License-Identifier: MIT
4    */
5   package oshi.driver.unix.aix;
6   
7   import java.util.regex.Matcher;
8   import java.util.regex.Pattern;
9   
10  import oshi.annotation.concurrent.ThreadSafe;
11  import oshi.util.ExecutingCommand;
12  import oshi.util.ParseUtil;
13  
14  /**
15   * Utility to query up time.
16   */
17  @ThreadSafe
18  public final class Uptime {
19  
20      private static final long MINUTE_MS = 60L * 1000L;
21      private static final long HOUR_MS = 60L * MINUTE_MS;
22      private static final long DAY_MS = 24L * HOUR_MS;
23  
24      // sample format:
25      // 18:36pm up 10 days 8:11, 2 users, load average: 3.14, 2.74, 2.41
26  
27      private static final Pattern UPTIME_FORMAT_AIX = Pattern
28              .compile(".*\\sup\\s+((\\d+)\\s+days?,?\\s+)?\\b((\\d+):)?(\\d+)(\\s+min(utes?)?)?,\\s+\\d+\\s+user.+"); // NOSONAR:squid:S5843
29  
30      private Uptime() {
31      }
32  
33      /**
34       * Query {@code uptime} to get up time
35       *
36       * @return Up time in milliseconds
37       */
38      public static long queryUpTime() {
39          long uptime = 0L;
40          String s = ExecutingCommand.getFirstAnswer("uptime");
41          if (s.isEmpty()) {
42              s = ExecutingCommand.getFirstAnswer("w");
43          }
44          if (s.isEmpty()) {
45              s = ExecutingCommand.getFirstAnswer("/usr/bin/uptime");
46          }
47          Matcher m = UPTIME_FORMAT_AIX.matcher(s);
48          if (m.matches()) {
49              if (m.group(2) != null) {
50                  uptime += ParseUtil.parseLongOrDefault(m.group(2), 0L) * DAY_MS;
51              }
52              if (m.group(4) != null) {
53                  uptime += ParseUtil.parseLongOrDefault(m.group(4), 0L) * HOUR_MS;
54              }
55              uptime += ParseUtil.parseLongOrDefault(m.group(5), 0L) * MINUTE_MS;
56          }
57          return uptime;
58      }
59  }