Search in sources :

Example 16 with Request

use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method loadPatch.

@Override
public Patch loadPatch(PatchDetailsRequest request) throws PatchException {
    File descriptor = new File(patchesDir, request.getPatchId() + ".patch");
    try {
        Patch patch = loadPatch(descriptor, true);
        if (patch == null) {
            return null;
        }
        Git repo = gitPatchRepository.findOrCreateMainGitRepository();
        List<DiffEntry> diff = null;
        if (request.isFiles() || request.isDiff()) {
            // fetch the information from git
            ObjectId commitId = repo.getRepository().resolve(patch.getManagedPatch().getCommitId());
            RevCommit commit = new RevWalk(repo.getRepository()).parseCommit(commitId);
            diff = gitPatchRepository.diff(repo, commit.getParent(0), commit);
        }
        if (request.isBundles()) {
        // it's already in PatchData
        }
        if (request.isFiles() && diff != null) {
            for (DiffEntry de : diff) {
                DiffEntry.ChangeType ct = de.getChangeType();
                String newPath = de.getNewPath();
                String oldPath = de.getOldPath();
                switch(ct) {
                    case ADD:
                        patch.getManagedPatch().getFilesAdded().add(newPath);
                        break;
                    case MODIFY:
                        patch.getManagedPatch().getFilesModified().add(newPath);
                        break;
                    case DELETE:
                        patch.getManagedPatch().getFilesRemoved().add(oldPath);
                        break;
                }
            }
        }
        if (request.isDiff() && diff != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DiffFormatter formatter = new DiffFormatter(baos);
            formatter.setContext(4);
            formatter.setRepository(repo.getRepository());
            for (DiffEntry de : diff) {
                formatter.format(de);
            }
            formatter.flush();
            patch.getManagedPatch().setUnifiedDiff(new String(baos.toByteArray(), "UTF-8"));
        }
        return patch;
    } catch (IOException | GitAPIException e) {
        throw new PatchException(e.getMessage(), e);
    }
}
Also used : ObjectId(org.eclipse.jgit.lib.ObjectId) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Git(org.eclipse.jgit.api.Git) PatchException(io.fabric8.patch.management.PatchException) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) ManagedPatch(io.fabric8.patch.management.ManagedPatch) Patch(io.fabric8.patch.management.Patch) DiffEntry(org.eclipse.jgit.diff.DiffEntry) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 17 with Request

use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.

the class TcpGatewayHandler method handle.

@Override
public void handle(final NetSocket socket) {
    NetClient client = null;
    List<String> paths = serviceMap.getPaths();
    TcpClientRequestFacade requestFacade = new TcpClientRequestFacade(socket);
    String path = pathLoadBalancer.choose(paths, requestFacade);
    if (path != null) {
        List<ServiceDetails> services = serviceMap.getServices(path);
        if (!services.isEmpty()) {
            ServiceDetails serviceDetails = serviceLoadBalancer.choose(services, requestFacade);
            if (serviceDetails != null) {
                List<String> urlStrings = serviceDetails.getServices();
                for (String urlString : urlStrings) {
                    if (Strings.notEmpty(urlString)) {
                        // lets create a client for this request...
                        try {
                            URI uri = new URI(urlString);
                            // URL url = new URL(urlString);
                            String urlProtocol = uri.getScheme();
                            if (Objects.equal(protocol, urlProtocol)) {
                                Handler<AsyncResult<NetSocket>> handler = new Handler<AsyncResult<NetSocket>>() {

                                    public void handle(final AsyncResult<NetSocket> asyncSocket) {
                                        socket.resume();
                                        NetSocket clientSocket = asyncSocket.result();
                                        Pump.createPump(clientSocket, socket).start();
                                        Pump.createPump(socket, clientSocket).start();
                                    }
                                };
                                client = createClient(socket, uri, handler);
                                break;
                            }
                        } catch (MalformedURLException e) {
                            LOG.warn("Failed to parse URL: " + urlString + ". " + e, e);
                        } catch (URISyntaxException e) {
                            LOG.warn("Failed to parse URI: " + urlString + ". " + e, e);
                        }
                    }
                }
            }
        }
    }
    if (client == null) {
        // fail to route
        LOG.info("No service available for protocol " + protocol + " for paths " + paths);
        socket.close();
    }
}
Also used : NetSocket(org.vertx.java.core.net.NetSocket) MalformedURLException(java.net.MalformedURLException) Handler(org.vertx.java.core.Handler) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) NetClient(org.vertx.java.core.net.NetClient) ServiceDetails(io.fabric8.gateway.ServiceDetails) AsyncResult(org.vertx.java.core.AsyncResult)

Example 18 with Request

use of io.fabric8.insight.metrics.model.Request in project fabric8 by jboss-fuse.

the class HttpGatewayHandler method handle.

@Override
public void handle(HttpServerRequest request) {
    long callStart = System.nanoTime();
    LOG.debug("Proxying request: {} {}", request.method(), request.uri());
    // lets map the request URI to map to the service URI and then the renaming URI
    // using mapping rules...
    Map<String, MappedServices> mappingRules = httpGateway.getMappedServices();
    try {
        if (isMappingIndexRequest(request)) {
            // lets return the JSON of all the results
            doReturnIndex(request, mappingRules);
        } else {
            doRouteRequest(mappingRules, request);
        }
        CallDetailRecord cdr = new CallDetailRecord(System.nanoTime() - callStart, null);
        httpGateway.addCallDetailRecord(cdr);
    } catch (Throwable e) {
        LOG.error("Caught: " + e, e);
        CallDetailRecord cdr = new CallDetailRecord(System.nanoTime() - callStart, new Date() + ":" + e.getMessage());
        httpGateway.addCallDetailRecord(cdr);
        request.response().setStatusCode(404);
        StringWriter buffer = new StringWriter();
        e.printStackTrace(new PrintWriter(buffer));
        request.response().setStatusMessage("Error: " + e + "\nStack Trace: " + buffer);
        request.response().close();
    }
}
Also used : StringWriter(java.io.StringWriter) Date(java.util.Date) CallDetailRecord(io.fabric8.gateway.CallDetailRecord) PrintWriter(java.io.PrintWriter)

Example 19 with Request

use of io.fabric8.insight.metrics.model.Request in project vertx-openshift-it by cescoffier.

the class Http2IT method testGRPC.

@Test
public void testGRPC() throws Exception {
    Assertions.assertThat(client).deployments().pods().isPodReadyForPeriod();
    String host = securedUrlForRoute(client.routes().withName("hello").get()).getHost();
    System.out.println("Host: " + host);
    System.out.println("Port: " + 443);
    ManagedChannel channel = VertxChannelBuilder.forAddress(vertx, host, 443).useSsl(options -> options.setSsl(true).setUseAlpn(true).setTrustAll(true)).build();
    GreeterGrpc.GreeterVertxStub stub = GreeterGrpc.newVertxStub(channel);
    HelloRequest request = HelloRequest.newBuilder().setName("OpenShift").build();
    AtomicReference<String> result = new AtomicReference<>();
    System.out.println("Sending request...");
    stub.sayHello(request, asyncResponse -> {
        System.out.println("Got result");
        if (asyncResponse.succeeded()) {
            System.out.println("Succeeded " + asyncResponse.result().getMessage());
            result.set(asyncResponse.result().getMessage());
        } else {
            asyncResponse.cause().printStackTrace();
        }
    });
    await().atMost(5, TimeUnit.MINUTES).untilAtomic(result, is(notNullValue()));
    assertThat(result.get()).contains("Hello OpenShift");
}
Also used : Awaitility.await(org.awaitility.Awaitility.await) ManagedChannel(io.grpc.ManagedChannel) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Vertx(io.vertx.core.Vertx) GreeterGrpc(io.grpc.examples.helloworld.GreeterGrpc) HelloRequest(io.grpc.examples.helloworld.HelloRequest) IOException(java.io.IOException) AtomicReference(java.util.concurrent.atomic.AtomicReference) VertxChannelBuilder(io.vertx.grpc.VertxChannelBuilder) Assertions(io.fabric8.kubernetes.assertions.Assertions) TimeUnit(java.util.concurrent.TimeUnit) Kube.securedUrlForRoute(io.vertx.it.openshift.utils.Kube.securedUrlForRoute) HttpVersion(io.vertx.core.http.HttpVersion) AbstractTestClass(io.vertx.it.openshift.utils.AbstractTestClass) Matchers.is(org.hamcrest.Matchers.is) HttpClientOptions(io.vertx.core.http.HttpClientOptions) org.junit(org.junit) Kube.urlForRoute(io.vertx.it.openshift.utils.Kube.urlForRoute) HelloRequest(io.grpc.examples.helloworld.HelloRequest) ManagedChannel(io.grpc.ManagedChannel) GreeterGrpc(io.grpc.examples.helloworld.GreeterGrpc) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 20 with Request

use of io.fabric8.insight.metrics.model.Request in project syndesis by syndesisio.

the class KubernetesSupport method watchLog.

/*
     * Feeds the controller of the given podName to the callback handler for processing.
     *
     * We do this instead of using the watchLog() feature of the k8s client lib because it really sucks due to:
     *  1. You can't configure the timestamps option or the sinceTime option.  Need to resume log downloads.
     *  2. It seems to need extra threads..
     *  3. It might be hiding some of the http failure conditions.
     *
     */
protected void watchLog(String podName, Consumer<InputStream> handler, String sinceTime, Executor executor) throws IOException {
    try {
        PodOperationsImpl pod = (PodOperationsImpl) client.pods().withName(podName);
        StringBuilder url = new StringBuilder().append(pod.getResourceUrl().toString()).append("/log?pretty=false&follow=true&timestamps=true");
        if (sinceTime != null) {
            url.append("&sinceTime=");
        }
        Request request = new Request.Builder().url(new URL(url.toString())).get().build();
        OkHttpClient clone = okHttpClient.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
        clone.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                LOG.info("Failure occurred getting  controller for pod: {},", podName, e);
                handler.accept(null);
            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                executor.execute(() -> {
                    try {
                        if (response.code() == 200) {
                            handler.accept(response.body().byteStream());
                        } else {
                            LOG.info("Failure occurred while processing controller for pod: {}, http status: {}, details: {}", podName, response.code(), response.body().string());
                            handler.accept(null);
                        }
                    } catch (IOException e) {
                        LOG.error("Unexpected Error", e);
                    }
                });
            }
        });
    } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") RuntimeException t) {
        throw new IOException("Unexpected Error", t);
    }
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) Callback(okhttp3.Callback) Request(okhttp3.Request) IOException(java.io.IOException) PodOperationsImpl(io.fabric8.kubernetes.client.dsl.internal.PodOperationsImpl) URL(java.net.URL)

Aggregations

IOException (java.io.IOException)17 HashMap (java.util.HashMap)9 File (java.io.File)8 Test (org.junit.Test)8 ByteArrayInputStream (java.io.ByteArrayInputStream)5 MalformedURLException (java.net.MalformedURLException)5 Map (java.util.Map)5 FabricService (io.fabric8.api.FabricService)4 RuntimeProperties (io.fabric8.api.RuntimeProperties)4 AbstractRuntimeProperties (io.fabric8.api.scr.AbstractRuntimeProperties)4 MavenResolver (io.fabric8.maven.MavenResolver)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Date (java.util.Date)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3 Container (io.fabric8.api.Container)3 NameValidator (io.fabric8.api.NameValidator)3 FileInputStream (java.io.FileInputStream)3