Skip to content
This repository was archived by the owner on Nov 12, 2025. It is now read-only.

Commit fa7e0b8

Browse files
author
Valentin Aitken
committed
WinRM commands
Use executePsCommand and executeCmdCommand instead of executeScript WinRM Script tests
1 parent 9d5ba14 commit fa7e0b8

File tree

14 files changed

+464
-53
lines changed

14 files changed

+464
-53
lines changed

brooklyn-server/camp/camp-brooklyn/src/test/java/org/apache/brooklyn/camp/brooklyn/catalog/CatalogYamlTemplateTest.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323

2424
import java.util.List;
2525

26+
import com.google.common.collect.Iterables;
2627
import org.apache.brooklyn.api.entity.Application;
2728
import org.apache.brooklyn.api.entity.Entity;
2829
import org.apache.brooklyn.api.entity.EntitySpec;

brooklyn-server/launcher/src/test/java/org/apache/brooklyn/launcher/blueprints/Windows7zipBlueprintLiveTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ public void test7zip() throws Exception {
8888
String password = Strings.getFirstWordAfter(winRMAddress, ":");
8989

9090
WinRmTool winRmTool = WinRmTool.connect(ipPort, user, password);
91-
WinRmToolResponse winRmResponse = winRmTool.executePs(ImmutableList.of("(Get-Item \"C:\\\\Program Files\\\\7-Zip\\\\7z.exe\").name"));
91+
WinRmToolResponse winRmResponse = winRmTool.executePs("(Get-Item \"C:\\\\Program Files\\\\7-Zip\\\\7z.exe\").name");
9292

9393
LOG.info("winRmResponse: code="+winRmResponse.getStatusCode()+"; out="+winRmResponse.getStdOut()+"; err="+winRmResponse.getStdErr());
9494
return "7z.exe\r\n".equals(winRmResponse.getStdOut());

brooklyn-server/locations/jclouds/src/main/java/org/apache/brooklyn/location/jclouds/JcloudsLocation.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -862,7 +862,7 @@ protected MachineLocation obtainOnce(ConfigBag setup) throws NoMachinesAvailable
862862
String scriptContent = ResourceUtils.create(this).getResourceAsString(setupScriptItem);
863863
String script = TemplateProcessor.processTemplateContents(scriptContent, getManagementContext(), substitutions);
864864
if (windows) {
865-
((WinRmMachineLocation)machineLocation).executeCommand(ImmutableList.copyOf((script.replace("\r", "").split("\n"))));
865+
((WinRmMachineLocation)machineLocation).executeCommand(script);
866866
} else {
867867
((SshMachineLocation)machineLocation).execCommands("Customizing node " + this, ImmutableList.of(script));
868868
}
@@ -2664,6 +2664,8 @@ protected LoginCredentials waitForWinRmAvailable(final ComputeService computeSer
26642664
public Boolean call() {
26652665
for (Map.Entry<WinRmMachineLocation, LoginCredentials> entry : machinesToTry.entrySet()) {
26662666
WinRmMachineLocation machine = entry.getKey();
2667+
2668+
// TODO explicitely execute no retry
26672669
WinRmToolResponse response = machine.executeCommand(
26682670
ImmutableMap.of(WinRmTool.PROP_EXEC_TRIES.getName(), 1),
26692671
ImmutableList.of("echo testing"));

brooklyn-server/software/base/src/main/java/org/apache/brooklyn/entity/software/base/AbstractSoftwareProcessWinRmDriver.java

Lines changed: 45 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,19 @@
2929
import java.util.concurrent.Callable;
3030
import java.util.concurrent.TimeUnit;
3131

32+
import com.google.common.collect.ImmutableList;
3233
import org.apache.brooklyn.api.entity.EntityLocal;
3334
import org.apache.brooklyn.api.mgmt.Task;
3435
import org.apache.brooklyn.api.sensor.AttributeSensor;
3536
import org.apache.brooklyn.core.entity.BrooklynConfigKeys;
3637
import org.apache.brooklyn.core.entity.Entities;
3738
import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
3839
import org.apache.brooklyn.core.sensor.Sensors;
39-
import org.apache.brooklyn.entity.software.base.lifecycle.NativeWindowsScriptRunner;
4040
import org.apache.brooklyn.entity.software.base.lifecycle.WinRmExecuteHelper;
41+
import org.apache.brooklyn.location.winrm.NaiveWindowsScriptRunner;
4142
import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
43+
import org.apache.brooklyn.util.collections.MutableMap;
44+
import org.apache.brooklyn.util.core.internal.winrm.WinRmScriptTool;
4245
import org.apache.brooklyn.util.core.internal.winrm.WinRmTool;
4346
import org.apache.brooklyn.util.core.internal.winrm.WinRmToolResponse;
4447
import org.apache.brooklyn.util.core.task.Tasks;
@@ -51,11 +54,10 @@
5154
import org.slf4j.Logger;
5255
import org.slf4j.LoggerFactory;
5356

54-
import com.google.common.collect.ImmutableList;
5557
import com.google.common.collect.ImmutableMap;
5658
import com.google.common.collect.Maps;
5759

58-
public abstract class AbstractSoftwareProcessWinRmDriver extends AbstractSoftwareProcessDriver implements NativeWindowsScriptRunner {
60+
public abstract class AbstractSoftwareProcessWinRmDriver extends AbstractSoftwareProcessDriver implements NaiveWindowsScriptRunner {
5961
private static final Logger LOG = LoggerFactory.getLogger(AbstractSoftwareProcessWinRmDriver.class);
6062

6163
AttributeSensor<String> WINDOWS_USERNAME = Sensors.newStringSensor("windows.username",
@@ -175,7 +177,7 @@ public int copyResource(Map<Object, Object> sshFlags, String source, String targ
175177
if (createParentDir) {
176178
createDirectory(getDirectory(target), "Creating resource directory");
177179
}
178-
180+
179181
InputStream stream = null;
180182
try {
181183
Tasks.setBlockingDetails("retrieving resource "+source+" for copying across");
@@ -204,15 +206,15 @@ protected void createDirectory(String directoryName, String summaryForLogging) {
204206
}
205207

206208
@Override
207-
public Integer executeNativeOrPsCommand(Map flags, String regularCommand, String powerShellCommand, String phase, Boolean allowNoOp) {
209+
public Integer executeNativeOrPsCommand(Map flags, String regularCommand, final String powerShellCommand, String summaryForLogging, Boolean allowNoOp) {
208210
if (Strings.isBlank(regularCommand) && Strings.isBlank(powerShellCommand)) {
209211
if (allowNoOp) {
210212
return new WinRmToolResponse("", "", 0).getStatusCode();
211213
} else {
212-
throw new IllegalStateException(String.format("Exactly one of cmd or psCmd must be set for %s of %s", phase, entity));
214+
throw new IllegalStateException(String.format("Exactly one of cmd or psCmd must be set for %s of %s", summaryForLogging, entity));
213215
}
214216
} else if (!Strings.isBlank(regularCommand) && !Strings.isBlank(powerShellCommand)) {
215-
throw new IllegalStateException(String.format("%s and %s cannot both be set for %s of %s", regularCommand, powerShellCommand, phase, entity));
217+
throw new IllegalStateException(String.format("%s and %s cannot both be set for %s of %s", regularCommand, powerShellCommand, summaryForLogging, entity));
216218
}
217219

218220
ByteArrayOutputStream stdIn = new ByteArrayOutputStream();
@@ -236,7 +238,7 @@ public Integer executeNativeOrPsCommand(Map flags, String regularCommand, String
236238

237239
WinRmToolResponse response;
238240
if (Strings.isBlank(regularCommand)) {
239-
response = getLocation().executePsScript(ImmutableList.of(powerShellCommand));
241+
response = getLocation().executePsScript(powerShellCommand);
240242
} else {
241243
response = getLocation().executeCommand(ImmutableList.of(regularCommand));
242244
}
@@ -249,6 +251,24 @@ public Integer executeNativeOrPsCommand(Map flags, String regularCommand, String
249251
return response.getStatusCode();
250252
}
251253

254+
public int executeNativeOrPsScript(Map flags, List<String> regularCommands, final List<String> powerShellCommands, String summaryForLogging, Boolean allowNoOp) {
255+
if ((regularCommands == null || regularCommands.size() == 0) && (powerShellCommands == null || powerShellCommands.size() == 0)) {
256+
if (allowNoOp) {
257+
return new WinRmToolResponse("", "", 0).getStatusCode();
258+
} else {
259+
throw new IllegalStateException(String.format("Exactly one of cmd or psCmd must be set for %s", summaryForLogging));
260+
}
261+
}
262+
263+
MutableMap<String, Object> scriptProps = MutableMap.<String, Object>of(WinRmScriptTool.PROP_SUMMARY.getName(), summaryForLogging);
264+
WinRmScriptTool scriptTool = new WinRmScriptTool(scriptProps, this);
265+
if (regularCommands == null || regularCommands.size() == 0) {
266+
return scriptTool.execPsScript(flags, powerShellCommands);
267+
} else {
268+
return scriptTool.execNativeScript(flags, regularCommands);
269+
}
270+
}
271+
252272
private void writeToStream(ByteArrayOutputStream stream, String string) {
253273
try {
254274
stream.write(string.getBytes());
@@ -257,18 +277,30 @@ private void writeToStream(ByteArrayOutputStream stream, String string) {
257277
}
258278
}
259279

260-
public int execute(List<String> script) {
280+
public int execute(String script) {
261281
return getLocation().executeCommand(script).getStatusCode();
262282
}
263283

264-
public int executePsScriptNoRetry(List<String> psScript) {
265-
return getLocation().executePsScript(ImmutableMap.of(WinRmTool.PROP_EXEC_TRIES, 1), psScript).getStatusCode();
284+
public int executePsCommandNoRetry(String psCommand) {
285+
return getLocation().executePsScript(ImmutableMap.of(WinRmTool.PROP_EXEC_TRIES, 1), ImmutableList.of(psCommand)).getStatusCode();
286+
}
287+
288+
public int executeCommandNoRetry(String command) {
289+
return getLocation().executeCommand(ImmutableMap.of(WinRmTool.PROP_EXEC_TRIES, 1), ImmutableList.of(command)).getStatusCode();
266290
}
267291

268292
public int executePsScript(List<String> psScript) {
269293
return getLocation().executePsScript(psScript).getStatusCode();
270294
}
271295

296+
public WinRmToolResponse executeCommand(String cmdCommand) {
297+
return getLocation().executeCommand(cmdCommand);
298+
}
299+
300+
public WinRmToolResponse executePsScript(String psCommand) {
301+
return getLocation().executePsScript(psCommand);
302+
}
303+
272304
public int copyTo(File source, String destination) {
273305
return getLocation().copyTo(source, destination);
274306
}
@@ -278,12 +310,7 @@ public int copyTo(InputStream source, String destination) {
278310
}
279311

280312
public void rebootAndWait() {
281-
try {
282-
executePsScriptNoRetry(ImmutableList.of("Restart-Computer -Force"));
283-
} catch (Exception e) {
284-
// Restarting the computer will cause the command to fail; ignore the exception and continue
285-
Exceptions.propagateIfFatal(e);
286-
}
313+
executePsCommandNoRetry("Restart-Computer -Force");
287314
waitForWinRmStatus(false, entity.getConfig(VanillaWindowsProcess.REBOOT_BEGUN_TIMEOUT));
288315
waitForWinRmStatus(true, entity.getConfig(VanillaWindowsProcess.REBOOT_COMPLETED_TIMEOUT)).getWithError();
289316
}
@@ -298,7 +325,7 @@ private ReferenceWithError<Boolean> waitForWinRmStatus(final boolean requiredSta
298325
@Override
299326
public Boolean call() throws Exception {
300327
try {
301-
return (execute(ImmutableList.of("hostname")) == 0) == requiredStatus;
328+
return (execute("hostname") == 0) == requiredStatus;
302329
} catch (Exception e) {
303330
return !requiredStatus;
304331
}

brooklyn-server/software/base/src/main/java/org/apache/brooklyn/entity/software/base/lifecycle/WinRmExecuteHelper.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import org.apache.brooklyn.api.mgmt.Task;
3333
import org.apache.brooklyn.api.mgmt.TaskQueueingContext;
3434
import org.apache.brooklyn.core.mgmt.BrooklynTaskTags;
35+
import org.apache.brooklyn.location.winrm.NaiveWindowsScriptRunner;
3536
import org.apache.brooklyn.util.core.task.DynamicTasks;
3637
import org.apache.brooklyn.util.core.task.TaskBuilder;
3738
import org.apache.brooklyn.util.core.task.Tasks;
@@ -51,7 +52,7 @@ public class WinRmExecuteHelper {
5152

5253
private Task<Integer> task;
5354

54-
protected final NativeWindowsScriptRunner runner;
55+
protected final NaiveWindowsScriptRunner runner;
5556
public final String summary;
5657

5758
private String command;
@@ -62,7 +63,7 @@ public class WinRmExecuteHelper {
6263
protected Predicate<? super Integer> resultCodeCheck = Predicates.alwaysTrue();
6364
protected ByteArrayOutputStream stdout, stderr, stdin;
6465

65-
public WinRmExecuteHelper(NativeWindowsScriptRunner runner, String summary) {
66+
public WinRmExecuteHelper(NaiveWindowsScriptRunner runner, String summary) {
6667
this.runner = runner;
6768
this.summary = summary;
6869
}

brooklyn-server/software/base/src/test/java/org/apache/brooklyn/entity/software/base/VanillaWindowsProcessWinrmExitStatusLiveTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.apache.brooklyn.entity.software.base.test.location.WindowsTestFixture;
3535
import org.apache.brooklyn.location.winrm.WinRmMachineLocation;
3636
import org.apache.brooklyn.test.EntityTestUtils;
37+
import org.apache.brooklyn.util.exceptions.Exceptions;
3738
import org.apache.brooklyn.util.time.Duration;
3839
import org.slf4j.Logger;
3940
import org.slf4j.LoggerFactory;
@@ -147,6 +148,23 @@ public void testExecPsWithZeroExitCodes() {
147148
EntityTestUtils.assertAttributeEqualsEventually(entity, Attributes.SERVICE_UP, false);
148149
}
149150

151+
@Test(groups = "Live", expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "Execution failed, invalid result 1.*")
152+
public void testExecPsWithExitCodesWithMultiLineCommands() throws Throwable {
153+
try {
154+
VanillaWindowsProcess entity = app.createAndManageChild(EntitySpec.create(VanillaWindowsProcess.class)
155+
.configure(
156+
VanillaWindowsProcess.INSTALL_POWERSHELL_COMMAND,
157+
"exit 1")
158+
.configure(VanillaWindowsProcess.LAUNCH_POWERSHELL_COMMAND, "Write-Host launch")
159+
.configure(VanillaWindowsProcess.CHECK_RUNNING_POWERSHELL_COMMAND, "Write-Host checkrunning")
160+
.configure(VanillaWindowsProcess.STOP_POWERSHELL_COMMAND, "Write-Host stop"));
161+
162+
app.start(ImmutableList.of(machine));
163+
} catch (Exception e) {
164+
throw Exceptions.getFirstInteresting(e);
165+
}
166+
}
167+
150168
@Test(groups = "Live")
151169
public void testPreInstallNonZeroExitCode() {
152170
runExecNonZeroExitCode("pre-install-command");

0 commit comments

Comments
 (0)