org.apache.brooklyn.util.os.Os Java Examples

The following examples show how to use org.apache.brooklyn.util.os.Os. 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: JcloudsLoginLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Live"})
protected void testAwsEc2WhenBlankUserSoUsesRootLoginUser() throws Exception {
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "");
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa");
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub");
    jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().getLocationManaged(AWS_EC2_LOCATION_SPEC);
    
    machine = createEc2Machine(ImmutableMap.<String,Object>of("imageId", AWS_EC2_UBUNTU_10_IMAGE_ID));
    assertSshable(machine);
    
    assertSshable(ImmutableMap.builder()
            .put("address", machine.getAddress())
            .put("user", "root")
            .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa"))
            .build());
}
 
Example #2
Source File: ElasticSearchNodeSshDriver.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void launch() {
    String pidFile = getRunDir() + "/" + AbstractSoftwareProcessSshDriver.PID_FILENAME;
    entity.sensors().set(ElasticSearchNode.PID_FILE, pidFile);
    StringBuilder commandBuilder = new StringBuilder()
        .append(String.format("%s/bin/elasticsearch -d -p %s", getExpandedInstallDir(), pidFile));
    if (entity.getConfig(ElasticSearchNode.TEMPLATE_CONFIGURATION_URL) != null) {
        commandBuilder.append(" -Des.config=" + Os.mergePaths(getRunDir(), getConfigFile()));
    }
    appendConfigIfPresent(commandBuilder, "es.path.data", ElasticSearchNode.DATA_DIR, Os.mergePaths(getRunDir(), "data"));
    appendConfigIfPresent(commandBuilder, "es.path.logs", ElasticSearchNode.LOG_DIR, Os.mergePaths(getRunDir(), "logs"));
    appendConfigIfPresent(commandBuilder, "es.node.name", ElasticSearchNode.NODE_NAME.getConfigKey());
    appendConfigIfPresent(commandBuilder, "es.cluster.name", ElasticSearchNode.CLUSTER_NAME.getConfigKey());
    appendConfigIfPresent(commandBuilder, "es.discovery.zen.ping.multicast.enabled", ElasticSearchNode.MULTICAST_ENABLED);
    appendConfigIfPresent(commandBuilder, "es.discovery.zen.ping.unicast.enabled", ElasticSearchNode.UNICAST_ENABLED);
    commandBuilder.append(" > out.log 2> err.log < /dev/null");
    newScript(MutableMap.of("usePidFile", false), LAUNCHING)
        .updateTaskAndFailOnNonZeroResultCode()
        .body.append(commandBuilder.toString())
        .execute();
}
 
Example #3
Source File: BundleAndTypeResourcesTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static File createJar(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "jar");

    JarOutputStream zip = new JarOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        JarEntry ze = new JarEntry(entry.getKey());
        zip.putNextEntry(ze);
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}
 
Example #4
Source File: RebindFailuresTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureRebindingBecauseDirectoryCorrupt() throws Exception {
    RebindFailureMode danglingRefFailureMode = RebindManager.RebindFailureMode.CONTINUE;
    RebindFailureMode rebindFailureMode = RebindManager.RebindFailureMode.FAIL_AT_END;
    
    origManagementContext.getRebindManager().stopPersistence();
    if (mementoDir != null) RebindTestUtils.deleteMementoDir(mementoDir);
    File entitiesDir = Os.mkdirs(new File(mementoDir, "entities"));
    Files.write("invalid text", new File(entitiesDir, "mycorruptfile"), Charsets.UTF_8);
    
    LocalManagementContext newManagementContext = LocalManagementContextForTests.newInstance();
    RecordingRebindExceptionHandler exceptionHandler = new RecordingRebindExceptionHandler(danglingRefFailureMode, rebindFailureMode);
    try {
        newApp = rebind(RebindOptions.create().newManagementContext(newManagementContext).exceptionHandler(exceptionHandler));
        fail();
    } catch (Exception e) {
        assertFailureRebindingError(e);
    }
    
    // exception handler should have been told about failure
    assertFalse(exceptionHandler.loadMementoFailures.isEmpty(), "exceptions="+exceptionHandler.loadMementoFailures);
}
 
Example #5
Source File: ProcessTool.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public int execCommands(Map<String,?> props, List<String> commands, Map<String,?> env) {
    if (Boolean.FALSE.equals(props.get("blocks"))) {
        throw new IllegalArgumentException("Cannot exec non-blocking: command="+commands);
    }
    OutputStream out = getOptionalVal(props, PROP_OUT_STREAM);
    OutputStream err = getOptionalVal(props, PROP_ERR_STREAM);
    String separator = getOptionalVal(props, PROP_SEPARATOR);
    String directory = getOptionalVal(props, PROP_DIRECTORY);
    File directoryDir = (directory != null) ? new File(Os.tidyPath(directory)) : null;

    List<String> allcmds = toCommandSequence(commands, null);

    String singlecmd = Joiner.on(separator).join(allcmds);
    if (Boolean.TRUE.equals(getOptionalVal(props, PROP_RUN_AS_ROOT))) {
        LOG.warn("Cannot run as root when executing as command; run as a script instead (will run as normal user): "+singlecmd);
    }
    if (LOG.isTraceEnabled()) LOG.trace("Running shell command (process): {}", singlecmd);
    
    return asInt(execProcesses(allcmds, env, directoryDir, out, err, separator, getOptionalVal(props, PROP_LOGIN_SHELL), this), -1);
}
 
Example #6
Source File: TomcatSshDriver.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
@Override
public void customize() {
    newScript(CUSTOMIZING)
            .body.append("mkdir -p conf logs webapps temp")
            .failOnNonZeroResultCode()
            .execute();

    copyTemplate(entity.getConfig(TomcatServer.SERVER_XML_RESOURCE), Os.mergePaths(getRunDir(), "conf", "server.xml"));
    copyTemplate(entity.getConfig(TomcatServer.WEB_XML_RESOURCE), Os.mergePaths(getRunDir(), "conf", "web.xml"));

    // Deduplicate same code in JBoss
    if (isProtocolEnabled("HTTPS")) {
        String keystoreUrl = Preconditions.checkNotNull(getSslKeystoreUrl(), "keystore URL must be specified if using HTTPS for " + entity);
        String destinationSslKeystoreFile = getHttpsSslKeystoreFile();
        InputStream keystoreStream = resource.getResourceFromUrl(keystoreUrl);
        getMachine().copyTo(keystoreStream, destinationSslKeystoreFile);
    }

    getEntity().deployInitialWars();
}
 
Example #7
Source File: JcloudsLoginLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Live"})
protected void testAwsEc2SpecifyingSpecialUser() throws Exception {
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "ec2-user");
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa");
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub");
    jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().getLocationManaged(AWS_EC2_LOCATION_SPEC);
    
    machine = createEc2Machine(ImmutableMap.<String,Object>of("imageId", AWS_EC2_UBUNTU_10_IMAGE_ID));
    assertSshable(machine);
    
    assertSshable(ImmutableMap.builder()
            .put("address", machine.getAddress())
            .put("user", "ec2-user")
            .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa"))
            .build());
}
 
Example #8
Source File: SoftwareProcessEntityTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testInstallDirAndRunDirUsingTilde() throws Exception {
    String dataDirName = ".brooklyn-foo"+Strings.makeRandomId(4);
    String dataDir = "~/"+dataDirName;
    String resolvedDataDir = Os.mergePaths(Os.home(), dataDirName);
    
    MyService entity = app.createAndManageChild(EntitySpec.create(MyService.class)
        .configure(BrooklynConfigKeys.ONBOX_BASE_DIR, dataDir));

    entity.start(ImmutableList.of(loc));

    Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.INSTALL_DIR)),
                        Os.nativePath(Os.mergePaths(resolvedDataDir, "installs/MyService")));
    Assert.assertEquals(Os.nativePath(entity.getAttribute(SoftwareProcess.RUN_DIR)),
                        Os.nativePath(Os.mergePaths(resolvedDataDir, "apps/"+entity.getApplicationId()+"/entities/MyService_"+entity.getId())));
}
 
Example #9
Source File: BrooklynPropertiesFactoryHelperTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups="UNIX")
public void testStartsWithSymlinkedBrooklynPropertiesPermissionsX00() throws Exception {
    File dir = Files.createTempDir();
    Path globalPropsFile = java.nio.file.Files.createFile(Paths.get(dir.toString(), "globalProps.properties"));
    Path globalSymlink = java.nio.file.Files.createSymbolicLink(Paths.get(dir.toString(), "globalLink"), globalPropsFile);
    Path localPropsFile = java.nio.file.Files.createFile(Paths.get(dir.toString(), "localPropsFile.properties"));
    Path localSymlink = java.nio.file.Files.createSymbolicLink(Paths.get(dir.toString(), "localLink"), localPropsFile);

    Files.write(getMinimalLauncherPropertiesString() + "key_in_global=1", globalPropsFile.toFile(), Charset.defaultCharset());
    Files.write("key_in_local=2", localPropsFile.toFile(), Charset.defaultCharset());
    FileUtil.setFilePermissionsTo600(globalPropsFile.toFile());
    FileUtil.setFilePermissionsTo600(localPropsFile.toFile());
    try {
        BrooklynProperties props = new BrooklynPropertiesFactoryHelper(
                globalSymlink.toAbsolutePath().toString(),
                localSymlink.toAbsolutePath().toString())
            .createPropertiesBuilder()
            .build();
        
        assertEquals(props.getFirst("key_in_global"), "1");
        assertEquals(props.getFirst("key_in_local"), "2");
    } finally {
        Os.deleteRecursively(dir);
    }
}
 
Example #10
Source File: FileBasedStoreObjectAccessorWriterTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups={"Integration", "Broken"}, invocationCount=5000)
public void testSimpleOperationsDelay() throws Exception {
    Callable<Void> r = new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            File tmp = Os.newTempFile(getClass(), "txt");
            try(Writer out = new FileWriter(tmp)) {
                out.write(TEST_FILE_CONTENT);
            }
            tmp.delete();
            return null;
        }
    };

    final Future<Void> f1 = executor.submit(r);
    final Future<Void> f2 = executor.submit(r);

    CountdownTimer time = CountdownTimer.newInstanceStarted(FILE_OPERATION_TIMEOUT);
    f1.get(time.getDurationRemaining().toMilliseconds(), TimeUnit.MILLISECONDS);
    f2.get(time.getDurationRemaining().toMilliseconds(), TimeUnit.MILLISECONDS);
}
 
Example #11
Source File: BundleMaker.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
/** Creates a temporary file with the given metadata */ 
public File createTempBundle(String nameHint, Manifest mf, Map<ZipEntry, InputStream> files) {
    File f2 = Os.newTempFile(nameHint, "zip");
    ZipOutputStream zout = null;
    ZipFile zf = null;
    try {
        zout = mf!=null ? new JarOutputStream(new FileOutputStream(f2), mf) : new ZipOutputStream(new FileOutputStream(f2));
        writeZipEntries(zout, files);
    } catch (IOException e) {
        throw Exceptions.propagateAnnotated("Unable to read/write for "+nameHint, e);
    } finally {
        Streams.closeQuietly(zf);
        Streams.closeQuietly(zout);
    }
    return f2;
}
 
Example #12
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 #13
Source File: CompoundTransformerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
protected File persist(BrooklynMementoRawData rawData) throws Exception {
    File newMementoDir = Os.newTempDir(getClass());
    
    FileBasedObjectStore objectStore = new FileBasedObjectStore(newMementoDir);
    objectStore.injectManagementContext(origManagementContext);
    objectStore.prepareForSharedUse(PersistMode.CLEAN, HighAvailabilityMode.DISABLED);

    BrooklynMementoPersisterToObjectStore persister = new BrooklynMementoPersisterToObjectStore(
            objectStore, origManagementContext);
    persister.enableWriteAccess();

    PersistenceExceptionHandler exceptionHandler = PersistenceExceptionHandlerImpl.builder().build();
    persister.checkpoint(rawData, exceptionHandler);
    
    LOG.info("Test "+getClass()+" persisted raw data to "+newMementoDir);
    return newMementoDir;
}
 
Example #14
Source File: BundleAndTypeResourcesTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private static File createZip(Map<String, String> files) throws Exception {
    File f = Os.newTempFile("osgi", "zip");

    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(f));

    for (Map.Entry<String, String> entry : files.entrySet()) {
        ZipEntry ze = new ZipEntry(entry.getKey());
        zip.putNextEntry(ze);
        zip.write(entry.getValue().getBytes());
    }

    zip.closeEntry();
    zip.flush();
    zip.close();

    return f;
}
 
Example #15
Source File: JcloudsLoginLiveTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Live"})
@SuppressWarnings("deprecation")
protected void testAwsEc2SpecifyingPrivateAndPublicSshKeyInDeprecatedForm() throws Exception {
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.USER.getName(), "myname");
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.LEGACY_PRIVATE_KEY_FILE.getName(), "~/.ssh/id_rsa");
    brooklynProperties.put(BROOKLYN_PROPERTIES_PREFIX+JcloudsLocationConfig.LEGACY_PUBLIC_KEY_FILE.getName(), "~/.ssh/id_rsa.pub");
    jcloudsLocation = (JcloudsLocation) managementContext.getLocationRegistry().getLocationManaged(AWS_EC2_LOCATION_SPEC);
    
    machine = createEc2Machine();
    assertSshable(machine);
    
    assertSshable(ImmutableMap.builder()
            .put("address", machine.getAddress())
            .put("user", "myname")
            .put(SshMachineLocation.PRIVATE_KEY_FILE, Os.tidyPath("~/.ssh/id_rsa"))
            .build());
}
 
Example #16
Source File: InitSlaveTaskBody.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
private boolean isReplicationInfoValid(ReplicationSnapshot replicationSnapshot) {
    MySqlNode master = getMaster();
    String dataDir = Strings.nullToEmpty(master.getConfig(MySqlNode.DATA_DIR));
    if (!checkFileExistsOnEntity(master, Os.mergePathsUnix(dataDir, replicationSnapshot.getBinLogName()))) {
        return false;
    }
    if (replicationSnapshot.getEntityId() != null) {
        Optional<Entity> snapshotSlave = Iterables.tryFind(cluster.getChildren(), EntityPredicates.idEqualTo(replicationSnapshot.getEntityId()));
        if (!snapshotSlave.isPresent()) {
            log.info("MySql cluster " + cluster + " missing node " + replicationSnapshot.getEntityId() + " with last snapshot " + replicationSnapshot.getSnapshotPath() + ". Will generate new snapshot.");
            return false;
        }
        if (!checkFileExistsOnEntity(snapshotSlave.get(), replicationSnapshot.getSnapshotPath())) {
            log.info("MySql cluster " + cluster + ", node " + snapshotSlave.get() + " missing replication snapshot " + replicationSnapshot.getSnapshotPath() + ". Will generate new snapshot.");
            return false;
        }
    }
    return true;
}
 
Example #17
Source File: AbstractSoftwareProcessDriver.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
public String getExpandedInstallDir() {
    if (expandedInstallDir != null) return expandedInstallDir;

    String existingVal = getEntity().getAttribute(SoftwareProcess.EXPANDED_INSTALL_DIR);
    if (Strings.isNonBlank(existingVal)) { // e.g. on rebind
        expandedInstallDir = existingVal;
        return expandedInstallDir;
    }

    String untidiedVal = ConfigToAttributes.apply(getEntity(), SoftwareProcess.EXPANDED_INSTALL_DIR);
    if (Strings.isNonBlank(untidiedVal)) {
        setExpandedInstallDir(Os.tidyPath(untidiedVal));
        return expandedInstallDir;
    } else {
        throw new IllegalStateException("expandedInstallDir is null; most likely install was not called for "+getEntity());
    }
}
 
Example #18
Source File: SshFetchTaskWrapper.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Override
public String call() throws Exception {
    int result = -1;
    try {
        Preconditions.checkNotNull(getMachine(), "machine");
        backingFile = Os.newTempFile("brooklyn-ssh-fetch-", FilenameUtils.getName(remoteFile));
        backingFile.deleteOnExit();
        
        result = getMachine().copyFrom(config.getAllConfig(), remoteFile, backingFile.getPath());
    } catch (Exception e) {
        throw new IllegalStateException("SSH fetch "+getRemoteFile()+" from "+getMachine()+" returned threw exception, in "+Tasks.current()+": "+e, e);
    }
    if (result!=0) {
        throw new IllegalStateException("SSH fetch "+getRemoteFile()+" from "+getMachine()+" returned non-zero exit code  "+result+", in "+Tasks.current());
    }
    return FileUtils.readFileToString(backingFile);
}
 
Example #19
Source File: BrooklynNodeIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@AfterMethod(alwaysRun=true)
@Override
public void tearDown() throws Exception {
    try {
        super.tearDown();
    } finally {
        if (pseudoBrooklynPropertiesFile != null) pseudoBrooklynPropertiesFile.delete();
        if (pseudoBrooklynCatalogFile != null) pseudoBrooklynCatalogFile.delete();
        if (brooklynCatalogSourceFile != null) brooklynCatalogSourceFile.delete();
        if (persistenceDir != null) Os.deleteRecursively(persistenceDir);
    }
}
 
Example #20
Source File: SoftwareProcessDriverCopyResourcesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun = true)
@Override
public void setUp() throws Exception {
    super.setUp();

    sourceFileDir = Os.newTempDir(getClass().getSimpleName());
    sourceTemplateDir = Os.newTempDir(getClass().getSimpleName());

    installDir = Os.newTempDir(getClass().getSimpleName());
    runDir = Os.newTempDir(getClass().getSimpleName());

    location = app.newLocalhostProvisioningLocation();
}
 
Example #21
Source File: ArchiveUtilsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private File newZip(Map<String, String> files) throws Exception {
    File parentDir = Os.newTempDir(getClass().getSimpleName()+"-archive");
    for (Map.Entry<String, String> entry : files.entrySet()) {
        File subFile = new File(Os.mergePaths(parentDir.getAbsolutePath(), entry.getKey()));
        subFile.getParentFile().mkdirs();
        Files.write(entry.getValue(), subFile, Charsets.UTF_8);
    }
    return ArchiveBuilder.zip().addDirContentsAt(parentDir, ".").create();
}
 
Example #22
Source File: BrooklynServerPaths.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** @see BrooklynServerPaths#getMgmtBaseDir(ManagementContext) */
@SuppressWarnings("deprecation")
public static String getMgmtBaseDir(StringConfigMap brooklynProperties) {
    String base = (String) brooklynProperties.getConfigLocalRaw(BrooklynServerConfig.MGMT_BASE_DIR).orNull();
    if (base==null) {
        base = brooklynProperties.getConfig(BrooklynServerConfig.BROOKLYN_DATA_DIR);
        if (base!=null)
            log.warn("Using deprecated "+BrooklynServerConfig.BROOKLYN_DATA_DIR.getName()+": use "+BrooklynServerConfig.MGMT_BASE_DIR.getName()+" instead; value: "+base);
    }
    if (base==null) base = brooklynProperties.getConfig(BrooklynServerConfig.MGMT_BASE_DIR);
    return Os.tidyPath(base)+File.separator;
}
 
Example #23
Source File: FilePermissions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void apply(File file) throws IOException {
    Path filePath = file.toPath();

    // the appropriate condition is actually Files.getFileStore(filePath).supportsFileAttributeView(PosixFileAttributeView.class)
    // but that downs performance to ~9000 calls per second

    boolean done = false;
    try {
        // ~59000 calls per sec
        if (!Os.isMicrosoftWindows()) {
            Files.setPosixFilePermissions(filePath, posixPermissions);
        }
        done = true;
    } catch (UnsupportedOperationException ex) {}
    
    if (!done) {
        // ~42000 calls per sec
        // TODO: what happens to group permissions ?
        boolean setRead = file.setReadable(posixPermissions.contains(OTHERS_READ), false) & file.setReadable(posixPermissions.contains(OWNER_READ), true);
        boolean setWrite = file.setWritable(posixPermissions.contains(OTHERS_WRITE), false) & file.setWritable(posixPermissions.contains(OWNER_WRITE), true);
        boolean setExec = file.setExecutable(posixPermissions.contains(OTHERS_EXECUTE), false) & file.setExecutable(posixPermissions.contains(OWNER_EXECUTE), true);

        if (!(setRead && setWrite && setExec)) {
            throw new IOException("setting file permissions failed: read=" + setRead + " write=" + setWrite + " exec=" + setExec);
        }
    }
}
 
Example #24
Source File: BashCommandsIntegrationTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@BeforeMethod(alwaysRun=true)
public void setUp() throws Exception {
    super.setUp();
    
    exec = new BasicExecutionContext(mgmt.getExecutionManager());
    
    destFile = Os.newTempFile(getClass(), "commoncommands-test-dest.txt");
    
    sourceNonExistantFile = new File("/this/does/not/exist/ERQBETJJIG1234");
    sourceNonExistantFileUrl = sourceNonExistantFile.toURI().toString();
    
    sourceFile1 = Os.newTempFile(getClass(), "commoncommands-test.txt");
    sourceFileUrl1 = sourceFile1.toURI().toString();
    Files.write("mysource1".getBytes(), sourceFile1);
    
    sourceFile2 = Os.newTempFile(getClass(), "commoncommands-test2.txt");
    sourceFileUrl2 = sourceFile2.toURI().toString();
    Files.write("mysource2".getBytes(), sourceFile2);

    localRepoEntityVersionPath = JavaClassNames.simpleClassName(this)+"-test-dest-"+Identifiers.makeRandomId(8);
    localRepoBasePath = new File(format("%s/.brooklyn/repository", System.getProperty("user.home")));
    localRepoEntityBasePath = new File(localRepoBasePath, localRepoEntityVersionPath);
    localRepoEntityFile = new File(localRepoEntityBasePath, localRepoFilename);
    localRepoEntityBasePath.mkdirs();
    Files.write("mylocal1".getBytes(), localRepoEntityFile);

    tmpSudoersFile = Os.newTempFile(getClass(), "sudoers" + Identifiers.makeRandomId(8));

    String sudoers = ResourceUtils.create(this).getResourceAsString("classpath://brooklyn/util/ssh/test_sudoers");
    Files.write(sudoers.getBytes(), tmpSudoersFile);
    
    loc = mgmt.getLocationManager().createLocation(LocalhostMachineProvisioningLocation.spec()).obtain();
}
 
Example #25
Source File: AbstractSoftwareProcessSshDriver.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void prepare() {
    // Check if we should create a download resolver?
    String downloadUrl = getEntity().config().get(SoftwareProcess.DOWNLOAD_URL);
    if (Strings.isNonEmpty(downloadUrl)) {
        resolver = Entities.newDownloader(this);
        String formatString = getArchiveNameFormat();
        if (Strings.isNonEmpty(formatString)) {
            setExpandedInstallDir(Os.mergePaths(getInstallDir(), resolver.getUnpackedDirectoryName(String.format(formatString, getVersion()))));
        } else {
            setExpandedInstallDir(getInstallDir());
        }
    }
}
 
Example #26
Source File: RebindWithDeserializingClassRenamesTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private File givenLegacyEntityFile(final String entityId) throws IOException {
    // load template entity config file
    final String persistedEntity = ResourceUtils.create(RebindWithDeserializingClassRenamesTest.class)
            .getResourceAsString(RESOURCE_PATH + entityId);
    // create a private/writable copy of the legacy config file
    final File persistedEntityFile = new File(mementoDir, Os.mergePaths("entities", entityId));
    Files.write(persistedEntityFile.toPath(), persistedEntity.getBytes());
    return persistedEntityFile;
}
 
Example #27
Source File: OsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public void testIsAbsolutish() {
    assertFalse(Os.isAbsolutish(""));
    assertFalse(Os.isAbsolutish("foo/bar"));
    assertTrue(Os.isAbsolutish("/"));
    assertTrue(Os.isAbsolutish("~/"));
    assertTrue(Os.isAbsolutish("~"));
    assertTrue(Os.isAbsolutish("/foo/bar"));
}
 
Example #28
Source File: OsTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteRecursivelySubDirs() throws Exception {
    File dir = Os.newTempDir(OsTest.class);
    File subdir = new File(dir, "mysubdir");
    File subfile = new File(subdir, "mysubfile");
    subdir.mkdirs();
    Files.write("abc".getBytes(), subfile);
    
    DeletionResult result = Os.deleteRecursively(dir);
    assertTrue(result.wasSuccessful());
    assertFalse(dir.exists());
}
 
Example #29
Source File: BrooklynDevelopmentModes.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static boolean computeAutodectectedDevelopmentMode() {
    String cp = System.getProperty("java.class.path");
    String platformSegment = Os.nativePath(segment);
    if (cp==null) return false;
    if (cp.endsWith(platformSegment) || cp.contains(platformSegment+File.pathSeparator)) {
        log.debug("Brooklyn developmentMode autodetected (based on presence of '"+segment+"' in classpath)");
        return true;
    }
    return false;
}
 
Example #30
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;
}