Skip to content

Commit

Permalink
https://github.com/apache/camel-k-runtime/issues/326
Browse files Browse the repository at this point in the history
  • Loading branch information
lburgazzoli committed May 15, 2020
1 parent d46694a commit 698a880
Show file tree
Hide file tree
Showing 6 changed files with 563 additions and 382 deletions.
5 changes: 0 additions & 5 deletions camel-knative/camel-knative-http/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,6 @@
<artifactId>camel-log</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-undertow</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-http</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import io.vertx.core.http.HttpServerRequest;
import org.apache.camel.AsyncCallback;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.component.knative.spi.CloudEvent;
import org.apache.camel.component.knative.spi.Knative;
Expand Down Expand Up @@ -101,10 +102,37 @@ public static Processor withoutCloudEventHeaders(Processor delegate, CloudEvent
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
return processor.process(exchange, doneSync -> {
final Message message = exchange.getMessage();

// remove CloudEvent headers
for (CloudEvent.Attribute attr : ce.attributes()) {
exchange.getMessage().removeHeader(attr.http());
message.removeHeader(attr.http());
}

callback.done(doneSync);
});
}
};
}

/**
* Remap camel headers to cloud event http headers.
*/
public static Processor remalCloudEventHeaders(Processor delegate, CloudEvent ce) {
return new DelegateAsyncProcessor(delegate) {
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
return processor.process(exchange, doneSync -> {
final Message message = exchange.getMessage();

// remap CloudEvent camel --> http
for (CloudEvent.Attribute attr : ce.attributes()) {
Object value = message.getHeader(attr.id());
if (value != null) {
message.setHeader(attr.http(), value);
}
}

callback.done(doneSync);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
public class KnativeHttpTransport extends ServiceSupport implements CamelContextAware, KnativeTransport {
public static final int DEFAULT_PORT = 8080;
public static final String DEFAULT_PATH = "/";

private PlatformHttp platformHttp;
private WebClientOptions vertxHttpClientOptions;
private CamelContext camelContext;
Expand Down Expand Up @@ -96,10 +96,12 @@ public Producer createProducer(Endpoint endpoint, KnativeTransportConfiguration

@Override
public Consumer createConsumer(Endpoint endpoint, KnativeTransportConfiguration config, KnativeEnvironment.KnativeServiceDefinition service, Processor processor) {
Processor next = processor;
Processor next = KnativeHttpSupport.remalCloudEventHeaders(processor, config.getCloudEvent());

if (config.isRemoveCloudEventHeadersInReply()) {
next = KnativeHttpSupport.withoutCloudEventHeaders(processor, config.getCloudEvent());
next = KnativeHttpSupport.withoutCloudEventHeaders(next, config.getCloudEvent());
}

return new KnativeHttpConsumer(this, endpoint, service, this.platformHttp, next);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.camel.component.knative.http;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import org.apache.camel.CamelContext;
import org.apache.camel.component.platform.http.PlatformHttpConstants;
import org.apache.camel.support.service.ServiceSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class KnativeHttpServer extends ServiceSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(KnativeHttpServer.class);

private final CamelContext context;
private final String host;
private final int port;
private final String path;

private Vertx vertx;
private Router router;
private ExecutorService executor;
private HttpServer server;
private BlockingQueue<HttpServerRequest> requests;
private Handler<RoutingContext> handler;

public KnativeHttpServer(CamelContext context, int port) {
this(context, "localhost", port, "/", null);
}

public KnativeHttpServer(CamelContext context, int port, Handler<RoutingContext> handler) {
this(context, "localhost", port, "/", handler);
}

public KnativeHttpServer(CamelContext context, String host, int port, String path) {
this(context, host, port, path, null);
}

public KnativeHttpServer(CamelContext context, String host, int port, String path, Handler<RoutingContext> handler) {
this.context = context;
this.host = host;
this.port = port;
this.path = path;
this.requests = new LinkedBlockingQueue<>();
this.handler = handler != null
? handler
: event -> {
event.response().setStatusCode(200);
event.response().end();
};
}

public HttpServerRequest poll(int timeout, TimeUnit unit) throws InterruptedException {
return requests.poll(timeout, unit);
}

@Override
protected void doStart() throws Exception {
this.executor = context.getExecutorServiceManager().newSingleThreadExecutor(this, "knative-http-server");
this.vertx = Vertx.vertx();
this.server = vertx.createHttpServer();
this.router = Router.router(vertx);
this.router.route(path)
.handler(event -> {
event.request().resume();
BodyHandler.create().handle(event);
})
.handler(event -> {
this.requests.offer(event.request());
event.next();
})
.handler(handler);

CompletableFuture.runAsync(
() -> {
CountDownLatch latch = new CountDownLatch(1);
server.requestHandler(router).listen(port, host, result -> {
try {
if (result.failed()) {
LOGGER.warn("Failed to start Vert.x HttpServer on {}:{}, reason: {}",
host,
port,
result.cause().getMessage()
);

throw new RuntimeException(result.cause());
}

LOGGER.info("Vert.x HttpServer started on {}:{}", host, port);
} finally {
latch.countDown();
}
});

try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
},
executor
).toCompletableFuture().join();
}

@Override
protected void doStop() throws Exception {
try {
if (server != null) {
CompletableFuture.runAsync(
() -> {
CountDownLatch latch = new CountDownLatch(1);

// remove the platform-http component
context.removeComponent(PlatformHttpConstants.PLATFORM_HTTP_COMPONENT_NAME);

server.close(result -> {
try {
if (result.failed()) {
LOGGER.warn("Failed to close Vert.x HttpServer reason: {}",
result.cause().getMessage()
);

throw new RuntimeException(result.cause());
}

LOGGER.info("Vert.x HttpServer stopped");
} finally {
latch.countDown();
}
});

try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
},
executor
).toCompletableFuture().join();
}
} finally {
this.server = null;
}

if (vertx != null) {
Future<?> future = executor.submit(
() -> {
CountDownLatch latch = new CountDownLatch(1);

vertx.close(result -> {
try {
if (result.failed()) {
LOGGER.warn("Failed to close Vert.x reason: {}",
result.cause().getMessage()
);

throw new RuntimeException(result.cause());
}

LOGGER.info("Vert.x stopped");
} finally {
latch.countDown();
}
});

try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
);

try {
future.get();
} finally {
vertx = null;
}
}

if (executor != null) {
context.getExecutorServiceManager().shutdown(executor);
executor = null;
}
}
}
Loading

0 comments on commit 698a880

Please sign in to comment.