@Override protected void channelRead0(ChannelHandlerContext ctx, Routed routed) throws Exception { if (localJobManagerAddressFuture.isCompleted()) { if (localJobManagerAddress == null) { localJobManagerAddress = Await.result(localJobManagerAddressFuture, timeout); } Option<Tuple2<ActorGateway, Integer>> jobManager = retriever.getJobManagerGatewayAndWebPort(); if (jobManager.isDefined()) { Tuple2<ActorGateway, Integer> gatewayPort = jobManager.get(); String redirectAddress = HandlerRedirectUtils.getRedirectAddress(localJobManagerAddress, gatewayPort); if (redirectAddress != null) { HttpResponse redirect = HandlerRedirectUtils.getRedirectResponse(redirectAddress, routed.path()); KeepAliveWrite.flush(ctx, routed.request(), redirect); } else { respondAsLeader(ctx, routed, gatewayPort._1()); } } else { KeepAliveWrite.flush(ctx, routed.request(), HandlerRedirectUtils.getUnavailableResponse()); } } else { KeepAliveWrite.flush(ctx, routed.request(), HandlerRedirectUtils.getUnavailableResponse()); } }
private void respondAsLeader(ChannelHandlerContext ctx, Routed routed, ActorGateway jobManager) { DefaultFullHttpResponse response; try { // we only pass the first element in the list to the handlers. Map<String, String> queryParams = new HashMap<>(); for (String key : routed.queryParams().keySet()) { queryParams.put(key, routed.queryParam(key)); } InetSocketAddress address = (InetSocketAddress) ctx.channel().localAddress(); queryParams.put(WEB_MONITOR_ADDRESS_KEY, address.getHostName() + ":" + address.getPort()); String result = handler.handleRequest(routed.pathParams(), queryParams, jobManager); byte[] bytes = result.getBytes(ENCODING); response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(bytes)); response.headers().set(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*"); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json"); } catch (NotFoundException e) { // this should result in a 404 error code (not found) ByteBuf message = e.getMessage() == null ? Unpooled.buffer(0) : Unpooled.wrappedBuffer(e.getMessage().getBytes(ENCODING)); response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, message); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); LOG.warn("Error while handling request", e); } catch (Exception e) { byte[] bytes = ExceptionUtils.stringifyException(e).getBytes(ENCODING); response = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR, Unpooled.wrappedBuffer(bytes)); response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain"); LOG.warn("Error while handling request", e); } response.headers().set(HttpHeaders.Names.CONTENT_ENCODING, "utf-8"); response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes()); KeepAliveWrite.flush(ctx, routed.request(), response); }