<commit_before>/**
 * Copyright (C) FuseSource, Inc.
 * http://fusesource.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.fusesource.fabric.service.ssh;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.LinkedHashSet;
import java.util.Set;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.fusesource.fabric.api.Container;
import org.fusesource.fabric.api.ContainerProvider;
import org.fusesource.fabric.api.CreateContainerMetadata;
import org.fusesource.fabric.api.CreationStateListener;
import org.fusesource.fabric.api.FabricException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.fusesource.fabric.internal.ContainerProviderUtils.buildInstallAndStartScript;
import static org.fusesource.fabric.internal.ContainerProviderUtils.buildStartScript;
import static org.fusesource.fabric.internal.ContainerProviderUtils.buildStopScript;
import static org.fusesource.fabric.internal.ContainerProviderUtils.buildUninstallScript;

/**
 * A concrete {@link org.fusesource.fabric.api.ContainerProvider} that builds Containers via ssh.
 */
public class SshContainerProvider implements ContainerProvider<CreateSshContainerOptions, CreateSshContainerMetadata> {

    private static final String SCHEME = "ssh";

    private static final Logger logger = LoggerFactory.getLogger(SshContainerProvider.class);

    private boolean verbose = false;

    @Override
    public CreateSshContainerOptions.Builder newBuilder() {
        return CreateSshContainerOptions.builder();
    }

    /**
     * Creates an {@link org.fusesource.fabric.api.Container} with the given name pointing to the specified zooKeeperUrl.
     */
    public CreateSshContainerMetadata create(CreateSshContainerOptions options, CreationStateListener listener) {
        try {
            String path = options.getPath();
            String host = options.getHost();
            String ip = InetAddress.getByName(host).getHostAddress();
            if (host == null) {
                throw new IllegalArgumentException("Host name not specified.");
            }
            int port = options.getPort();
            if (port == -1) {
                port = 22;
            }

            String containerName = options.getName();
            CreateSshContainerMetadata metadata = new CreateSshContainerMetadata();
            metadata.setCreateOptions(options);
            metadata.setContainerName(containerName);
            String script = buildInstallAndStartScript(containerName, options);
            logger.debug("Running script on host {}:\n{}", host, script);
            try {
                runScriptOnHost(options,script);
            } catch (Throwable ex) {
                metadata.setFailure(ex);
            }
            return metadata;
        } catch (Exception e) {
            throw FabricException.launderThrowable(e);
        }
    }

    @Override
    public void start(Container container) {
        CreateContainerMetadata metadata = container.getMetadata();
        if (!(metadata instanceof CreateSshContainerMetadata)) {
            throw new IllegalStateException("Container doesn't have valid create container metadata type");
        } else {
            CreateSshContainerMetadata sshContainerMetadata = (CreateSshContainerMetadata) metadata;
            CreateSshContainerOptions options = sshContainerMetadata.getCreateOptions();
            try {
                String script = buildStartScript(container.getId(), options);
                runScriptOnHost(options,script);
            } catch (Throwable t) {
                logger.error("Failed to start container: "+container.getId(),t);
            }
        }
    }

    @Override
    public void stop(Container container) {
        CreateContainerMetadata metadata = container.getMetadata();
        if (!(metadata instanceof CreateSshContainerMetadata)) {
            throw new IllegalStateException("Container doesn't have valid create container metadata type");
        } else {
            CreateSshContainerMetadata sshContainerMetadata = (CreateSshContainerMetadata) metadata;
            CreateSshContainerOptions options = sshContainerMetadata.getCreateOptions();
            try {
                String script = buildStopScript(container.getId(), options);
                runScriptOnHost(options,script);
            } catch (Throwable t) {
                logger.error("Failed to stop container: " + container.getId(), t);
            }
        }
    }

    @Override
    public void destroy(Container container) {
        CreateContainerMetadata metadata = container.getMetadata();
        if (!(metadata instanceof CreateSshContainerMetadata)) {
            throw new IllegalStateException("Container doesn't have valid create container metadata type");
        } else {
            CreateSshContainerMetadata sshContainerMetadata = (CreateSshContainerMetadata) metadata;
            CreateSshContainerOptions options = sshContainerMetadata.getCreateOptions();
            try {
                String script = buildUninstallScript(container.getId(), options);
                runScriptOnHost(options, script);
            } catch (Throwable t) {
                logger.error("Failed to stop container: "+container.getId(),t);
            }
        }
    }

    @Override
    public String getScheme() {
        return SCHEME;
    }

    @Override
    public Class<CreateSshContainerOptions> getOptionsType() {
        return CreateSshContainerOptions.class;
    }

    @Override
    public Class<CreateSshContainerMetadata> getMetadataType() {
        return CreateSshContainerMetadata.class;
    }

    protected void runScriptOnHost(CreateSshContainerOptions options, String script) throws Exception {
        Session session = null;
        Exception connectException = null;
        for (int i = 0; i <= options.getSshRetries(); i++) {
            if (i > 0) {
                long delayMs = (long) (200L * Math.pow(i, 2));
                Thread.sleep(delayMs);
            }
            try {
                JSch jsch = new JSch();
                byte[] privateKey = readFile(options.getPrivateKeyFile());
                byte[] passPhrase = options.getPassPhrase() != null ? options.getPassPhrase().getBytes() : null;
                if (privateKey != null && options.getPassword() == null) {
                    jsch.addIdentity(options.getUsername(),privateKey,null, passPhrase);
                    session = jsch.getSession(options.getUsername(), options.getHost(), options.getPort());
                } else {
                    session = jsch.getSession(options.getUsername(), options.getHost(), options.getPort());
                    session.setPassword(options.getPassword());
                }
                session.setTimeout(60000);
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                connectException = null;
                break;
            } catch (Exception from) {
                connectException = from;
                if (session != null && session.isConnected()) {
                    session.disconnect();<commit_msg>[FABRIC-476] Prevent jsch prompting from credentials.<commit_after>/**
 * Copyright (C) FuseSource, Inc.
 * http://fusesource.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.fusesource.fabric.service.ssh;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.util.LinkedHashSet;
import java.util.Set;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import org.fusesource.fabric.api.Container;
import org.fusesource.fabric.api.ContainerProvider;
import org.fusesource.fabric.api.CreateContainerMetadata;
import org.fusesource.fabric.api.CreationStateListener;
import org.fusesource.fabric.api.FabricException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.fusesource.fabric.internal.ContainerProviderUtils.buildInstallAndStartScript;
import static org.fusesource.fabric.internal.ContainerProviderUtils.buildStartScript;
import static org.fusesource.fabric.internal.ContainerProviderUtils.buildStopScript;
import static org.fusesource.fabric.internal.ContainerProviderUtils.buildUninstallScript;

/**
 * A concrete {@link org.fusesource.fabric.api.ContainerProvider} that builds Containers via ssh.
 */
public class SshContainerProvider implements ContainerProvider<CreateSshContainerOptions, CreateSshContainerMetadata> {

    private static final String SCHEME = "ssh";

    private static final Logger logger = LoggerFactory.getLogger(SshContainerProvider.class);

    private boolean verbose = false;

    @Override
    public CreateSshContainerOptions.Builder newBuilder() {
        return CreateSshContainerOptions.builder();
    }

    /**
     * Creates an {@link org.fusesource.fabric.api.Container} with the given name pointing to the specified zooKeeperUrl.
     */
    public CreateSshContainerMetadata create(CreateSshContainerOptions options, CreationStateListener listener) {
        try {
            String path = options.getPath();
            String host = options.getHost();
            String ip = InetAddress.getByName(host).getHostAddress();
            if (host == null) {
                throw new IllegalArgumentException("Host name not specified.");
            }
            int port = options.getPort();
            if (port == -1) {
                port = 22;
            }

            String containerName = options.getName();
            CreateSshContainerMetadata metadata = new CreateSshContainerMetadata();
            metadata.setCreateOptions(options);
            metadata.setContainerName(containerName);
            String script = buildInstallAndStartScript(containerName, options);
            logger.debug("Running script on host {}:\n{}", host, script);
            try {
                runScriptOnHost(options,script);
            } catch (Throwable ex) {
                metadata.setFailure(ex);
            }
            return metadata;
        } catch (Exception e) {
            throw FabricException.launderThrowable(e);
        }
    }

    @Override
    public void start(Container container) {
        CreateContainerMetadata metadata = container.getMetadata();
        if (!(metadata instanceof CreateSshContainerMetadata)) {
            throw new IllegalStateException("Container doesn't have valid create container metadata type");
        } else {
            CreateSshContainerMetadata sshContainerMetadata = (CreateSshContainerMetadata) metadata;
            CreateSshContainerOptions options = sshContainerMetadata.getCreateOptions();
            try {
                String script = buildStartScript(container.getId(), options);
                runScriptOnHost(options,script);
            } catch (Throwable t) {
                logger.error("Failed to start container: "+container.getId(),t);
            }
        }
    }

    @Override
    public void stop(Container container) {
        CreateContainerMetadata metadata = container.getMetadata();
        if (!(metadata instanceof CreateSshContainerMetadata)) {
            throw new IllegalStateException("Container doesn't have valid create container metadata type");
        } else {
            CreateSshContainerMetadata sshContainerMetadata = (CreateSshContainerMetadata) metadata;
            CreateSshContainerOptions options = sshContainerMetadata.getCreateOptions();
            try {
                String script = buildStopScript(container.getId(), options);
                runScriptOnHost(options,script);
            } catch (Throwable t) {
                logger.error("Failed to stop container: " + container.getId(), t);
            }
        }
    }

    @Override
    public void destroy(Container container) {
        CreateContainerMetadata metadata = container.getMetadata();
        if (!(metadata instanceof CreateSshContainerMetadata)) {
            throw new IllegalStateException("Container doesn't have valid create container metadata type");
        } else {
            CreateSshContainerMetadata sshContainerMetadata = (CreateSshContainerMetadata) metadata;
            CreateSshContainerOptions options = sshContainerMetadata.getCreateOptions();
            try {
                String script = buildUninstallScript(container.getId(), options);
                runScriptOnHost(options, script);
            } catch (Throwable t) {
                logger.error("Failed to stop container: "+container.getId(),t);
            }
        }
    }

    @Override
    public String getScheme() {
        return SCHEME;
    }

    @Override
    public Class<CreateSshContainerOptions> getOptionsType() {
        return CreateSshContainerOptions.class;
    }

    @Override
    public Class<CreateSshContainerMetadata> getMetadataType() {
        return CreateSshContainerMetadata.class;
    }

    protected void runScriptOnHost(CreateSshContainerOptions options, String script) throws Exception {
        Session session = null;
        Exception connectException = null;
        for (int i = 0; i <= options.getSshRetries(); i++) {
            if (i > 0) {
                long delayMs = (long) (200L * Math.pow(i, 2));
                Thread.sleep(delayMs);
            }
            try {
                JSch jsch = new JSch();
                byte[] privateKey = readFile(options.getPrivateKeyFile());
                byte[] passPhrase = options.getPassPhrase() != null ? options.getPassPhrase().getBytes() : null;
                if (privateKey != null && options.getPassword() == null) {
                    jsch.addIdentity(options.getUsername(),privateKey,null, passPhrase);
                    session = jsch.getSession(options.getUsername(), options.getHost(), options.getPort());
                } else {
                    session = jsch.getSession(options.getUsername(), options.getHost(), options.getPort());
                    session.setPassword(options.getPassword());
                }
                session.setTimeout(60000);
                java.util.Properties config = new java.util.Properties();
                config.put("StrictHostKeyChecking", "no");
                config.put("PreferredAuthentications", "publickey,password");
                session.setConfig(config);
                session.connect();
                connectException = null;
                break;
            } catch (Exception from) {
                connectException = from;
                if (session != null && session.isConnected()) {
                    session.disconnect();
{'fraction_non_alphanumeric': 0.09037426461384404, 'fraction_numerical': 0.0026912004005507574, 'mean_word_length': 2.620892816677997, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5941490', 'n_tokens_mistral': 3973, 'n_tokens_neox': 3794, 'n_words': 974}