/** writes given contents to a temporary file which will be deleted on exit */ public static File writeToTempFile(InputStream is, String prefix, String suffix) { return writeToTempFile(is, new File(Os.tmp()), prefix, suffix); }
public static File writePropertiesToTempFile(Properties props, String prefix, String suffix) { return writePropertiesToTempFile(props, new File(Os.tmp()), prefix, suffix); }
/** creates a private temp file which will be deleted on exit; * either prefix or ext may be null; * if ext is non-empty and not > 4 chars and not starting with a ., then a dot will be inserted; * if either name part is too long it will be shortened to prevent filesystem errors */ public static File newTempFile(String prefix, String ext) { String sanitizedPrefix = (Strings.isNonEmpty(prefix) ? Strings.makeValidFilename(prefix) + "-" : ""); if (sanitizedPrefix.length()>101) sanitizedPrefix = sanitizedPrefix.substring(0, 100)+"--"; String extWithPrecedingSeparator = (Strings.isNonEmpty(ext) ? ext.startsWith(".") || ext.length()>4 ? ext : "."+ext : ""); if (extWithPrecedingSeparator.length()>13) sanitizedPrefix = sanitizedPrefix.substring(0, 12)+"--"; try { File tempFile = File.createTempFile(sanitizedPrefix, extWithPrecedingSeparator, new File(tmp())); tempFile.deleteOnExit(); return tempFile; } catch (IOException e) { throw Exceptions.propagate(e); } }
/** creates a temp dir which will be deleted on exit */ public static File newTempDir(String prefix) { String sanitizedPrefix = (prefix==null ? "" : Strings.makeValidFilename(prefix) + "-"); String tmpParent = tmp(); //With lots of stale temp dirs it is possible to have //name collisions so we need to retry until a unique //name is found for (int i = 0; i < TEMP_DIR_ATTEMPTS; i++) { String baseName = sanitizedPrefix + Identifiers.makeRandomId(4); File tempDir = new File(tmpParent, baseName); if (!tempDir.exists()) { if (tempDir.mkdir()) { Os.deleteOnExitRecursively(tempDir); return tempDir; } else { log.warn("Attempt to create temp dir failed " + tempDir + ". Either an IO error (disk full, no rights) or someone else created the folder after the !exists() check."); } } else { log.debug("Attempt to create temp dir failed, already exists " + tempDir + ". With ID of length 4 it is not unusual (15% chance) to have duplicate names at the 2000 samples mark."); } } throw new IllegalStateException("cannot create temporary folders in parent " + tmpParent + " after " + TEMP_DIR_ATTEMPTS + " attempts."); }
@Test(groups = "Integration") public void testInstallClasspathCopyTo() throws Exception { File dest = new File(Os.tmp(), "sshMachineLocationTest_dir/"); dest.mkdir(); try { int result = host.installTo("classpath://brooklyn/config/sample.properties", Urls.mergePaths(dest.getAbsolutePath(), "sample.properties")); assertEquals(result, 0); String contents = ArchiveUtils.readFullyString(new File(dest, "sample.properties")); assertTrue(contents.contains("Property 1"), "contents missing expected phrase; contains:\n"+contents); } finally { dest.delete(); } }
@Test(groups = "Integration") public void testInstallUrlTo() throws Exception { File dest = new File(Os.tmp(), "sshMachineLocationTest_dir/"); dest.mkdir(); try { int result = host.installTo("https://raw.github.com/brooklyncentral/brooklyn/master/README.md", Urls.mergePaths(dest.getAbsolutePath(), "README.md")); assertEquals(result, 0); String contents = ArchiveUtils.readFullyString(new File(dest, "README.md")); assertTrue(contents.contains("http://brooklyncentral.github.com"), "contents missing expected phrase; contains:\n"+contents); } finally { dest.delete(); } }
@Test(groups = {"Integration"}) public void testOutputAsExpected() throws Exception { final String CONTENTS = "hello world\n" + "bye bye\n"; execCommands("cat > "+Os.mergePaths(Os.tmp(), "test1")+" << X\n" + CONTENTS + "X\n"); String read = execCommands("echo START_FOO", "cat "+Os.mergePaths(Os.tmp(), "test1"), "echo END_FOO"); log.debug("read back data written, as:\n"+read); String contents = Strings.getFragmentBetween(read, "START_FOO", "END_FOO"); Assert.assertEquals(CONTENTS.trim(), contents.trim()); }
@Test(groups = "Integration") public void testCopyStreamTo() throws Exception { String contents = "abc"; File dest = new File(Os.tmp(), "sshMachineLocationTest_dest.tmp"); try { host.copyTo(Streams.newInputStreamWithContents(contents), dest.getAbsolutePath()); assertEquals("abc", Files.readFirstLine(dest, Charsets.UTF_8)); } finally { dest.delete(); } }
public static File getOsgiCacheDir(ManagementContext mgmt) { StringConfigMap brooklynProperties = mgmt.getConfig(); String cacheDir = brooklynProperties.getConfig(BrooklynServerConfig.OSGI_CACHE_DIR); // note dir should be different for each instance if starting multiple instances // hence default including management node ID cacheDir = TemplateProcessor.processTemplateContents(cacheDir, mgmt, MutableMap.of(BrooklynServerConfig.MGMT_BASE_DIR.getName(), getMgmtBaseDir(mgmt), BrooklynServerConfig.MANAGEMENT_NODE_ID_PROPERTY, mgmt.getManagementNodeId(), Os.TmpDirFinder.BROOKLYN_OS_TMPDIR_PROPERTY, Os.tmp())); cacheDir = resolveAgainstBaseDir(mgmt.getConfig(), cacheDir); return new File(cacheDir); }
@Test(groups="Integration") // integration only because non-reusable OSGi takes ~200ms public void testOsgiPathCustom() { BrooklynProperties bp = BrooklynProperties.Factory.newEmpty(); String randomSeg = "osgi-test-"+Identifiers.makeRandomId(4); bp.put(BrooklynServerConfig.OSGI_CACHE_DIR, "${brooklyn.os.tmpdir}"+"/"+randomSeg+"/"+"${brooklyn.mgmt.node.id}"); mgmt = LocalManagementContextForTests.builder(true).enableOsgiNonReusable().useProperties(bp).build(); String path = BrooklynServerPaths.getOsgiCacheDir(mgmt).getAbsolutePath(); Os.deleteOnExitRecursivelyAndEmptyParentsUpTo(new File(path), new File(Os.tmp()+"/"+randomSeg)); Assert.assertTrue(path.startsWith(Os.tmp()), path); Assert.assertTrue(path.contains(mgmt.getManagementNodeId()), path); assertExistsThenIsCleaned(path); }
@Test(groups="Integration") // integration only because non-reusable OSGi takes ~200ms public void testOsgiPathCustomWithoutNodeIdNotCleaned() { BrooklynProperties bp = BrooklynProperties.Factory.newEmpty(); String randomSeg = "osgi-test-"+Identifiers.makeRandomId(4); bp.put(BrooklynServerConfig.OSGI_CACHE_DIR, "${brooklyn.os.tmpdir}"+"/"+randomSeg+"/"+"sample"); mgmt = LocalManagementContextForTests.builder(true).enableOsgiNonReusable().useProperties(bp).build(); String path = BrooklynServerPaths.getOsgiCacheDir(mgmt).getAbsolutePath(); Os.deleteOnExitRecursivelyAndEmptyParentsUpTo(new File(path), new File(Os.tmp()+"/"+randomSeg)); Assert.assertTrue(path.startsWith(Os.tmp()), path); Assert.assertFalse(path.contains(mgmt.getManagementNodeId()), path); assertExistsThenCorrectCleanedBehaviour(path, false); }
@Test public void testDeleteRecursivelyNonExistantDir() throws Exception { DeletionResult result = Os.deleteRecursively(Os.mergePaths(Os.tmp(), Identifiers.makeRandomId(8))); assertTrue(result.wasSuccessful()); }
@Test(groups = {"Integration"}) public void testUsesCustomLocalTempDir() throws Exception { class SshjToolForTest extends SshjTool { public SshjToolForTest(Map<String, ?> map) { super(map); } public File getLocalTempDir() { return localTempDir; } }; final SshjToolForTest localtool = new SshjToolForTest(ImmutableMap.<String, Object>of("host", "localhost")); assertNotNull(localtool.getLocalTempDir()); assertEquals(localtool.getLocalTempDir(), new File(Os.tidyPath(SshjTool.PROP_LOCAL_TEMP_DIR.getDefaultValue()))); String customTempDir = Os.tmp(); final SshjToolForTest localtool2 = new SshjToolForTest(ImmutableMap.of( "host", "localhost", SshjTool.PROP_LOCAL_TEMP_DIR.getName(), customTempDir)); assertEquals(localtool2.getLocalTempDir(), new File(customTempDir)); String customRelativeTempDir = "~/tmp"; final SshjToolForTest localtool3 = new SshjToolForTest(ImmutableMap.of( "host", "localhost", SshjTool.PROP_LOCAL_TEMP_DIR.getName(), customRelativeTempDir)); assertEquals(localtool3.getLocalTempDir(), new File(Os.tidyPath(customRelativeTempDir))); }
public void testResolvesLocalTempDir() throws Exception { String localTempDir = Os.mergePaths(Os.tmp(), "testResolvesUsernameAtHost"); brooklynProperties.put("brooklyn.location.byon.localTempDir", localTempDir); FixedListMachineProvisioningLocation<MachineLocation> byon = resolve("byon(hosts=\"1.1.1.1\",osFamily=\"windows\")"); MachineLocation machine = byon.obtain(); assertEquals(machine.getConfig(SshMachineLocation.LOCAL_TEMP_DIR), localTempDir); }
@Test(groups = "Integration") public void testStartsInDifferentRunAndInstallSpecifiedDirectories() throws Exception { String dir1 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); String dir2 = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); app.config().set(BrooklynConfigKeys.INSTALL_DIR, dir1); app.config().set(BrooklynConfigKeys.RUN_DIR, dir2); doTestSpecifiedDirectory(dir1, dir2); Os.deleteRecursively(dir1); Os.deleteRecursively(dir2); }
@Test(groups = "Integration") public void testStartsInMgmtSpecifiedDirectory() throws Exception { String dir = Os.mergePathsUnix(Os.tmp(), "/brooklyn-test-"+Strings.makeRandomId(4)); tearDown(); mgmt = new LocalManagementContextForTests(); mgmt.getBrooklynProperties().put(BrooklynConfigKeys.ONBOX_BASE_DIR, dir); setUp(); doTestSpecifiedDirectory(dir, dir); Os.deleteRecursively(dir); }