• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java ExecResponse类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中org.jclouds.compute.domain.ExecResponse的典型用法代码示例。如果您正苦于以下问题:Java ExecResponse类的具体用法?Java ExecResponse怎么用?Java ExecResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ExecResponse类属于org.jclouds.compute.domain包,在下文中一共展示了ExecResponse类的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: isSudoersFixRequired

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * Returns true if fixing /etc/sudoers (disabling "Defaults requiretty" configuration option) is required for given Node.
 *
 * @param node Node to check
 * @param jcloudsSshClient SSH client instance
 * @return true if fix is required by node configuration and "/etc/sudoers" file exists, false otherwise
 */
private boolean isSudoersFixRequired(AbstractJCloudsNode<?> node, org.jclouds.ssh.SshClient jcloudsSshClient) {
    final String fixSudoersPropertyName = node.getCloudProvider().getProviderSpecificPropertyName(node.config(),
            Config.Node.Shared.SSH_FIX_SUDOERS);

    // check if fixing /etc/sudoers is requested in Node configuration
    if (node.config().getPropertyAsBoolean(fixSudoersPropertyName, false)) {
        // check if /etc/sudoers exists on the Node
        ExecResponse sudoersResult = jcloudsSshClient
                .exec("sh -c '" + SshUtils.FileType.getShellTestStr("/etc/sudoers") + "'");
        SshUtils.FileType sudoersFile = SshUtils.FileType.fromExitCode(sudoersResult.getExitStatus());
        if (sudoersFile == SshUtils.FileType.FILE) {
            return true;
        }
    }
    return false;
}
 
开发者ID:wildfly-extras,项目名称:sunstone,代码行数:24,代码来源:JCloudsSshClient.java


示例2: unmountVolume

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * Make sure you've unmounted the volume first. Failure to do so could result in failure or data loss.
 */
private void unmountVolume(VolumeAttachment volumeAttachment) {
   System.out.format("Unmount Volume%n");

   String script = new ScriptBuilder().addStatement(exec("umount /mnt")).render(OsFamily.UNIX);

   RunScriptOptions options = RunScriptOptions.Builder
         .overrideLoginUser(ROOT)
         .overrideLoginPassword(PASSWORD)
         .blockOnComplete(true);

   RegionAndId regionAndId = RegionAndId.fromRegionAndId(REGION, volumeAttachment.getServerId());
   ExecResponse response = computeService.runScriptOnNode(regionAndId.slashEncode(), script, options);

   if (response.getExitStatus() == 0) {
      System.out.format("  Exit Status: %s%n", response.getExitStatus());
   }
   else {
      System.out.format("  Error: %s%n",response.getOutput());
   }
}
 
开发者ID:jclouds,项目名称:jclouds-examples,代码行数:24,代码来源:DetachVolume.java


示例3: mountVolume

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
private void mountVolume(NodeMetadata node) {
   System.out.format("Mount Volume and Create Filesystem%n");

   String script = new ScriptBuilder()
         .addStatement(exec("mkfs -t ext4 /dev/xvdd"))
         .addStatement(exec("mount /dev/xvdd /mnt"))
         .render(OsFamily.UNIX);

   RunScriptOptions options = RunScriptOptions.Builder
         .blockOnComplete(true)
         .overrideLoginPassword(PASSWORD);

   ExecResponse response = computeService.runScriptOnNode(node.getId(), script, options);

   if (response.getExitStatus() == 0) {
      System.out.format("  Exit Status: %s%n", response.getExitStatus());
   }
   else {
      System.out.format("  Error: %s%n", response.getOutput());
   }
}
 
开发者ID:jclouds,项目名称:jclouds-examples,代码行数:22,代码来源:CreateVolumeAndAttach.java


示例4: runScriptOnGroup

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
private static void runScriptOnGroup(final ComputeService compute,
                                     final LoginCredentials login, final String groupName, final Statement command)
        throws RunScriptOnNodesException {
    // when you run commands, you can pass options to decide whether
    // to run it as root, supply or own credentials vs from cache,
    // and wrap in an init script vs directly invoke
    Map<? extends NodeMetadata, ExecResponse> execResponses =
            compute.runScriptOnNodesMatching(//
                    inGroup(groupName), // predicate used to select nodes
                    command, // what you actually intend to run
                    overrideLoginCredentials(login)); // use the local user & ssh key

    for (Entry<? extends NodeMetadata, ExecResponse> response : execResponses.entrySet()) {
        System.out.printf(
                "<< node %s: %s%n",
                response.getKey().getId(),
                concat(response.getKey().getPrivateAddresses(), response.getKey()
                        .getPublicAddresses())
        );
        System.out.printf("<<     %s%n", response.getValue());
    }
}
 
开发者ID:jclouds,项目名称:jclouds-examples,代码行数:23,代码来源:MainApp.java


示例5: exec

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
public static ExecResult exec(SshClient sshClient, String... command) throws OperationNotSupportedException {
    // note that this is much better than ComputeService.runScriptOnNode, which uses a monstrous script
    // that embeds the 'command' and messes up with the exit code

    StringBuilder stringBuilder = new StringBuilder();
    for (String string : command) {
        stringBuilder.append('\'').append(string).append('\'').append(" ");
    }
    ExecResponse execResponse = sshClient.exec(stringBuilder.toString());
    sshClient.disconnect();
    return new DefaultExecResult(execResponse.getOutput(), execResponse.getError(), execResponse.getExitStatus());
}
 
开发者ID:wildfly-extras,项目名称:sunstone,代码行数:13,代码来源:SshUtils.java


示例6: testLaunchClusterWithDomainName

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
@Test
    public void testLaunchClusterWithDomainName() throws RunNodesException {
        final String name = "test";

        Template template = view.getComputeService().templateBuilder()
                .osFamily(OsFamily.UBUNTU)
                .locationId("NA9")
                //.minRam(8192)
                //.locationId("NA12")
                .build();

        DimensionDataCloudControllerTemplateOptions options = template.getOptions().as(DimensionDataCloudControllerTemplateOptions.class);
        options
                .inboundPorts(22, 8080, 8081)
                .runScript(AdminAccess.standard())
                .networkDomainId("91f577d2-5812-4e39-a79f-a35e42eb78a6")
                .vlanId("025c59d7-b7e5-4261-95b8-4af067233ee7");

        try {
            Set<? extends NodeMetadata> nodes = view.getComputeService().createNodesInGroup(name, NUM_NODES, template);
            assertThat(nodes).hasSize(NUM_NODES);

            Map<? extends NodeMetadata, ExecResponse> responses = view.getComputeService().runScriptOnNodesMatching(runningInGroup(name), "echo hello");
            assertThat(responses).hasSize(NUM_NODES);

            for (ExecResponse execResponse : responses.values()) {
                assertThat(execResponse.getOutput().trim()).isEqualTo("hello");
            }
        } catch (RunScriptOnNodesException e) {
            Assert.fail();
        } finally {
            view.getComputeService().destroyNodesMatching(inGroup(name));
        }
}
 
开发者ID:cloudsoft,项目名称:amp-dimensiondata,代码行数:35,代码来源:DimensionDataCloudControllerComputeServiceContextLiveTest.java


示例7: runScriptOnNode

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * Runs a script on the target node.
 */
protected void runScriptOnNode(Exchange exchange) throws CamelException {
    String script = exchange.getIn().getBody(String.class);
    String nodeId = getNodeId(exchange);
    String user = getUser(exchange);

    LoginCredentials credentials = null;

    if (ObjectHelper.isNotEmpty(user)) {
        credentials = LoginCredentials.builder().user(user).build();
    }
    ExecResponse execResponse = null;

    if (credentials == null) {
        execResponse = computeService.runScriptOnNode(nodeId, script);
    } else {
        execResponse = computeService.runScriptOnNode(nodeId, script, RunScriptOptions.Builder.overrideLoginCredentials(credentials).runAsRoot(false));
    }

    if (execResponse == null) {
        throw new CamelExchangeException("Failed to receive response for run script operation on node: " + nodeId + " using script: " + script, exchange);
    }

    exchange.setProperty(JcloudsConstants.RUN_SCRIPT_ERROR, execResponse.getError());
    exchange.setProperty(JcloudsConstants.RUN_SCRIPT_EXIT_CODE, execResponse.getExitStatus());
    exchange.getOut().setBody(execResponse.getOutput());
}
 
开发者ID:HydAu,项目名称:Camel,代码行数:30,代码来源:JcloudsComputeProducer.java


示例8: log

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * Logs the script output
 * @param data the results
 * @return the result for further processing
 */
private Map<? extends NodeMetadata, ExecResponse> log(Map<? extends NodeMetadata, ExecResponse> data) {
	for (NodeMetadata node : data.keySet()) {
		log(node, data.get(node));
	}
	return data;
}
 
开发者ID:jasonrig,项目名称:openstack-queue,代码行数:12,代码来源:ServerCollection.java


示例9: onSuccess

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
@Subscribe
@AllowConcurrentEvents
public void onSuccess(StatementOnNodeCompletion event) {
   ExecResponse arg0 = event.getResponse();
   if (arg0.getExitStatus() != 0) {
      logger.error("<< error running {} on node({}): {}", new Object[] { event.getStatement(), event.getNode().getId(),
            arg0 });
   } else {
      logger.info("<< success executing {} on node({}): {}", new Object[] { event.getStatement(),
            event.getNode().getId(), arg0 });
   }
}
 
开发者ID:jclouds,项目名称:jclouds-examples,代码行数:13,代码来源:MainApp.java


示例10: stdoutFromCommandOnGroup

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public Map<NodeMetadata, String> stdoutFromCommandOnGroup(String command, String group) {
   try {
      return transformValues((Map<NodeMetadata, ExecResponse>) compute.runScriptOnNodesMatching(
            runningInGroup(group), command, asCurrentUser().wrapInInitScript(false)), getStdout());
   } catch (RunScriptOnNodesException e) {
      throw propagate(e);
   }
}
 
开发者ID:jclouds,项目名称:jclouds-examples,代码行数:10,代码来源:NodeManager.java


示例11: getStdout

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
public static Function<ExecResponse, String> getStdout() {
   return new Function<ExecResponse, String>() {

      @Override
      public String apply(ExecResponse input) {
         return input.getOutput();
      }
   };
}
 
开发者ID:jclouds,项目名称:jclouds-examples,代码行数:10,代码来源:Utils.java


示例12: copyFileFromNode

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * Copies a remote file or folder to the local machine.
 *
 * @param remoteSrc path to remote file of folder
 * @param localTarget path to local folder, or, if {@code remoteSrc} is a file, also a file
 * @throws OperationNotSupportedException if this node implementation doesn't provide ssh access
 * @throws IllegalArgumentException if {@code remoteSrc} is a folder and {@code localTarget} is a regular file or if
 *         {@code remoteSrc} is an empty string
 * @throws NullPointerException if {@code remoteSrc} or {@code localTarget} is {@code null}.
 * @throws FileNotFoundException if {@code remoteSrc} does not exist
 */
@Override
public void copyFileFromNode(String remoteSrc, Path localTarget) throws OperationNotSupportedException,
        IllegalArgumentException, NullPointerException, IOException, InterruptedException {
    if (remoteSrc == null || localTarget == null) {
        throw new NullPointerException("Remote path and local path can't be null.");
    }
    if (Strings.isNullOrEmpty(remoteSrc)) {
        throw new IllegalArgumentException("Remote path must not be empty.");
    }

    SunstoneCoreLogger.SSH.debug("Copying remote path '{}' on node '{}' to local target '{}'", remoteSrc, getName(),
            localTarget);

    SshUtils.FileType remoteFileType = SshUtils.FileType
            .fromExitCode(exec("sh", "-c", SshUtils.FileType.getShellTestStr(remoteSrc)).getExitCode());
    if (remoteFileType == SshUtils.FileType.NA) {
        throw new FileNotFoundException("Source file " + remoteSrc + " doesn't exist in node " + getName());
    }

    SshUtils.FileType localFileType = SshUtils.FileType.fromPath(localTarget);
    if (localFileType == SshUtils.FileType.FILE && remoteFileType == SshUtils.FileType.DIRECTORY) {
        throw new IllegalArgumentException(
                "Unable to copy remote directory " + remoteSrc + " to local regular file " + localTarget);
    }

    SshClient sshClient = getSsh();
    Path remoteFile = Paths.get(remoteSrc);
    String remoteTarSrc = remoteFile.getParent() + "/" + remoteFile.getFileName() + ".tar"; // TODO: separators for other
                                                                                            // platforms?
    String command = "cd " + remoteFile.getParent().toString() + " ; tar " + "cf " + remoteTarSrc + " "
            + remoteFile.getFileName().toString();
    SunstoneCoreLogger.SSH.debug("Using command '{}' to tar remote file on node '{}'", command, getName());
    ExecResponse execResponse = sshClient.exec(command);
    if (execResponse.getExitStatus() != 0) {
        SunstoneCoreLogger.SSH.warn("Error output when copying file on node '{}': {}", getName(), execResponse.getError());
        throw new IllegalStateException("File cannot be copied successfully. Return code of remote tar archive creation is "
                + execResponse.getExitStatus());
    }

    Payload payload = sshClient.get(remoteTarSrc);

    try (TarInputStream tis = new TarInputStream(payload.openStream())) {
        if (remoteFileType == SshUtils.FileType.DIRECTORY) {
            SshUtils.untarFolder(tis, localTarget,
                    localFileType == SshUtils.FileType.NA ? new File(remoteSrc).getName() : null);
        } else {
            SshUtils.untarFile(tis, localTarget, localFileType == SshUtils.FileType.DIRECTORY);
        }

        while (tis.getNextEntry() != null) {
            // just skip
        }
    } catch (IOException e) {
        throw new RuntimeException(
                "Copying file " + remoteSrc + " from node " + getInitialNodeMetadata().getId() + " failed", e);
    } finally {
        exec("rm", remoteTarSrc); // TODO why not sshClient.exec(), like above for the 'tar' command?
        sshClient.disconnect();
        SunstoneCoreLogger.SSH.debug("Copied remote path '{}' on node '{}' to local target '{}'", remoteSrc, getName(),
                localTarget);
    }
}
 
开发者ID:wildfly-extras,项目名称:sunstone,代码行数:74,代码来源:AbstractJCloudsNode.java


示例13: JCloudsSshClient

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * @throws OperationNotSupportedException when connecting to SSH fails, presumably because there's no SSH server
 * @throws InterruptedException when interrupted while waiting for SSH to connect
 */
public JCloudsSshClient(AbstractJCloudsNode<?> node) throws OperationNotSupportedException, InterruptedException {

    org.jclouds.ssh.SshClient jcloudsSshClient = null;
    boolean connected = false;

    ExponentialBackoff backoff = new ExponentialBackoff(1000);
    long endTime = System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(1);
    int count = 1;
    while (System.currentTimeMillis() < endTime) {
        NodeMetadata nodeMetadata = node.getFreshNodeMetadata();
        jcloudsSshClient = node.getCloudProvider().getComputeServiceContext().utils().sshForNode().apply(nodeMetadata);

        if (jcloudsSshClient != null) {
            try {
                jcloudsSshClient.connect();
                connected = true;
                break;
            } catch (Exception e) {
                SunstoneCoreLogger.SSH.debug("Failed to establish SSH connection to node '{}' (attempt {})", node.getName(),
                        count, e);

                try {
                    jcloudsSshClient.disconnect();
                } catch (Exception e2) {
                    SunstoneCoreLogger.SSH.trace("Failed to destroy SSH client that failed to connect", e2);
                }
            }
        }

        backoff.delay();

        count++;
    }

    if (jcloudsSshClient == null || !connected) {
        SunstoneCoreLogger.SSH.warn("Failed to establish SSH connection to node '{}'", node.getName());
        throw new OperationNotSupportedException("Failed to establish SSH connection to node '" + node.getName() + "'");
    }

    if (isSudoersFixRequired(node, jcloudsSshClient)) {
        // see https://bugzilla.redhat.com/show_bug.cgi?id=1020147
        LOGGER.trace("Removing 'Defaults requiretty' from /etc/sudoers so that sudo works without a PTY");
        ExecResponse result = jcloudsSshClient
                .exec("sudo -n sed -i -e 's/^Defaults[ ]\\+requiretty/#Defaults requiretty/' /etc/sudoers");
        if (result.getExitStatus() != 0) {
            LOGGER.warn("Failed removing 'Defaults requiretty' from /etc/sudoers, running with sudo might not work");
            LOGGER.debug("stdout: {}", result.getOutput());
            LOGGER.debug("stderr: {}", result.getError());
        }
    }

    this.jclouds = jcloudsSshClient;
}
 
开发者ID:wildfly-extras,项目名称:sunstone,代码行数:58,代码来源:JCloudsSshClient.java


示例14: startDaemonOnNode

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
public ExecResponse startDaemonOnNode(InitScript daemon, String nodeId) {
   return compute.runScriptOnNode(nodeId, daemon, asCurrentUser().blockOnComplete(false));
}
 
开发者ID:jclouds,项目名称:jclouds-examples,代码行数:4,代码来源:NodeManager.java


示例15: callOnHosts

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/** TODO: Move to CassandraService? */
protected void callOnHosts(List<InetAddress> hosts, String functionName, String... functionArgs)
{
    final Set<String> hostset = new HashSet<String>();

    for (InetAddress host : hosts)
        hostset.add(host.getHostAddress());

    StatementBuilder statementBuilder = new StatementBuilder();
    statementBuilder.addStatement(Statements.call(functionName, functionArgs));
    Credentials credentials = new Credentials(clusterSpec.getClusterUser(), clusterSpec.getPrivateKey());

    Map<? extends NodeMetadata,ExecResponse> results;
    try
    {
        results = computeService.runScriptOnNodesMatching(new Predicate<NodeMetadata>()
        {
            public boolean apply(NodeMetadata node)
            {
                Set<String> intersection = new HashSet<String>(hostset);
                intersection.retainAll(node.getPublicAddresses());
                return !intersection.isEmpty();
            }
        },
        statementBuilder,
        RunScriptOptions.Builder.overrideCredentialsWith(credentials).wrapInInitScript(false).runAsRoot(false));
    }
    catch (RunScriptOnNodesException e)
    {
        throw new RuntimeException(e);
    }

    if (results.size() != hostset.size())
    {
        throw new RuntimeException(results.size() + " hosts matched " + hostset + ": " + results);
    }

    for (ExecResponse response : results.values())
    {
        if (response.getExitCode() != 0)
        {
            throw new RuntimeException("Call " + functionName + " failed on at least one of " + hostset + ": " + results.values());
        }
    }
}
 
开发者ID:devdattakulkarni,项目名称:Cassandra-KVPM,代码行数:46,代码来源:CassandraServiceController.java


示例16: runScriptOnNode

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * Runs a script on a node
 * @param nodeIndex node index
 * @param script the script to run
 * @return the result
 * @throws RunScriptOnNodesException
 */
public ExecResponse runScriptOnNode(int nodeIndex, String script) throws RunScriptOnNodesException {
	requireOpenState();
	
	NodeMetadata node = getNodeMetadata().asList().get(nodeIndex);
	return log(node, getComputeService().runScriptOnNode(node.getId(), script, getScriptLoginCredentials().runAsRoot(true).wrapInInitScript(false)));
}
 
开发者ID:jasonrig,项目名称:openstack-queue,代码行数:14,代码来源:ServerCollection.java


示例17: submitScriptOnNode

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * Non-blocking script execution on a remote node
 * @param nodeIndex node index
 * @param script the script to run
 * @return a ListenableFuture object to access the result once the script is complete
 * @throws RunScriptOnNodesException
 */
public ListenableFuture<ExecResponse> submitScriptOnNode(int nodeIndex, String script) throws RunScriptOnNodesException {
	requireOpenState();
	
	NodeMetadata node = getNodeMetadata().asList().get(nodeIndex);
	return log(node, getComputeService().submitScriptOnNode(node.getId(), script, getScriptLoginCredentials().runAsRoot(true).wrapInInitScript(false)));
}
 
开发者ID:jasonrig,项目名称:openstack-queue,代码行数:14,代码来源:ServerCollection.java


示例18: runScriptOnAllNodes

import org.jclouds.compute.domain.ExecResponse; //导入依赖的package包/类
/**
 * Runs a script on all nodes
 * @param script the script to run
 * @return the results from all nodes on which this script was run
 * @throws RunScriptOnNodesException
 */
public Map<? extends NodeMetadata, ExecResponse> runScriptOnAllNodes(String script) throws RunScriptOnNodesException {
	requireOpenState();
	
	return log(getComputeService().runScriptOnNodesMatching(getGroupPredicate(), script, getScriptLoginCredentials().runAsRoot(true).wrapInInitScript(false)));
}
 
开发者ID:jasonrig,项目名称:openstack-queue,代码行数:12,代码来源:ServerCollection.java



注:本文中的org.jclouds.compute.domain.ExecResponse类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java UserStoreException类代码示例发布时间:2022-05-22
下一篇:
Java EclipsePreferences类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap