Search in sources :

Example 41 with Connection

use of org.ovirt.engine.sdk4.Connection in project Payara by payara.

the class SSHLauncher method setupKey.

/**
 * Setting up the key involves the following steps:
 * -If a key exists and we can connect using the key, do nothing.
 * -Generate a key pair if there isn't one
 * -Connect to remote host using password auth and do the following:
 *  1. create .ssh directory if it doesn't exist
 *  2. copy over the key as key.tmp
 *  3. Append the key to authorized_keys file
 *  4. Remove the temporary key file key.tmp
 *  5. Fix permissions for home, .ssh and authorized_keys
 * @param node        - remote host
 * @param pubKeyFile  - .pub file
 * @param generateKey - flag to indicate if key needs to be generated or not
 * @param passwd      - ssh user password
 * @throws IOException
 * @throws InterruptedException
 */
public void setupKey(String node, String pubKeyFile, boolean generateKey, String passwd) throws IOException, InterruptedException {
    boolean connected = false;
    File key = new File(keyFile);
    if (logger.isLoggable(Level.FINER))
        logger.finer("Key = " + keyFile);
    if (key.exists()) {
        if (checkConnection()) {
            throw new IOException("SSH public key authentication is already configured for " + userName + "@" + node);
        }
    } else {
        if (generateKey) {
            if (!generateKeyPair()) {
                throw new IOException("SSH key pair generation failed. Please generate key manually.");
            }
        } else {
            throw new IOException("SSH key pair not present. Please generate a key pair manually or specify an existing one and re-run the command.");
        }
    }
    // password is must for key distribution
    if (passwd == null) {
        throw new IOException("SSH password is required for distributing the public key. You can specify the SSH password in a password file and pass it through --passwordfile option.");
    }
    connection = new Connection(node, port);
    connection.connect();
    connected = connection.authenticateWithPassword(userName, passwd);
    if (!connected) {
        throw new IOException("SSH password authentication failed for user " + userName + " on host " + node);
    }
    // We open up a second connection for scp and exec. For some reason, a hang
    // is seen in MKS if we try to do everything using the same connection.
    Connection conn = new Connection(node, port);
    conn.connect();
    boolean ret = conn.authenticateWithPassword(userName, passwd);
    if (!ret) {
        throw new IOException("SSH password authentication failed for user " + userName + " on host " + node);
    }
    // initiate scp client
    SCPClient scp = new SCPClient(conn);
    SFTPClient sftp = new SFTPClient(connection);
    if (key.exists()) {
        // fixes .ssh file mode
        setupSSHDir();
        if (pubKeyFile == null) {
            pubKeyFile = keyFile + ".pub";
        }
        File pubKey = new File(pubKeyFile);
        if (!pubKey.exists()) {
            throw new IOException("Public key file " + pubKeyFile + " does not exist.");
        }
        try {
            if (!sftp.exists(SSH_DIR)) {
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine(SSH_DIR + " does not exist");
                }
                sftp.mkdirs(".ssh", 0700);
            }
        } catch (Exception e) {
            if (logger.isLoggable(Level.FINER)) {
                e.printStackTrace();
            }
            throw new IOException("Error while creating .ssh directory on remote host:" + e.getMessage());
        }
        // copy over the public key to remote host
        scp.put(pubKey.getAbsolutePath(), "key.tmp", ".ssh", "0600");
        // append the public key file contents to authorized_keys file on remote host
        String mergeCommand = "cd .ssh; cat key.tmp >> " + AUTH_KEY_FILE;
        if (logger.isLoggable(Level.FINER)) {
            logger.finer("mergeCommand = " + mergeCommand);
        }
        if (conn.exec(mergeCommand, new ByteArrayOutputStream()) != 0) {
            throw new IOException("Failed to propogate the public key " + pubKeyFile + " to " + host);
        }
        logger.info("Copied keyfile " + pubKeyFile + " to " + userName + "@" + host);
        // remove the public key file on remote host
        if (conn.exec("rm .ssh/key.tmp", new ByteArrayOutputStream()) != 0) {
            logger.warning("WARNING: Failed to remove the public key file key.tmp on remote host " + host);
        }
        if (logger.isLoggable(Level.FINER)) {
            logger.finer("Removed the temporary key file on remote host");
        }
        // Lets fix all the permissions
        // On MKS, chmod doesn't work as expected. StrictMode needs to be disabled
        // for connection to go through
        logger.info("Fixing file permissions for home(755), .ssh(700) and authorized_keys file(644)");
        sftp.chmod(".", 0755);
        sftp.chmod(SSH_DIR, 0700);
        sftp.chmod(SSH_DIR + AUTH_KEY_FILE, 0644);
        // release the connections
        sftp.close();
        conn.close();
    }
}
Also used : SCPClient(com.trilead.ssh2.SCPClient) Connection(com.trilead.ssh2.Connection) SFTPClient(org.glassfish.cluster.ssh.sftp.SFTPClient) IOException(java.io.IOException) File(java.io.File) ProcessManagerException(com.sun.enterprise.universal.process.ProcessManagerException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException)

Example 42 with Connection

use of org.ovirt.engine.sdk4.Connection in project MVPFrames by RockyQu.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    // 请求地址
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    log(requestStartMessage);
    // Content-Type
    if (hasRequestBody) {
        if (requestBody.contentType() != null) {
            log("Content-Type: " + requestBody.contentType());
        }
        if (requestBody.contentLength() != -1) {
            log("Content-Length: " + requestBody.contentLength());
        }
    }
    // 拼装请求参数
    Headers headers = request.headers();
    for (int i = 0, count = headers.size(); i < count; i++) {
        String name = headers.name(i);
        if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
            log(name + ": " + headers.value(i));
        }
    }
    // Request结束
    if (!hasRequestBody) {
        log("--> END " + request.method());
    } else if (bodyEncoded(request.headers())) {
        log("--> END " + request.method() + " (encoded body omitted)");
    } else {
        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        if (isPlaintext(buffer)) {
            log(buffer.readString(charset));
            log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        } else {
            log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
        }
    }
    // Response开始
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (", " + bodySize + " body") + ')');
    headers = response.headers();
    for (int i = 0, count = headers.size(); i < count; i++) {
        log(headers.name(i) + ": " + headers.value(i));
    }
    if (!HttpHeaders.hasBody(response)) {
        log("<-- END HTTP");
    } else if (bodyEncoded(response.headers())) {
        log("<-- END HTTP (encoded body omitted)");
    } else {
        BufferedSource source = responseBody.source();
        // Buffer the entire body.
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                log("Couldn't decode the response body; charset is likely malformed.");
                log("<-- END HTTP");
                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
            return response;
        }
        if (contentLength != 0) {
            log(buffer.clone().readString(charset));
        }
        log("<-- END HTTP (" + buffer.size() + "-byte body)");
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 43 with Connection

use of org.ovirt.engine.sdk4.Connection in project ttdj by soonphe.

the class HttpLoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol);
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log("--> END " + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            logger.log("");
            logger.log(buffer.readString(charset));
            logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        }
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpHeaders.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 44 with Connection

use of org.ovirt.engine.sdk4.Connection in project ovirt-engine-sdk-java by oVirt.

the class UpdateDataCenter method main.

public static void main(String[] args) throws Exception {
    // Create the connection to the server:
    Connection connection = connection().url("https://engine40.example.com/ovirt-engine/api").user("admin@internal").password("redhat123").trustStoreFile("truststore.jks").build();
    // Get the reference to the data centers service:
    DataCentersService dcsService = connection.systemService().dataCentersService();
    // Retrieve the description of the data center:
    DataCenter dc = dcsService.list().search("name=mydc").send().dataCenters().get(0);
    // In order to update the data center we need a reference to the service that manages it, then we can call the
    // "update" method passing the update:
    DataCenterService dcService = dcsService.dataCenterService(dc.id());
    dc = dcService.update().dataCenter(dataCenter().description("Updated description")).send().dataCenter();
    // Print the description of the result of the update:
    System.out.printf("%s: %s", dc.name(), dc.description());
    // Close the connection to the server:
    connection.close();
}
Also used : DataCentersService(org.ovirt.engine.sdk4.services.DataCentersService) DataCenter(org.ovirt.engine.sdk4.types.DataCenter) Connection(org.ovirt.engine.sdk4.Connection) DataCenterService(org.ovirt.engine.sdk4.services.DataCenterService)

Example 45 with Connection

use of org.ovirt.engine.sdk4.Connection in project ovirt-engine-sdk-java by oVirt.

the class UpdateFencingOptions method main.

public static void main(String[] args) throws Exception {
    // Create the connection to the server:
    Connection connection = connection().url("https://engine40.example.com/ovirt-engine/api").user("admin@internal").password("redhat123").trustStoreFile("truststore.jks").build();
    // The name and value of the option that we want to add or update:
    String name = "lanplus";
    String value = "1";
    // Get the reference to the service that manages the hosts:
    HostsService hostsService = connection.systemService().hostsService();
    // Find the host:
    Host host = hostsService.list().search("name=myhost").send().hosts().get(0);
    // Get the reference to the service that manages the fencing agents used by the host that we found in the
    // previous step:
    HostService hostService = hostsService.hostService(host.id());
    FenceAgentsService agentsService = hostService.fenceAgentsService();
    // The host may have multiple fencing agents, so we need to locate the first of type 'ipmilan':
    List<Agent> agents = agentsService.list().send().agents();
    Agent agent = null;
    for (Agent x : agents) {
        if ("ipmlan".equals(x.type())) {
            agent = x;
            break;
        }
    }
    // Get the options of the fencing agent. There may be no options, in that case we need to use an empty list.
    List<Option> original = agent.options();
    if (original == null) {
        original = Collections.emptyList();
    }
    // Create a list of modified options, containing all the original options except the one with the name we want
    // to modify, as we will add that with the right value later:
    List<Option> modified = new ArrayList<>();
    for (Option option : original) {
        if (!name.equals(option.name())) {
            modified.add(option);
        }
    }
    // Add the modified option to the list of modified options:
    Option option = option().name(name).value(value).build();
    modified.add(option);
    // Find the service that manages the fence agent:
    FenceAgentService agentService = agentsService.agentService(agent.id());
    // Send the update request containing the modified list of options:
    agentService.update().agent(agent().options(modified)).send();
    // Close the connection to the server:
    connection.close();
}
Also used : HostService(org.ovirt.engine.sdk4.services.HostService) Agent(org.ovirt.engine.sdk4.types.Agent) FenceAgentService(org.ovirt.engine.sdk4.services.FenceAgentService) Connection(org.ovirt.engine.sdk4.Connection) ArrayList(java.util.ArrayList) HostsService(org.ovirt.engine.sdk4.services.HostsService) Host(org.ovirt.engine.sdk4.types.Host) Option(org.ovirt.engine.sdk4.types.Option) FenceAgentsService(org.ovirt.engine.sdk4.services.FenceAgentsService)

Aggregations

Connection (org.ovirt.engine.sdk4.Connection)63 Connection (com.trilead.ssh2.Connection)52 IOException (java.io.IOException)41 VmsService (org.ovirt.engine.sdk4.services.VmsService)33 Session (com.trilead.ssh2.Session)32 Vm (org.ovirt.engine.sdk4.types.Vm)30 InputStream (java.io.InputStream)25 VmService (org.ovirt.engine.sdk4.services.VmService)18 SystemService (org.ovirt.engine.sdk4.services.SystemService)14 StorageDomainsService (org.ovirt.engine.sdk4.services.StorageDomainsService)12 StorageDomain (org.ovirt.engine.sdk4.types.StorageDomain)12 Connection (okhttp3.Connection)11 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)10 Request (okhttp3.Request)10 File (java.io.File)9 Response (okhttp3.Response)9 Connection (ch.ethz.ssh2.Connection)8 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 MediaType (okhttp3.MediaType)8 RequestBody (okhttp3.RequestBody)8