@VisibleForTesting void createRolesIfNecessary(ImmutableList.Builder<Statement> statements) { // The roles directory must contain one file for each role definition if (roles.isPresent() && !roles.get().isEmpty()) { statements.add(exec("{md} " + rolePath)); for (Role role : roles.get()) { statements.add(createOrOverwriteFile(rolePath + "/" + role.getName() + ".json", ImmutableSet.of(role.toJsonString()))); } } }
public InstallChefUsingOmnibus(String chefVersion) { super(call("setupPublicCurl"), saveHttpResponseTo(URI.create(OMNIBUS_INSTALLER), "/tmp", "install-chef.sh"), exec("sh /tmp/install-chef.sh -v " + chefVersion)); } }
public String render(OsFamily family) { String linesToPrepend = Joiner.on('\n').withKeyValueSeparator(" ").join(params); Statement prependSshdConfig = exec(String.format( "exec 3<> %1$s && awk -v TEXT=\"%2$s\n\" 'BEGIN {print TEXT}{print}' %1$s >&3", sshdConfig, linesToPrepend)); Statement reloadSshdConfig = exec("hash service 2>&- && service ssh reload 2>&- || /etc/init.d/ssh* reload"); return newStatementList(prependSshdConfig, reloadSshdConfig).render(family); }
public static Statement addAuthorizedKeysToRoot(String publicKey) { return newStatementList( appendFile("/root/.ssh/authorized_keys", Splitter.on('\n').split(publicKey)), interpret("chmod 600 /root/.ssh/authorized_keys")); }
public void testCreateDefaultNodeConfiguration() { ImmutableList.Builder<Statement> statements = ImmutableList.builder(); ChefSolo solo = ChefSolo.builder().build(); solo.createNodeConfiguration(statements); ImmutableList<Statement> statementList = statements.build(); Statement expected = createOrOverwriteFile(ChefSolo.DEFAULT_SOLO_PATH + "/node.json", ImmutableSet.of("{\"run_list\":[]}")); assertEquals(statementList.size(), 1); assertEquals(statementList.get(0).render(OsFamily.UNIX), expected.render(OsFamily.UNIX)); }
public void testCreateNewKeyPairUnlessUserSpecifiedOtherwise_reusesKeyWhenToldToWithRunScriptAndCredentialsAlreadyInMap() { // setup constants String region = Region.AP_SOUTHEAST_1; String group = "group"; String userSuppliedKeyPair = "myKeyPair"; // create mocks CreateKeyPairAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy(); EC2TemplateOptions options = createMock(EC2TemplateOptions.class); KeyPair keyPair = createMock(KeyPair.class); // setup expectations expect(options.getKeyPair()).andReturn(userSuppliedKeyPair); expect(options.getLoginPrivateKey()).andReturn(null); expect(options.getRunScript()).andReturn(Statements.exec("echo foo")); expect(strategy.credentialsMap.containsKey(new RegionAndName(region, userSuppliedKeyPair))).andReturn(true); // replay mocks replay(options); replay(keyPair); replayStrategy(strategy); // run assertEquals(strategy.createNewKeyPairUnlessUserSpecifiedOtherwise(region, group, options), userSuppliedKeyPair); // verify mocks verify(options); verify(keyPair); verifyStrategy(strategy); }
public void testSwitchArgUNIX() { assertEquals(new SwitchArg(1, ImmutableMap.of("0", newStatementList(appendFile( "{tmp}{fs}{uid}{fs}scripttest{fs}temp.txt", ImmutableList.of("hello world")), interpret("echo hello zero{lf}")), "1", interpret("echo hello one{lf}"))).render(OsFamily.UNIX), "case $1 in\n"+ "0)\n"+ " cat >> /tmp/$USER/scripttest/temp.txt <<-'END_OF_JCLOUDS_FILE'\n"+ "\thello world\n"+ "END_OF_JCLOUDS_FILE\n"+ " echo hello zero\n"+ " ;;\n"+ "1)\n"+ " echo hello one\n"+ " ;;\n"+ "esac\n"); }
@Test public void testSwitchOn() { ScriptBuilder builder = new ScriptBuilder(); builder.addStatement(switchArg(1, ImmutableMap.of("start", interpret("echo started{lf}"), "stop", interpret("echo stopped{lf}")))); assertEquals(builder.statements, ImmutableList.of(new SwitchArg(1, ImmutableMap.of("start", interpret("echo started{lf}"), "stop", interpret("echo stopped{lf}"))))); }
@Test(expectedExceptions = IllegalStateException.class) public void testWithoutInitThrowsIllegalStateException() { Statement command = exec("doFoo"); NodeMetadata node = new NodeMetadataBuilder().ids("id").status(Status.RUNNING).credentials( LoginCredentials.builder().user("tester").password("notalot").build()).build(); SshClient sshClient = createMock(SshClient.class); replay(sshClient); RunScriptOnNodeAsInitScriptUsingSsh testMe = new RunScriptOnNodeAsInitScriptUsingSsh(Functions .forMap(ImmutableMap.of(node, sshClient)), eventBus, InitScriptConfigurationForTasks.create() .appendIncrementingNumberToAnonymousTaskNames(), node, command, new RunScriptOptions()); testMe.call(); }
public void testSwitchArgWindows() { assertEquals( new SwitchArg(1, ImmutableMap.of("0", interpret("echo hello zero{lf}"), "1", interpret("echo hello one{lf}"))).render(OsFamily.WINDOWS), "if not \"%1\" == \"0\" if not \"%1\" == \"1\" (\r\n set EXCEPTION=bad argument: %1 not in 0 1\r\n goto abort\r\n)\r\ngoto CASE_%1\r\n:CASE_0\r\n echo hello zero\r\n GOTO END_SWITCH\r\n:CASE_1\r\n echo hello one\r\n GOTO END_SWITCH\r\n:END_SWITCH\r\n"); } }
private void addUnixRunScriptHeader(String runScript, StringBuilder builder) { builder.append("# create runscript header\n"); Builder<String> beginningOfFile = ImmutableList.builder(); beginningOfFile.addAll(Splitter.on(ShellToken.LF.to(OsFamily.UNIX)).split( ShellToken.BEGIN_SCRIPT.to(OsFamily.UNIX))); beginningOfFile.add(format("PROMPT_COMMAND='echo -ne \\\"\\033]0;%s\\007\\\"'", instanceName)); beginningOfFile.add(Utils.writeZeroPath(OsFamily.UNIX)); beginningOfFile.add(format("export INSTANCE_NAME='%s'", instanceName)); builder.append(createOrOverwriteFile(runScript, beginningOfFile.build(), DELIMITER).render(OsFamily.UNIX)); ImmutableMap.<String, String> of("abort", Utils.writeFunctionFromResource("abort", OsFamily.UNIX)), statements, OsFamily.UNIX); StringBuilder functions = new StringBuilder(); ScriptBuilder.writeFunctions(functionsToWrite, OsFamily.UNIX, functions); builder.append(appendFile(runScript, functions.toString(), DELIMITER).render(OsFamily.UNIX));
public String render(OsFamily family) { checkNotNull(family, "family"); if (family == OsFamily.WINDOWS) throw new UnsupportedOperationException("windows not yet implemented"); Builder<Statement> statements = ImmutableList.builder(); statements.add(createOrOverwriteFile(sudoers, ImmutableSet.of("root ALL = (ALL) ALL", "%wheel ALL = (ALL) NOPASSWD:ALL"))); statements.add(exec("chmod 0440 " + sudoers)); return new StatementList(statements.build()).render(family); }
private void addUnixRunScript(String runScript, StringBuilder builder) { builder.append("# add desired commands from the user\n"); Builder<String> userCommands = ImmutableList.builder(); userCommands.add("cd " + pwd); for (Statement statement : statements) { if (statement instanceof Call || (statement instanceof StatementList && any(StatementList.class.cast(statement).delegate(), instanceOf(Call.class)))) { statement = new ExitInsteadOfReturn(statement); } userCommands.addAll(Splitter.on('\n').split(statement.render(OsFamily.UNIX))); } builder.append(appendFile(runScript, userCommands.build(), DELIMITER).render(OsFamily.UNIX)); }
public void testWhenAdminAccessInsideList() { AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class); AdminAccess statement = createMock(AdminAccess.class); Credentials creds = createMock(Credentials.class); expect(statement.getAdminCredentials()).andReturn(creds); replay(configuration); replay(statement); replay(creds); assertEquals(CredentialsFromAdminAccess.INSTANCE.apply(Statements.newStatementList(statement)), creds); verify(configuration); verify(statement); verify(creds); }
@Override public String render(OsFamily family) { checkNotNull(family, "family"); if (family == OsFamily.WINDOWS) throw new UnsupportedOperationException("windows not yet implemented"); Builder<Statement> statements = ImmutableList.builder(); statements.add(exec("mkdir -p " + sshDir)); String authorizedKeys = sshDir + "{fs}authorized_keys"; statements.add(appendFile(authorizedKeys, Splitter.on('\n').split(Joiner.on("\n\n").join(publicKeys)))); statements.add(exec("chmod 600 " + authorizedKeys)); return new StatementList(statements.build()).render(family); } }
public void testExtractTargzIntoDirectoryUNIX() { Statement save = Statements .extractTargzIntoDirectory( URI.create("https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft_server.tar.gz"), "/opt/minecraft"); assertEquals( save.render(OsFamily.UNIX), "curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET https://s3.amazonaws.com/MinecraftDownload/launcher/minecraft_server.tar.gz |(mkdir -p /opt/minecraft &&cd /opt/minecraft &&tar -xpzf -)\n"); }
public void testWhenNotAdminAccess() { Statement statement = Statements.exec("echo hello"); assertEquals(CredentialsFromAdminAccess.INSTANCE.apply(statement), null); Statement statementList = Statements.newStatementList(statement); assertEquals(CredentialsFromAdminAccess.INSTANCE.apply(statementList), null); }
public void testWhenNotAdminAccess() { AdminAccess.Configuration configuration = createMock(AdminAccess.Configuration.class); InitAdminAccess initAdminAccess = new InitAdminAccess(configuration); replay(configuration); initAdminAccess.visit(Statements.exec("echo hello")); initAdminAccess.visit(Statements.newStatementList(Statements.exec("echo hello"))); verify(configuration); }
/** * Record timestamps for this phase execution on the remote machine */ @Override public void beforeBootstrap(ClusterActionEvent event) { addStatement(event, Statements.newStatementList( exec("date +%s > /tmp/bootstrap-start"), exec("sleep 60"), // 1 minute exec("date +%s > /tmp/bootstrap-end") )); recordTime("before-bootstrap"); }