Search in sources :

Example 1 with Connection

use of ch.ethz.ssh2.Connection in project pinpoint by naver.

the class MethodInvocationHandlerInterceptor method createTrace.

/**
     * Creates the trace.
     *
     * @param target the target
     * @param args the args
     * @return the trace
     */
private Trace createTrace(final Object target, final Object[] args) {
    final Method methodInvoked = (Method) args[2];
    final StringBuilder methodNameBuilder = new StringBuilder();
    if (methodInvoked != null) {
        try {
            final Class<?> declaringClass = methodInvoked.getDeclaringClass();
            if (declaringClass != null) {
                methodNameBuilder.append(declaringClass.getCanonicalName());
                methodNameBuilder.append(".");
            }
            methodNameBuilder.append(methodInvoked.getName());
        } catch (final Exception exception) {
            logger.error("An error occurred while fetching method details", exception);
        }
    }
    final Trace trace = traceContext.newTraceObject();
    final Connection connection = RemotingContext.getConnection();
    final String remoteAddress = JbossUtility.fetchRemoteAddress(connection);
    if (trace.canSampled()) {
        final SpanRecorder recorder = trace.getSpanRecorder();
        recordRootSpan(recorder, methodNameBuilder.toString(), remoteAddress);
        if (isDebug) {
            logger.debug("Trace sampling is true, Recording trace. methodInvoked:{}, remoteAddress:{}", methodNameBuilder.toString(), remoteAddress);
        }
    } else {
        if (isDebug) {
            logger.debug("Trace sampling is false, Skip recording trace. methodInvoked:{}, remoteAddress:{}", methodNameBuilder.toString(), remoteAddress);
        }
    }
    return trace;
}
Also used : Trace(com.navercorp.pinpoint.bootstrap.context.Trace) SpanRecorder(com.navercorp.pinpoint.bootstrap.context.SpanRecorder) Connection(org.jboss.remoting3.Connection) Method(java.lang.reflect.Method)

Example 2 with Connection

use of ch.ethz.ssh2.Connection in project Fast-Android-Networking by amitshekhariitbhu.

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;
    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("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
            }
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.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";
    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 (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }
            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) IOException(java.io.IOException) EOFException(java.io.EOFException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 3 with Connection

use of ch.ethz.ssh2.Connection in project okhttp by square.

the class RetryAndFollowUpInterceptor method followUpRequest.

/**
   * Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
   * either add authentication headers, follow redirects or handle a client request timeout. If a
   * follow-up is either unnecessary or not applicable, this returns null.
   */
private Request followUpRequest(Response userResponse) throws IOException {
    if (userResponse == null)
        throw new IllegalStateException();
    Connection connection = streamAllocation.connection();
    Route route = connection != null ? connection.route() : null;
    int responseCode = userResponse.code();
    final String method = userResponse.request().method();
    switch(responseCode) {
        case HTTP_PROXY_AUTH:
            Proxy selectedProxy = route != null ? route.proxy() : client.proxy();
            if (selectedProxy.type() != Proxy.Type.HTTP) {
                throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
            }
            return client.proxyAuthenticator().authenticate(route, userResponse);
        case HTTP_UNAUTHORIZED:
            return client.authenticator().authenticate(route, userResponse);
        case HTTP_PERM_REDIRECT:
        case HTTP_TEMP_REDIRECT:
            // or HEAD, the user agent MUST NOT automatically redirect the request"
            if (!method.equals("GET") && !method.equals("HEAD")) {
                return null;
            }
        // fall-through
        case HTTP_MULT_CHOICE:
        case HTTP_MOVED_PERM:
        case HTTP_MOVED_TEMP:
        case HTTP_SEE_OTHER:
            // Does the client allow redirects?
            if (!client.followRedirects())
                return null;
            String location = userResponse.header("Location");
            if (location == null)
                return null;
            HttpUrl url = userResponse.request().url().resolve(location);
            // Don't follow redirects to unsupported protocols.
            if (url == null)
                return null;
            // If configured, don't follow redirects between SSL and non-SSL.
            boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
            if (!sameScheme && !client.followSslRedirects())
                return null;
            // Most redirects don't include a request body.
            Request.Builder requestBuilder = userResponse.request().newBuilder();
            if (HttpMethod.permitsRequestBody(method)) {
                final boolean maintainBody = HttpMethod.redirectsWithBody(method);
                if (HttpMethod.redirectsToGet(method)) {
                    requestBuilder.method("GET", null);
                } else {
                    RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
                    requestBuilder.method(method, requestBody);
                }
                if (!maintainBody) {
                    requestBuilder.removeHeader("Transfer-Encoding");
                    requestBuilder.removeHeader("Content-Length");
                    requestBuilder.removeHeader("Content-Type");
                }
            }
            // way to retain them.
            if (!sameConnection(userResponse, url)) {
                requestBuilder.removeHeader("Authorization");
            }
            return requestBuilder.url(url).build();
        case HTTP_CLIENT_TIMEOUT:
            // repeat the request (even non-idempotent ones.)
            if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
                return null;
            }
            return userResponse.request();
        default:
            return null;
    }
}
Also used : ProtocolException(java.net.ProtocolException) Connection(okhttp3.Connection) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) Proxy(java.net.Proxy) Route(okhttp3.Route) RequestBody(okhttp3.RequestBody)

Example 4 with Connection

use of ch.ethz.ssh2.Connection in project CloudStack-archive by CloudStack-extras.

the class StressTestDirectAttach method sshTest.

private static String sshTest(String host, String password) {
    int i = 0;
    if (host == null) {
        s_logger.info("Did not receive a host back from test, ignoring ssh test");
        return null;
    }
    if (password == null) {
        s_logger.info("Did not receive a password back from test, ignoring ssh test");
        return null;
    }
    // We will retry 5 times before quitting
    String result = null;
    int retry = 0;
    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt. Account is " + _account.get());
                Thread.sleep(120000);
            }
            s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry + ". Account is " + _account.get());
            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);
            s_logger.info("User + " + _account.get() + " ssHed successfully into linux host " + host);
            boolean isAuthenticated = conn.authenticateWithPassword("root", password);
            if (isAuthenticated == false) {
                s_logger.info("Authentication failed for root with password" + password);
                return "Authentication failed";
            }
            boolean success = false;
            String linuxCommand = null;
            if (i % 10 == 0)
                linuxCommand = "rm -rf *; wget http://192.168.1.250/dump.bin && ls -al dump.bin";
            else
                linuxCommand = "wget http://192.168.1.250/dump.bin && ls -al dump.bin";
            Session sess = conn.openSession();
            s_logger.info("User " + _account.get() + " executing : " + linuxCommand);
            sess.execCommand(linuxCommand);
            InputStream stdout = sess.getStdout();
            InputStream stderr = sess.getStderr();
            byte[] buffer = new byte[8192];
            while (true) {
                if ((stdout.available() == 0) && (stderr.available() == 0)) {
                    int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 120000);
                    if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                        s_logger.info("Timeout while waiting for data from peer.");
                        return null;
                    }
                    if ((conditions & ChannelCondition.EOF) != 0) {
                        if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                            break;
                        }
                    }
                }
                while (stdout.available() > 0) {
                    success = true;
                    int len = stdout.read(buffer);
                    if (// this check is somewhat paranoid
                    len > 0)
                        s_logger.info(new String(buffer, 0, len));
                }
                while (stderr.available() > 0) {
                    /* int len = */
                    stderr.read(buffer);
                }
            }
            sess.close();
            conn.close();
            if (!success) {
                retry++;
                if (retry == MAX_RETRY_LINUX) {
                    result = "SSH Linux Network test fail";
                }
            }
            return result;
        } catch (Exception e) {
            retry++;
            s_logger.error("SSH Linux Network test fail with error");
            if (retry == MAX_RETRY_LINUX) {
                return "SSH Linux Network test fail with error " + e.getMessage();
            }
        }
        i++;
    }
}
Also used : InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Session(com.trilead.ssh2.Session)

Example 5 with Connection

use of ch.ethz.ssh2.Connection in project CloudStack-archive by CloudStack-extras.

the class TestClient method sshTest.

private static String sshTest(String host) {
    if (host == null) {
        s_logger.info("Did not receive a host back from test, ignoring ssh test");
        return null;
    }
    // We will retry 5 times before quitting
    int retry = 0;
    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt");
                Thread.sleep(120000);
            }
            s_logger.info("Attempting to SSH into linux host " + host + " with retry attempt: " + retry);
            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);
            s_logger.info("SSHed successfully into linux host " + host);
            boolean isAuthenticated = conn.authenticateWithPassword("root", "password");
            if (isAuthenticated == false) {
                return "Authentication failed";
            }
            boolean success = false;
            Session sess = conn.openSession();
            s_logger.info("Executing : wget http://172.16.0.220/dump.bin");
            sess.execCommand("wget http://172.16.0.220/dump.bin && ls -al dump.bin");
            InputStream stdout = sess.getStdout();
            InputStream stderr = sess.getStderr();
            byte[] buffer = new byte[8192];
            while (true) {
                if ((stdout.available() == 0) && (stderr.available() == 0)) {
                    int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 120000);
                    if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                        s_logger.info("Timeout while waiting for data from peer.");
                        return null;
                    }
                    if ((conditions & ChannelCondition.EOF) != 0) {
                        if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                            break;
                        }
                    }
                }
                while (stdout.available() > 0) {
                    success = true;
                    int len = stdout.read(buffer);
                    if (// this check is somewhat paranoid
                    len > 0)
                        s_logger.info(new String(buffer, 0, len));
                }
                while (stderr.available() > 0) {
                    int len = stderr.read(buffer);
                }
            }
            sess.close();
            conn.close();
            if (success) {
                return null;
            } else {
                retry++;
                if (retry == MAX_RETRY_LINUX) {
                    return "SSH Linux Network test fail";
                }
            }
        } catch (Exception e) {
            retry++;
            if (retry == MAX_RETRY_LINUX) {
                return "SSH Linux Network test fail with error " + e.getMessage();
            }
        }
    }
}
Also used : InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) Session(com.trilead.ssh2.Session)

Aggregations

Connection (com.trilead.ssh2.Connection)36 Session (com.trilead.ssh2.Session)31 IOException (java.io.IOException)23 InputStream (java.io.InputStream)20 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 Connection (org.jboss.remoting3.Connection)7 SCPClient (com.trilead.ssh2.SCPClient)6 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 Principal (java.security.Principal)4 Connection (okhttp3.Connection)4 Request (okhttp3.Request)4 RequestBody (okhttp3.RequestBody)4 SecurityContext (org.jboss.security.SecurityContext)4 SecurityIdentity (org.wildfly.security.auth.server.SecurityIdentity)4 BufferedReader (java.io.BufferedReader)3 InputStreamReader (java.io.InputStreamReader)3 Charset (java.nio.charset.Charset)3 Headers (okhttp3.Headers)3