Search in sources :

Example 1 with SpanAdapter

use of org.commonjava.o11yphant.trace.spi.adapter.SpanAdapter in project indy by Commonjava.

the class TransferStreamingOutput method write.

@Override
@Measure
public void write(final OutputStream out) throws IOException, WebApplicationException {
    start = System.nanoTime();
    try {
        cout = new CountingOutputStream(out);
        IOUtils.copy(stream, cout);
        kbCount = (double) cout.getByteCount() / 1024;
        Logger logger = LoggerFactory.getLogger(getClass());
        logger.trace("Wrote: {} bytes", kbCount);
        long end = System.nanoTime();
        RequestContextHelper.setContext(RAW_IO_WRITE_NANOS, end - start);
        double elapsed = (end - start) / NANOS_PER_SEC;
        TraceManager.getActiveSpan().ifPresent(s -> s.setInProgressField(LATENCY_TIMER_PAUSE_KEY, s.getInProgressField(LATENCY_TIMER_PAUSE_KEY, 0.0) + (end - start)));
        String rateName = getName(metricsConfig.getNodePrefix(), TRANSFER_METRIC_NAME + WRITE_SPEED, getDefaultName(TransferStreamingOutput.class, WRITE_SPEED), METER);
        Histogram rateGram = metricsManager.getHistogram(rateName);
        writeSpeed = Math.round(kbCount / elapsed);
        logger.info("measured speed: {} kb/s to metric: {}", (writeSpeed / 1024), rateName);
        rateGram.update(writeSpeed);
        String sizeName = getName(metricsConfig.getNodePrefix(), TRANSFER_METRIC_NAME + WRITE_SIZE, getDefaultName(TransferStreamingOutput.class, WRITE_SIZE), METER);
        logger.info("measured size: {} kb to metric: {}", (kbCount / 1024), sizeName);
        Histogram sizeGram = metricsManager.getHistogram(sizeName);
        sizeGram.update(Math.round(kbCount));
    } finally {
        IOUtils.closeQuietly(stream);
        rootSpan.ifPresent(SpanAdapter::close);
    }
}
Also used : CountingOutputStream(org.apache.commons.io.output.CountingOutputStream) Histogram(org.commonjava.o11yphant.metrics.api.Histogram) SpanAdapter(org.commonjava.o11yphant.trace.spi.adapter.SpanAdapter) Logger(org.slf4j.Logger) Measure(org.commonjava.o11yphant.metrics.annotation.Measure)

Example 2 with SpanAdapter

use of org.commonjava.o11yphant.trace.spi.adapter.SpanAdapter in project indy by Commonjava.

the class ProxyResponseWriter method doHandleEvent.

private void doHandleEvent(final ConduitStreamSinkChannel sinkChannel) {
    if (directed) {
        return;
    }
    ProxyMeter meter = new ProxyMeter(httpRequest.getRequestLine().getMethod(), httpRequest.getRequestLine().toString(), startNanos, sliMetricSet, restLogger, peerAddress);
    try {
        HttpConduitWrapper http = new HttpConduitWrapper(sinkChannel, httpRequest, contentController, cacheProvider);
        if (httpRequest == null) {
            if (error != null) {
                logger.debug("Handling error from request reader: " + error.getMessage(), error);
                handleError(error, http);
            } else {
                logger.debug("Invalid state (no error or request) from request reader. Sending 400.");
                try {
                    http.writeStatus(ApplicationStatus.BAD_REQUEST);
                } catch (final IOException e) {
                    logger.error("Failed to write BAD REQUEST for missing HTTP first-line to response channel.", e);
                }
            }
            return;
        }
        restLogger.info("SERVE {} (from: {})", httpRequest.getRequestLine(), peerAddress);
        // TODO: Can we handle this?
        final String oldThreadName = Thread.currentThread().getName();
        Thread.currentThread().setName("PROXY-" + httpRequest.getRequestLine().toString());
        sinkChannel.getCloseSetter().set((c) -> {
            logger.trace("Sink channel closing.");
            Thread.currentThread().setName(oldThreadName);
            if (sslTunnel != null) {
                logger.trace("Close ssl tunnel");
                sslTunnel.close();
            }
        });
        logger.debug("\n\n\n>>>>>>> Handle write\n\n\n");
        if (error == null) {
            ProxyResponseHelper proxyResponseHelper = new ProxyResponseHelper(httpRequest, config, contentController, repoCreator, storeManager, metricsConfig, metricManager, cls);
            try {
                if (repoCreator == null) {
                    throw new IndyDataException("No valid instance of ProxyRepositoryCreator");
                }
                final UserPass proxyUserPass = parse(ApplicationHeader.proxy_authorization, httpRequest, null);
                logger.info("Using proxy authentication: {}", proxyUserPass);
                mdcManager.putExtraHeaders(httpRequest);
                // FIXME: We cannot trace through this interface currently!
                mdcManager.putExternalID(proxyUserPass == null ? null : proxyUserPass.getUser());
                logger.debug("Proxy UserPass: {}\nConfig secured? {}\nConfig tracking type: {}", proxyUserPass, config.isSecured(), config.getTrackingType());
                if (proxyUserPass == null && (config.isSecured() || TrackingType.ALWAYS == config.getTrackingType())) {
                    String realmInfo = String.format(PROXY_AUTHENTICATE_FORMAT, config.getProxyRealm());
                    logger.info("Not authenticated to proxy. Sending response: {} / {}: {}", PROXY_AUTHENTICATION_REQUIRED, proxy_authenticate, realmInfo);
                    http.writeStatus(PROXY_AUTHENTICATION_REQUIRED);
                    http.writeHeader(proxy_authenticate, realmInfo);
                } else {
                    RequestLine requestLine = httpRequest.getRequestLine();
                    String method = requestLine.getMethod().toUpperCase();
                    String trackingId = null;
                    boolean authenticated = true;
                    if (proxyUserPass != null) {
                        TrackingKey trackingKey = proxyResponseHelper.getTrackingKey(proxyUserPass);
                        if (trackingKey != null) {
                            trackingId = trackingKey.getId();
                            RequestContextHelper.setContext(RequestContextHelper.CONTENT_TRACKING_ID, trackingId);
                        }
                        String authCacheKey = generateAuthCacheKey(proxyUserPass);
                        Boolean isAuthToken = proxyAuthCache.get(authCacheKey);
                        if (Boolean.TRUE.equals(isAuthToken)) {
                            authenticated = true;
                            logger.debug("Found auth key in cache");
                        } else {
                            logger.debug("Passing BASIC authentication credentials to Keycloak bearer-token translation authenticator");
                            authenticated = proxyAuthenticator.authenticate(proxyUserPass, http);
                            if (authenticated) {
                                proxyAuthCache.put(authCacheKey, Boolean.TRUE, config.getAuthCacheExpirationHours(), TimeUnit.HOURS);
                            }
                        }
                        logger.debug("Authentication done, result: {}", authenticated);
                    }
                    if (authenticated) {
                        switch(method) {
                            case GET_METHOD:
                            case HEAD_METHOD:
                                {
                                    final URL url = new URL(requestLine.getUri());
                                    logger.debug("getArtifactStore starts, trackingId: {}, url: {}", trackingId, url);
                                    ArtifactStore store = proxyResponseHelper.getArtifactStore(trackingId, url);
                                    proxyResponseHelper.transfer(http, store, url.getPath(), GET_METHOD.equals(method), proxyUserPass, meter);
                                    break;
                                }
                            case OPTIONS_METHOD:
                                {
                                    http.writeStatus(ApplicationStatus.OK);
                                    http.writeHeader(ApplicationHeader.allow, ALLOW_HEADER_VALUE);
                                    break;
                                }
                            case CONNECT_METHOD:
                                {
                                    if (!config.isMITMEnabled()) {
                                        logger.debug("CONNECT method not supported unless MITM-proxying is enabled.");
                                        http.writeStatus(ApplicationStatus.BAD_REQUEST);
                                        break;
                                    }
                                    // e.g, github.com:443
                                    String uri = requestLine.getUri();
                                    logger.debug("Get CONNECT request, uri: {}", uri);
                                    String[] toks = uri.split(":");
                                    String host = toks[0];
                                    int port = parseInt(toks[1]);
                                    directed = true;
                                    // After this, the proxy simply opens a plain socket to the target server and relays
                                    // everything between the initial client and the target server (including the TLS handshake).
                                    SocketChannel socketChannel;
                                    ProxyMITMSSLServer svr = new ProxyMITMSSLServer(host, port, trackingId, proxyUserPass, proxyResponseHelper, contentController, cacheProvider, config, meter);
                                    tunnelAndMITMExecutor.submit(svr);
                                    socketChannel = svr.getSocketChannel();
                                    if (socketChannel == null) {
                                        logger.debug("Failed to get MITM socket channel");
                                        http.writeStatus(ApplicationStatus.SERVER_ERROR);
                                        svr.stop();
                                        break;
                                    }
                                    sslTunnel = new ProxySSLTunnel(sinkChannel, socketChannel, config);
                                    tunnelAndMITMExecutor.submit(sslTunnel);
                                    // client input will be directed to target socket
                                    proxyRequestReader.setProxySSLTunnel(sslTunnel);
                                    // When all is ready, send the 200 to client. Client send the SSL handshake to reader,
                                    // reader direct it to tunnel to MITM. MITM finish the handshake and read the request data,
                                    // retrieve remote content and send back to tunnel to client.
                                    http.writeStatus(ApplicationStatus.OK);
                                    http.writeHeader("Status", "200 OK\n");
                                    break;
                                }
                            default:
                                {
                                    http.writeStatus(ApplicationStatus.METHOD_NOT_ALLOWED);
                                }
                        }
                    }
                }
                logger.debug("Response complete.");
            } catch (final Throwable e) {
                error = e;
            } finally {
                mdcManager.clear();
            }
        }
        if (error != null) {
            handleError(error, http);
        }
        try {
            if (directed) {
                // do not close sink channel
                ;
            } else {
                http.close();
            }
        } catch (final IOException e) {
            logger.error("Failed to shutdown response", e);
        }
    } finally {
        meter.reportResponseSummary();
        span.ifPresent(SpanAdapter::close);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) HttpConduitWrapper(org.commonjava.indy.httprox.util.HttpConduitWrapper) UserPass(org.commonjava.indy.subsys.http.util.UserPass) IOException(java.io.IOException) URL(java.net.URL) TrackingKey(org.commonjava.indy.folo.model.TrackingKey) IndyDataException(org.commonjava.indy.data.IndyDataException) RequestLine(org.apache.http.RequestLine) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) ProxyMeter(org.commonjava.indy.httprox.util.ProxyMeter) ProxyResponseHelper(org.commonjava.indy.httprox.util.ProxyResponseHelper) SpanAdapter(org.commonjava.o11yphant.trace.spi.adapter.SpanAdapter)

Example 3 with SpanAdapter

use of org.commonjava.o11yphant.trace.spi.adapter.SpanAdapter in project indy by Commonjava.

the class ProxyRequestReader method handleEvent.

// TODO: May need to tune this to preserve request body.
// TODO: NONE of the request headers (except authorization) are passed through!
@Override
public void handleEvent(final ConduitStreamSourceChannel sourceChannel) {
    boolean sendResponse = false;
    try {
        final int read = doRead(sourceChannel);
        if (read <= 0) {
            logger.debug("Reads: {} ", read);
            return;
        }
        byte[] bytes = bReq.toByteArray();
        if (sslTunnel != null) {
            logger.debug("Send to ssl tunnel, {}, bytes:\n\n {}\n", new String(bytes), Hex.encodeHexString(bytes));
            directTo(sslTunnel);
            return;
        }
        logger.debug("Request in progress is:\n\n{}", new String(bytes));
        if (headDone) {
            logger.debug("Request done. parsing.");
            MessageConstraints mc = MessageConstraints.DEFAULT;
            SessionInputBufferImpl inbuf = new SessionInputBufferImpl(new HttpTransportMetricsImpl(), 1024);
            HttpRequestFactory requestFactory = new DefaultHttpRequestFactory();
            LineParser lp = new BasicLineParser();
            DefaultHttpRequestParser requestParser = new DefaultHttpRequestParser(inbuf, lp, requestFactory, mc);
            inbuf.bind(new ByteArrayInputStream(bytes));
            try {
                logger.debug("Passing parsed http request off to response writer.");
                HttpRequest request = requestParser.parse();
                Optional<SpanAdapter> span;
                if (traceManager.isPresent())
                    span = traceManager.get().startServiceRootSpan("httprox-get", contextExtractor(request));
                else
                    span = Optional.empty();
                logger.debug("Request contains {} header: '{}'", ApplicationHeader.authorization.key(), request.getHeaders(ApplicationHeader.authorization.key()));
                writer.setHttpRequest(request);
                writer.setSpan(span);
                sendResponse = true;
            } catch (ConnectionClosedException e) {
                logger.warn("Client closed connection. Aborting proxy request.");
                sendResponse = false;
                sourceChannel.shutdownReads();
            } catch (HttpException e) {
                logger.error("Failed to parse http request: " + e.getMessage(), e);
                writer.setError(e);
            }
        } else {
            logger.debug("Request not finished. Pausing until more reads are available.");
            sourceChannel.resumeReads();
        }
    } catch (final IOException e) {
        writer.setError(e);
        sendResponse = true;
    }
    if (sendResponse) {
        sinkChannel.resumeWrites();
    }
}
Also used : HttpRequest(org.apache.http.HttpRequest) DefaultHttpRequestFactory(org.apache.http.impl.DefaultHttpRequestFactory) HttpRequestFactory(org.apache.http.HttpRequestFactory) ConnectionClosedException(org.apache.http.ConnectionClosedException) BasicLineParser(org.apache.http.message.BasicLineParser) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) DefaultHttpRequestFactory(org.apache.http.impl.DefaultHttpRequestFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) MessageConstraints(org.apache.http.config.MessageConstraints) HttpTransportMetricsImpl(org.apache.http.impl.io.HttpTransportMetricsImpl) BasicLineParser(org.apache.http.message.BasicLineParser) LineParser(org.apache.http.message.LineParser) SpanAdapter(org.commonjava.o11yphant.trace.spi.adapter.SpanAdapter) HttpException(org.apache.http.HttpException) SessionInputBufferImpl(org.apache.http.impl.io.SessionInputBufferImpl) DefaultHttpRequestParser(org.apache.http.impl.io.DefaultHttpRequestParser)

Aggregations

SpanAdapter (org.commonjava.o11yphant.trace.spi.adapter.SpanAdapter)3 IOException (java.io.IOException)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InterruptedIOException (java.io.InterruptedIOException)1 URL (java.net.URL)1 SocketChannel (java.nio.channels.SocketChannel)1 CountingOutputStream (org.apache.commons.io.output.CountingOutputStream)1 ConnectionClosedException (org.apache.http.ConnectionClosedException)1 HttpException (org.apache.http.HttpException)1 HttpRequest (org.apache.http.HttpRequest)1 HttpRequestFactory (org.apache.http.HttpRequestFactory)1 RequestLine (org.apache.http.RequestLine)1 MessageConstraints (org.apache.http.config.MessageConstraints)1 DefaultHttpRequestFactory (org.apache.http.impl.DefaultHttpRequestFactory)1 DefaultHttpRequestParser (org.apache.http.impl.io.DefaultHttpRequestParser)1 HttpTransportMetricsImpl (org.apache.http.impl.io.HttpTransportMetricsImpl)1 SessionInputBufferImpl (org.apache.http.impl.io.SessionInputBufferImpl)1 BasicLineParser (org.apache.http.message.BasicLineParser)1 LineParser (org.apache.http.message.LineParser)1 IndyDataException (org.commonjava.indy.data.IndyDataException)1