Java Code Examples for org.apache.brooklyn.util.os.Os#isAbsolutish()

The following examples show how to use org.apache.brooklyn.util.os.Os#isAbsolutish() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SshCommandSensor.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Beta
public static String makeCommandExecutingInDirectory(String command, String executionDir, Entity entity) {
    String finalCommand = command;
    String execDir = executionDir;
    if (Strings.isBlank(execDir)) {
        // default to run dir
        execDir = (entity != null) ? entity.getAttribute(BrooklynConfigKeys.RUN_DIR) : null;
        // if no run dir, default to home
        if (Strings.isBlank(execDir)) {
            execDir = "~";
        }
    } else if (!Os.isAbsolutish(execDir)) {
        // relative paths taken wrt run dir
        String runDir = (entity != null) ? entity.getAttribute(BrooklynConfigKeys.RUN_DIR) : null;
        if (!Strings.isBlank(runDir)) {
            execDir = Os.mergePaths(runDir, execDir);
        }
    }
    if (!"~".equals(execDir)) {
        finalCommand = "mkdir -p '"+execDir+"' && cd '"+execDir+"' && "+finalCommand;
    }
    return finalCommand;
}
 
Example 2
Source File: MachineLifecycleEffectorTasks.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves the on-box dir.
 * <p>
 * Initialize and pre-create the right onbox working dir, if an ssh machine location.
 * Logs a warning if not.
 */
@SuppressWarnings("deprecation")
public static String resolveOnBoxDir(EntityInternal entity, MachineLocation machine) {
    String base = entity.getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
    if (base==null) base = machine.getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
    if (base!=null && Boolean.TRUE.equals(entity.getConfig(ON_BOX_BASE_DIR_RESOLVED))) return base;
    if (base==null) base = entity.getManagementContext().getConfig().getConfig(BrooklynConfigKeys.ONBOX_BASE_DIR);
    if (base==null) base = entity.getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
    if (base==null) base = machine.getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
    if (base==null) base = entity.getManagementContext().getConfig().getConfig(BrooklynConfigKeys.BROOKLYN_DATA_DIR);
    if (base==null) base = "~/brooklyn-managed-processes";
    
    if (base.equals("~")) base=".";
    if (base.startsWith("~/")) base = "."+base.substring(1);

    String resolvedBase = null;
    if (entity.getConfig(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION) || machine.getConfig(BrooklynConfigKeys.SKIP_ON_BOX_BASE_DIR_RESOLUTION)) {
        if (log.isDebugEnabled()) log.debug("Skipping on-box base dir resolution for "+entity+" at "+machine);
        if (!Os.isAbsolutish(base)) base = "~/"+base;
        resolvedBase = Os.tidyPath(base);
    } else if (machine instanceof CanResolveOnBoxDir) {
        resolvedBase = ((CanResolveOnBoxDir)machine).resolveOnBoxDirFor(entity, base);
    }
    if (resolvedBase==null) {
        if (!Os.isAbsolutish(base)) base = "~/"+base;
        resolvedBase = Os.tidyPath(base);
        log.warn("Could not resolve on-box directory for "+entity+" at "+machine+"; using "+resolvedBase+", though this may not be accurate at the target (and may fail shortly)");
    }
    entity.config().set(BrooklynConfigKeys.ONBOX_BASE_DIR, resolvedBase);
    entity.config().set(ON_BOX_BASE_DIR_RESOLVED, true);
    return resolvedBase;
}
 
Example 3
Source File: AbstractSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * @param sshFlags Extra flags to be used when making an SSH connection to the entity's machine.
 *                 If the map contains the key {@link #IGNORE_ENTITY_SSH_FLAGS} then only the
 *                 given flags are used. Otherwise, the given flags are combined with (and take
 *                 precendence over) the flags returned by {@link #getSshFlags()}.
 * @param source URI of file to copy, e.g. file://.., http://.., classpath://..
 * @param target Destination on server, relative to {@link #getRunDir()} if not absolute path
 * @param createParentDir Whether to create the parent target directory, if it doesn't already exist
 * @return The exit code of the SSH command run
 */
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public int copyResource(Map<Object,Object> sshFlags, String source, String target, boolean createParentDir) {
    // TODO use SshTasks.put instead, better logging
    Map flags = Maps.newLinkedHashMap();
    if (!sshFlags.containsKey(IGNORE_ENTITY_SSH_FLAGS)) {
        flags.putAll(getSshFlags());
    }
    flags.putAll(sshFlags);

    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);

    if (createParentDir) {
        // don't use File.separator because it's remote machine's format, rather than local machine's
        int lastSlashIndex = destination.lastIndexOf("/");
        String parent = (lastSlashIndex > 0) ? destination.substring(0, lastSlashIndex) : null;
        if (parent != null) {
            getMachine().execCommands("createParentDir", ImmutableList.of("mkdir -p "+parent));
        }
    }

    int result = getMachine().installTo(resource, flags, source, destination);
    if (result == 0) {
        if (log.isDebugEnabled()) {
            log.debug("Copied file for {}: {} to {} - result {}", new Object[] { entity, source, destination, result });
        }
    }
    return result;
}
 
Example 4
Source File: AbstractSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Input stream will be closed automatically.
 * <p>
 * If using {@link SshjTool} usage, consider using {@link KnownSizeInputStream} to avoid having
 * to write out stream once to find its size!
 *
 * @see #copyResource(Map, String, String) for parameter descriptions.
 */
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public int copyResource(Map<Object,Object> sshFlags, InputStream source, String target, boolean createParentDir) {
    Map flags = Maps.newLinkedHashMap();
    if (!sshFlags.containsKey(IGNORE_ENTITY_SSH_FLAGS)) {
        flags.putAll(getSshFlags());
    }
    flags.putAll(sshFlags);

    String destination = Os.isAbsolutish(target) ? target : Os.mergePathsUnix(getRunDir(), target);

    if (createParentDir) {
        // don't use File.separator because it's remote machine's format, rather than local machine's
        int lastSlashIndex = destination.lastIndexOf("/");
        String parent = (lastSlashIndex > 0) ? destination.substring(0, lastSlashIndex) : null;
        if (parent != null) {
            getMachine().execCommands("createParentDir", ImmutableList.of("mkdir -p "+parent));
        }
    }

    // TODO SshMachineLocation.copyTo currently doesn't log warn on non-zero or set blocking details
    // (because delegated to by installTo, for multiple calls). So do it here for now.
    int result;
    String prevBlockingDetails = Tasks.setBlockingDetails("copying resource to server at "+destination);
    try {
        result = getMachine().copyTo(flags, source, destination);
    } finally {
        Tasks.setBlockingDetails(prevBlockingDetails);
    }

    if (result == 0) {
        log.debug("copying stream complete; {} on {}", new Object[] { destination, getMachine() });
    } else {
        log.warn("copying stream failed; {} on {}: {}", new Object[] { destination, getMachine(), result });
    }
    return result;
}
 
Example 5
Source File: AbstractSoftwareProcessDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void applyFnToResourcesAppendToList(
        Map<String, String> resources, final Function<SourceAndDestination, Task<?>> function,
        String destinationParentDir, final List<TaskAdaptable<?>> tasks) {

    for (Map.Entry<String, String> entry : resources.entrySet()) {
        final String source = checkNotNull(entry.getKey(), "Missing source for resource");
        String target = checkNotNull(entry.getValue(), "Missing destination for resource");
        final String destination = Os.isAbsolutish(target) ? target : mergePaths(destinationParentDir, target);

        // if source is a directory then copy all files underneath.
        // e.g. /tmp/a/{b,c/d}, source = /tmp/a, destination = dir/a/b and dir/a/c/d.
        final File srcFile = new File(source);
        if (srcFile.isDirectory() && srcFile.exists()) {
            try {
                final Path start = srcFile.toPath();
                final int startElements = start.getNameCount();
                // Actually walking to a depth of Integer.MAX_VALUE would be interesting.
                Files.walkFileTree(start, EnumSet.of(FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (attrs.isRegularFile()) {
                            Path relativePath = file.subpath(startElements, file.getNameCount());
                            tasks.add(function.apply(new SourceAndDestination(file.toString(), mergePaths(destination, relativePath.toString()))));
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException e) {
                throw Exceptions.propagate(e);
            }
        } else {
            tasks.add(function.apply(new SourceAndDestination(source, destination)));
        }
    }
}
 
Example 6
Source File: BrooklynServerPaths.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
protected static String resolveAgainstBaseDir(StringConfigMap brooklynProperties, String path) {
    if (!Os.isAbsolutish(path)) path = Os.mergePaths(getMgmtBaseDir(brooklynProperties), path);
    return Os.tidyPath(path);
}