/** * Gets the primary group name from the user name. * * @param userName the user name * @return group name */ public static String getGroupName(String userName) throws IOException { return ShellUtils.execCommand("id", "-ng", userName).trim(); }
/** * Checks whether a path is the mounting point of a RAM disk volume. * * @param path a string represents the path to be checked * @param fsTypes an array of strings represents expected file system type * @return true if the path is the mounting point of volume with one of the given fsTypes, * false otherwise * @throws IOException if the function fails to get the mount information of the system */ public static boolean isMountingPoint(String path, String[] fsTypes) throws IOException { List<UnixMountInfo> infoList = ShellUtils.getUnixMountInfo(); for (UnixMountInfo info : infoList) { Optional<String> mountPoint = info.getMountPoint(); Optional<String> fsType = info.getFsType(); if (mountPoint.isPresent() && mountPoint.get().equals(path) && fsType.isPresent()) { for (String expectedType : fsTypes) { if (fsType.get().equalsIgnoreCase(expectedType)) { return true; } } } } return false; }
/** * Gets the current user's group list from Unix by running the command 'groups' NOTE. For * non-existing user it will return EMPTY list. This method may return duplicate groups. * * @param user user name * @return the groups list that the {@code user} belongs to. The primary group is returned first */ public static List<String> getUnixGroups(String user) throws IOException { String result; List<String> groups = new ArrayList<>(); try { result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(user)); } catch (ExitCodeException e) { // if we didn't get the group - just return empty list LOG.warn("got exception trying to get groups for user " + user + ": " + e.getMessage()); return groups; } StringTokenizer tokenizer = new StringTokenizer(result, ShellUtils.TOKEN_SEPARATOR_REGEX); while (tokenizer.hasMoreTokens()) { groups.add(tokenizer.nextToken()); } return groups; }
/** * Gets system mount information. This method should only be attempted on Unix systems. * * @return system mount information */ public static List<UnixMountInfo> getUnixMountInfo() throws IOException { Preconditions.checkState(OSUtils.isLinux() || OSUtils.isMacOS()); String output = execCommand(MOUNT_COMMAND); List<UnixMountInfo> mountInfo = new ArrayList<>(); for (String line : output.split("\n")) { mountInfo.add(parseMountInfo(line)); } return mountInfo; }
@Test public void parseRamfsMountInfoWithType() throws Exception { // Linux mount info. UnixMountInfo info = ShellUtils.parseMountInfo("ramfs on /mnt/ramdisk type ramfs (rw,relatime,size=1gb)"); assertEquals(Optional.of("ramfs"), info.getDeviceSpec()); assertEquals(Optional.of("/mnt/ramdisk"), info.getMountPoint()); assertEquals(Optional.of("ramfs"), info.getFsType()); assertEquals(Optional.of(Long.valueOf(Constants.GB)), info.getOptions().getSize()); }
/** * @param line the line to parse * @return the parsed {@link UnixMountInfo} */ public static UnixMountInfo parseMountInfo(String line) { // Example mount lines: // ramfs on /mnt/ramdisk type ramfs (rw,relatime,size=1gb) // map -hosts on /net (autofs, nosuid, automounted, nobrowse) UnixMountInfo.Builder builder = new UnixMountInfo.Builder(); // First get and remove the mount type if it's provided. Matcher matcher = Pattern.compile(".* (type \\w+ ).*").matcher(line); String lineWithoutType; if (matcher.matches()) { String match = matcher.group(1); builder.setFsType(match.replace("type", "").trim()); lineWithoutType = line.replace(match, ""); } else { lineWithoutType = line; } // Now parse the rest matcher = Pattern.compile("(.*) on (.*) \\((.*)\\)").matcher(lineWithoutType); if (!matcher.matches()) { LOG.debug("Unable to parse output of 'mount': {}", line); return builder.build(); } builder.setDeviceSpec(matcher.group(1)); builder.setMountPoint(matcher.group(2)); builder.setOptions(parseUnixMountOptions(matcher.group(3))); return builder.build(); }
/** * Gets system mount information. This method should only be attempted on Unix systems. * * @return system mount information */ public static List<UnixMountInfo> getUnixMountInfo() throws IOException { Preconditions.checkState(OSUtils.isLinux() || OSUtils.isMacOS()); String output = execCommand(MOUNT_COMMAND); List<UnixMountInfo> mountInfo = new ArrayList<>(); for (String line : output.split("\n")) { mountInfo.add(parseMountInfo(line)); } return mountInfo; }
@Test public void parseTmpfsMountInfo() throws Exception { // Docker VM mount info. UnixMountInfo info = ShellUtils .parseMountInfo("shm on /dev/shm type tmpfs (rw,nosuid,nodev,noexec,relatime,size=65536k)"); assertEquals(Optional.of("shm"), info.getDeviceSpec()); assertEquals(Optional.of("/dev/shm"), info.getMountPoint()); assertEquals(Optional.of("tmpfs"), info.getFsType()); assertEquals(Optional.of(Long.valueOf(65536 * Constants.KB)), info.getOptions().getSize()); }
/** * @param line the line to parse * @return the parsed {@link UnixMountInfo} */ public static UnixMountInfo parseMountInfo(String line) { // Example mount lines: // ramfs on /mnt/ramdisk type ramfs (rw,relatime,size=1gb) // map -hosts on /net (autofs, nosuid, automounted, nobrowse) UnixMountInfo.Builder builder = new UnixMountInfo.Builder(); // First get and remove the mount type if it's provided. Matcher matcher = Pattern.compile(".* (type \\w+ ).*").matcher(line); String lineWithoutType; if (matcher.matches()) { String match = matcher.group(1); builder.setFsType(match.replace("type", "").trim()); lineWithoutType = line.replace(match, ""); } else { lineWithoutType = line; } // Now parse the rest matcher = Pattern.compile("(.*) on (.*) \\((.*)\\)").matcher(lineWithoutType); if (!matcher.matches()) { LOG.debug("Unable to parse output of 'mount': {}", line); return builder.build(); } builder.setDeviceSpec(matcher.group(1)); builder.setMountPoint(matcher.group(2)); builder.setOptions(parseUnixMountOptions(matcher.group(3))); return builder.build(); }
/** * Gets the user name from the user id. * * @param uid user id * @return user name */ public static String getUserName(long uid) throws IOException { return ShellUtils.execCommand("id", "-nu", Long.toString(uid)).trim(); }
private void setupShellMocks(String username, List<String> groups) throws IOException { PowerMockito.mockStatic(ShellUtils.class); String shellResult = ""; for (String group: groups) { shellResult = shellResult + " " + group; } PowerMockito.when( ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(Mockito.eq(username)))) .thenReturn(shellResult); }
info = ShellUtils.getUnixMountInfo(); } catch (IOException e) { LOG.warn("Failed to get mount information for verifying memory capacity: {}",
@Test public void parseMountInfoWithoutType() throws Exception { // OS X mount info. UnixMountInfo info = ShellUtils.parseMountInfo("devfs on /dev (devfs, local, nobrowse)"); assertEquals(Optional.of("devfs"), info.getDeviceSpec()); assertEquals(Optional.of("/dev"), info.getMountPoint()); assertFalse(info.getFsType().isPresent()); assertFalse(info.getOptions().getSize().isPresent()); }
/** * Runs the "id" command with the given options on the passed username. * * @param option option to pass to id (either -u or -g) * @param username the username on which to run the command * @return the uid (-u) or gid (-g) of username */ private static long getIdInfo(String option, String username) { String output; try { output = ShellUtils.execCommand("id", option, username).trim(); } catch (IOException e) { LOG.error("Failed to get id from {} with option {}", username, option); return -1; } return Long.parseLong(output); }
/** * Tests the {@link ShellUtils#execCommand(String...)} method for a group of commands. * * @throws Throwable when the execution of the commands fails */ @Test public void execGetGroupCommand() throws Exception { String result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand("root")); // On Linux user "root" will be a part of the group "root". On OSX it will be a part of "admin". Assert.assertTrue(result.contains("root") || result.contains("admin")); }
@Test public void getMountInfo() throws Exception { assumeTrue(OSUtils.isMacOS() || OSUtils.isLinux()); List<UnixMountInfo> info = ShellUtils.getUnixMountInfo(); assertTrue(info.size() > 0); } }
@Test public void parseMountInfoSpaceInPath() throws Exception { UnixMountInfo info = ShellUtils.parseMountInfo("/dev/disk4s1 on /Volumes/Space Path " + "(hfs, local, nodev, nosuid, read-only, noowners, quarantine)"); assertEquals(Optional.of("/dev/disk4s1"), info.getDeviceSpec()); assertEquals(Optional.of("/Volumes/Space Path"), info.getMountPoint()); assertFalse(info.getFsType().isPresent()); assertFalse(info.getOptions().getSize().isPresent()); }
/** * Gets the group name from the group id. * * @param gid the group id * @return group name */ public static String getGroupName(long gid) throws IOException { if (OSUtils.isLinux()) { String script = "getent group " + gid + " | cut -d: -f1"; return ShellUtils.execCommand("bash", "-c", script).trim(); } else if (OSUtils.isMacOS()) { String script = "dscl . list /Groups PrimaryGroupID | awk '($2 == \"" + gid + "\") { print $1 }'"; return ShellUtils.execCommand("bash", "-c", script).trim(); } return ""; }
/** * Gets the current user's group list from Unix by running the command 'groups' NOTE. For * non-existing user it will return EMPTY list. This method may return duplicate groups. * * @param user user name * @return the groups list that the {@code user} belongs to. The primary group is returned first */ public static List<String> getUnixGroups(String user) throws IOException { String result; List<String> groups = new ArrayList<>(); try { result = ShellUtils.execCommand(ShellUtils.getGroupsForUserCommand(user)); } catch (ExitCodeException e) { // if we didn't get the group - just return empty list LOG.warn("got exception trying to get groups for user " + user + ": " + e.getMessage()); return groups; } StringTokenizer tokenizer = new StringTokenizer(result, ShellUtils.TOKEN_SEPARATOR_REGEX); while (tokenizer.hasMoreTokens()) { groups.add(tokenizer.nextToken()); } return groups; }
/** * Checks whether a path is the mounting point of a RAM disk volume. * * @param path a string represents the path to be checked * @param fsTypes an array of strings represents expected file system type * @return true if the path is the mounting point of volume with one of the given fsTypes, * false otherwise * @throws IOException if the function fails to get the mount information of the system */ public static boolean isMountingPoint(String path, String[] fsTypes) throws IOException { List<UnixMountInfo> infoList = ShellUtils.getUnixMountInfo(); for (UnixMountInfo info : infoList) { Optional<String> mountPoint = info.getMountPoint(); Optional<String> fsType = info.getFsType(); if (mountPoint.isPresent() && mountPoint.get().equals(path) && fsType.isPresent()) { for (String expectedType : fsTypes) { if (fsType.get().equalsIgnoreCase(expectedType)) { return true; } } } } return false; }