OSUtils.java 14.7 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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.
 */
Q
qiaozhanwei 已提交
17
package org.apache.dolphinscheduler.common.utils;
L
ligang 已提交
18 19 20 21 22 23 24 25 26 27

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
28 29
import java.util.Arrays;
import java.util.Collections;
L
ligang 已提交
30
import java.util.List;
31 32
import java.util.Optional;
import java.util.StringTokenizer;
33
import java.util.regex.Pattern;
L
ligang 已提交
34

35 36 37 38 39 40 41 42 43 44 45
import org.apache.commons.configuration.Configuration;
import org.apache.dolphinscheduler.common.Constants;
import org.apache.dolphinscheduler.common.shell.ShellExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import oshi.hardware.HardwareAbstractionLayer;

L
ligang 已提交
46 47 48 49 50 51 52 53
/**
 * os utils
 *
 */
public class OSUtils {

  private static final Logger logger = LoggerFactory.getLogger(OSUtils.class);

54 55
  public static final ThreadLocal<Logger> taskLoggerThreadLocal = new ThreadLocal<>();

L
ligang 已提交
56 57 58
  private static final SystemInfo SI = new SystemInfo();
  public static final String TWO_DECIMAL = "0.00";

59 60 61 62 63 64
  /**
   * return -1 when the function can not get hardware env info
   * e.g {@link OSUtils#loadAverage()} {@link OSUtils#cpuUsage()}
   */
  public static final double NEGATIVE_ONE = -1;

L
ligang 已提交
65 66 67 68
  private static HardwareAbstractionLayer hal = SI.getHardware();

  private OSUtils() {}

69 70 71 72 73 74
  /**
   * Initialization regularization, solve the problem of pre-compilation performance,
   * avoid the thread safety problem of multi-thread operation
   */
  private static final Pattern PATTERN = Pattern.compile("\\s+");

L
ligang 已提交
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125

  /**
   * get memory usage
   * Keep 2 decimal
   * @return  percent %
   */
  public static double memoryUsage() {
    GlobalMemory memory = hal.getMemory();
    double memoryUsage = (memory.getTotal() - memory.getAvailable() - memory.getSwapUsed()) * 0.1 / memory.getTotal() * 10;

    DecimalFormat df = new DecimalFormat(TWO_DECIMAL);
    df.setRoundingMode(RoundingMode.HALF_UP);
    return Double.parseDouble(df.format(memoryUsage));
  }


  /**
   * get available physical memory size
   *
   * Keep 2 decimal
   * @return  available Physical Memory Size, unit: G
   */
  public static double availablePhysicalMemorySize() {
    GlobalMemory memory = hal.getMemory();
    double  availablePhysicalMemorySize = (memory.getAvailable() + memory.getSwapUsed()) /1024.0/1024/1024;

    DecimalFormat df = new DecimalFormat(TWO_DECIMAL);
    df.setRoundingMode(RoundingMode.HALF_UP);
    return Double.parseDouble(df.format(availablePhysicalMemorySize));

  }

  /**
   * get total physical memory size
   *
   * Keep 2 decimal
   * @return  available Physical Memory Size, unit: G
   */
  public static double totalMemorySize() {
    GlobalMemory memory = hal.getMemory();
    double  availablePhysicalMemorySize = memory.getTotal() /1024.0/1024/1024;

    DecimalFormat df = new DecimalFormat(TWO_DECIMAL);
    df.setRoundingMode(RoundingMode.HALF_UP);
    return Double.parseDouble(df.format(availablePhysicalMemorySize));
  }


  /**
   * load average
   *
D
dailidong 已提交
126
   * @return load average
L
ligang 已提交
127 128 129
   */
  public static double loadAverage() {
    double loadAverage =  hal.getProcessor().getSystemLoadAverage();
130 131 132
    if (Double.isNaN(loadAverage)) {
      return NEGATIVE_ONE;
    }
L
ligang 已提交
133 134 135 136 137 138 139 140 141

    DecimalFormat df = new DecimalFormat(TWO_DECIMAL);
    df.setRoundingMode(RoundingMode.HALF_UP);
    return Double.parseDouble(df.format(loadAverage));
  }

  /**
   * get cpu usage
   *
D
dailidong 已提交
142
   * @return cpu usage
L
ligang 已提交
143 144 145 146
   */
  public static double cpuUsage() {
    CentralProcessor processor = hal.getProcessor();
    double cpuUsage = processor.getSystemCpuLoad();
147 148 149
    if (Double.isNaN(cpuUsage)) {
      return NEGATIVE_ONE;
    }
L
ligang 已提交
150 151 152 153 154 155

    DecimalFormat df = new DecimalFormat(TWO_DECIMAL);
    df.setRoundingMode(RoundingMode.HALF_UP);
    return Double.parseDouble(df.format(cpuUsage));
  }

156 157 158 159 160
  public static List<String> getUserList() {
    try {
      if (isMacOS()) {
        return getUserListFromMac();
      } else if (isWindows()) {
161
        return getUserListFromWindows();
162 163 164 165 166 167 168 169 170
      } else {
        return getUserListFromLinux();
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }

    return Collections.emptyList();
  }
L
ligang 已提交
171 172

  /**
173
   * get user list from linux
L
ligang 已提交
174
   *
D
dailidong 已提交
175
   * @return user list
L
ligang 已提交
176
   */
177
  private static List<String> getUserListFromLinux() throws IOException {
L
ligang 已提交
178 179
    List<String> userList = new ArrayList<>();

180 181
    try (BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(new FileInputStream("/etc/passwd")))) {
L
ligang 已提交
182 183 184 185 186 187 188 189
      String line;

      while ((line = bufferedReader.readLine()) != null) {
        if (line.contains(":")) {
          String[] userInfo = line.split(":");
          userList.add(userInfo[0]);
        }
      }
190 191 192 193 194 195 196 197 198 199 200 201
    }

    return userList;
  }

  /**
   * get user list from mac
   * @return user list
   */
  private static List<String> getUserListFromMac() throws IOException {
    String result = exeCmd("dscl . list /users");
    if (StringUtils.isNotEmpty(result)) {
T
Tboy 已提交
202
      return Arrays.asList(result.split( "\n"));
203 204 205 206 207
    }

    return Collections.emptyList();
  }

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
  /**
   *  get user list from windows
   * @return user list
   * @throws IOException
   */
  private static List<String> getUserListFromWindows() throws IOException {
    String result = exeCmd("net user");
    String[] lines = result.split("\n");

    int startPos = 0;
    int endPos = lines.length - 2;
    for (int i = 0; i < lines.length; i++) {
      if (lines[i].isEmpty()) {
        continue;
      }

      int count = 0;
      if (lines[i].charAt(0) == '-') {
        for (int j = 0; j < lines[i].length(); j++) {
          if (lines[i].charAt(i) == '-') {
            count++;
          }
        }
      }

      if (count == lines[i].length()) {
        startPos = i + 1;
        break;
      }
    }

    List<String> users = new ArrayList<>();
    while (startPos <= endPos) {
241
      users.addAll(Arrays.asList(PATTERN.split(lines[startPos])));
242 243 244 245 246 247
      startPos++;
    }

    return users;
  }

248 249 250 251 252 253 254 255 256
  /**
   * create user
   * @param userName user name
   * @return true if creation was successful, otherwise false
   */
  public static boolean createUser(String userName) {
    try {
      String userGroup = OSUtils.getGroup();
      if (StringUtils.isEmpty(userGroup)) {
257 258 259
        String errorLog = String.format("%s group does not exist for this operating system.", userGroup);
        LoggerUtils.logError(Optional.ofNullable(logger), errorLog);
        LoggerUtils.logError(Optional.ofNullable(taskLoggerThreadLocal.get()), errorLog);
260 261 262 263 264
        return false;
      }
      if (isMacOS()) {
        createMacUser(userName, userGroup);
      } else if (isWindows()) {
265
        createWindowsUser(userName, userGroup);
266 267 268 269
      } else {
        createLinuxUser(userName, userGroup);
      }
      return true;
L
ligang 已提交
270
    } catch (Exception e) {
271 272
      LoggerUtils.logError(Optional.ofNullable(logger), e);
      LoggerUtils.logError(Optional.ofNullable(taskLoggerThreadLocal.get()), e);
L
ligang 已提交
273 274
    }

275 276 277 278 279 280 281 282 283 284
    return false;
  }

  /**
   * create linux user
   * @param userName user name
   * @param userGroup user group
   * @throws IOException in case of an I/O error
   */
  private static void createLinuxUser(String userName, String userGroup) throws IOException {
285 286 287
    String infoLog1 = String.format("create linux os user : %s", userName);
    LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog1);
    LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog1);
288

289 290 291 292
    String cmd = String.format("sudo useradd -g %s %s", userGroup, userName);
    String infoLog2 = String.format("execute cmd : %s", cmd);
    LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog2);
    LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog2);
293 294 295 296 297 298 299 300 301 302 303
    OSUtils.exeCmd(cmd);
  }

  /**
   * create mac user (Supports Mac OSX 10.10+)
   * @param userName user name
   * @param userGroup user group
   * @throws IOException in case of an I/O error
   */
  private static void createMacUser(String userName, String userGroup) throws IOException {

304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    Optional<Logger> optionalLogger = Optional.ofNullable(logger);
    Optional<Logger> optionalTaskLogger = Optional.ofNullable(taskLoggerThreadLocal.get());

    String infoLog1 = String.format("create mac os user : %s", userName);
    LoggerUtils.logInfo(optionalLogger, infoLog1);
    LoggerUtils.logInfo(optionalTaskLogger, infoLog1);

    String createUserCmd = String.format("sudo sysadminctl -addUser %s -password %s", userName, userName);
    String infoLog2 = String.format("create user command : %s", createUserCmd);
    LoggerUtils.logInfo(optionalLogger, infoLog2);
    LoggerUtils.logInfo(optionalTaskLogger, infoLog2);
    OSUtils.exeCmd(createUserCmd);

    String appendGroupCmd = String.format("sudo dseditgroup -o edit -a %s -t user %s", userName, userGroup);
    String infoLog3 = String.format("append user to group : %s", appendGroupCmd);
    LoggerUtils.logInfo(optionalLogger, infoLog3);
    LoggerUtils.logInfo(optionalTaskLogger, infoLog3);
321
    OSUtils.exeCmd(appendGroupCmd);
L
ligang 已提交
322 323
  }

324 325 326 327 328 329 330
  /**
   * create windows user
   * @param userName user name
   * @param userGroup user group
   * @throws IOException in case of an I/O error
   */
  private static void createWindowsUser(String userName, String userGroup) throws IOException {
331 332 333
    String infoLog1 = String.format("create windows os user : %s", userName);
    LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog1);
    LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog1);
334

335 336 337 338
    String userCreateCmd = String.format("net user \"%s\" /add", userName);
    String infoLog2 = String.format("execute create user command : %s", userCreateCmd);
    LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog2);
    LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog2);
339 340
    OSUtils.exeCmd(userCreateCmd);

341 342 343 344
    String appendGroupCmd = String.format("net localgroup \"%s\" \"%s\" /add", userGroup, userName);
    String infoLog3 = String.format("execute append user to group : %s", appendGroupCmd);
    LoggerUtils.logInfo(Optional.ofNullable(logger), infoLog3);
    LoggerUtils.logInfo(Optional.ofNullable(taskLoggerThreadLocal.get()), infoLog3);
345 346 347
    OSUtils.exeCmd(appendGroupCmd);
  }

L
ligang 已提交
348 349
  /**
   * get system group information
D
dailidong 已提交
350 351
   * @return system group info
   * @throws IOException errors
L
ligang 已提交
352 353
   */
  public static String getGroup() throws IOException {
354 355 356 357
    if (isWindows()) {
      String currentProcUserName = System.getProperty("user.name");
      String result = exeCmd(String.format("net user \"%s\"", currentProcUserName));
      String line = result.split("\n")[22];
358
      String group = PATTERN.split(line)[1];
359 360 361 362 363 364 365 366 367 368 369
      if (group.charAt(0) == '*') {
        return group.substring(1);
      } else {
        return group;
      }
    } else {
      String result = exeCmd("groups");
      if (StringUtils.isNotEmpty(result)) {
        String[] groupInfo = result.split(" ");
        return groupInfo[0];
      }
L
ligang 已提交
370 371 372 373 374 375 376 377
    }

    return null;
  }

  /**
   * Execute the corresponding command of Linux or Windows
   *
D
dailidong 已提交
378 379 380
   * @param command command
   * @return result of execute command
   * @throws IOException errors
L
ligang 已提交
381 382
   */
  public static String exeCmd(String command) throws IOException {
383 384 385 386
    StringTokenizer st = new StringTokenizer(command);
    String[] cmdArray = new String[st.countTokens()];
    for (int i = 0; st.hasMoreTokens(); i++) {
      cmdArray[i] = st.nextToken();
L
ligang 已提交
387
    }
388
    return exeShell(cmdArray);
L
ligang 已提交
389 390 391 392
  }

  /**
   * Execute the shell
D
dailidong 已提交
393 394 395
   * @param command command
   * @return result of execute the shell
   * @throws IOException errors
L
ligang 已提交
396
   */
397
  public static String exeShell(String[] command) throws IOException {
journey2018's avatar
journey2018 已提交
398
    return ShellExecutor.execCommand(command);
L
ligang 已提交
399 400 401 402
  }

  /**
   * get process id
D
dailidong 已提交
403
   * @return process id
L
ligang 已提交
404 405 406 407 408 409 410 411
   */
  public static int getProcessID() {
    RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
    return Integer.parseInt(runtimeMXBean.getName().split("@")[0]);
  }

  /**
   * whether is macOS
D
dailidong 已提交
412
   * @return true if mac
L
ligang 已提交
413 414
   */
  public static boolean isMacOS() {
415
    return getOSName().startsWith("Mac");
L
ligang 已提交
416 417 418 419 420
  }


  /**
   * whether is windows
D
dailidong 已提交
421
   * @return true if windows
L
ligang 已提交
422
   */
423
  public static boolean isWindows() {
424 425 426 427 428 429 430 431 432
    return getOSName().startsWith("Windows");
  }

  /**
   * get current OS name
   * @return current OS name
   */
  public static String getOSName() {
    return System.getProperty("os.name");
L
ligang 已提交
433 434
  }

B
bao liang 已提交
435 436
  /**
   * check memory and cpu usage
437 438
   * @param systemCpuLoad systemCpuLoad
   * @param systemReservedMemory systemReservedMemory
B
bao liang 已提交
439 440 441
   * @return check memory and cpu usage
   */
  public static Boolean checkResource(double systemCpuLoad, double systemReservedMemory){
442
    // system load average
B
bao liang 已提交
443
    double loadAverage = OSUtils.loadAverage();
444
    // system available physical memory
B
bao liang 已提交
445 446 447
    double availablePhysicalMemorySize = OSUtils.availablePhysicalMemorySize();

    if(loadAverage > systemCpuLoad || availablePhysicalMemorySize < systemReservedMemory){
448
      logger.warn("load is too high or availablePhysicalMemorySize(G) is too low, it's availablePhysicalMemorySize(G):{},loadAvg:{}", availablePhysicalMemorySize , loadAverage);
B
bao liang 已提交
449 450 451 452 453
      return false;
    }else{
      return true;
    }
  }
L
ligang 已提交
454 455 456

  /**
   * check memory and cpu usage
D
dailidong 已提交
457 458 459
   * @param conf conf
   * @param isMaster is master
   * @return check memory and cpu usage
L
ligang 已提交
460 461 462 463 464
   */
  public static Boolean checkResource(Configuration conf, Boolean isMaster){
    double systemCpuLoad;
    double systemReservedMemory;

465 466 467
    if(Boolean.TRUE.equals(isMaster)){
      systemCpuLoad = conf.getDouble(Constants.MASTER_MAX_CPULOAD_AVG, Constants.DEFAULT_MASTER_CPU_LOAD);
      systemReservedMemory = conf.getDouble(Constants.MASTER_RESERVED_MEMORY, Constants.DEFAULT_MASTER_RESERVED_MEMORY);
L
ligang 已提交
468
    }else{
469 470
      systemCpuLoad = conf.getDouble(Constants.WORKER_MAX_CPULOAD_AVG, Constants.DEFAULT_WORKER_CPU_LOAD);
      systemReservedMemory = conf.getDouble(Constants.WORKER_RESERVED_MEMORY, Constants.DEFAULT_WORKER_RESERVED_MEMORY);
L
ligang 已提交
471
    }
472
    return checkResource(systemCpuLoad,systemReservedMemory);
L
ligang 已提交
473 474 475
  }

}