You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by se...@apache.org on 2015/07/21 21:10:49 UTC
[10/26] flink git commit: [FLINK-2358] [dashboard] Add server for
static dashboard files (HTML, JS, CSS, ...)
[FLINK-2358] [dashboard] Add server for static dashboard files (HTML, JS, CSS, ...)
Project: http://git-wip-us.apache.org/repos/asf/flink/repo
Commit: http://git-wip-us.apache.org/repos/asf/flink/commit/e86f4517
Tree: http://git-wip-us.apache.org/repos/asf/flink/tree/e86f4517
Diff: http://git-wip-us.apache.org/repos/asf/flink/diff/e86f4517
Branch: refs/heads/master
Commit: e86f451705315ea7d1ed4d3821e08dd2225d84c0
Parents: 44ee1c1
Author: Stephan Ewen <se...@apache.org>
Authored: Mon Jul 20 22:38:15 2015 +0200
Committer: Stephan Ewen <se...@apache.org>
Committed: Tue Jul 21 17:58:14 2015 +0200
----------------------------------------------------------------------
flink-dist/src/main/assemblies/bin.xml | 30 +-
.../runtime/webmonitor/WebRuntimeMonitor.java | 145 ++++++----
.../runtime/webmonitor/files/MimeTypes.java | 118 ++++++++
.../files/StaticFileServerHandler.java | 285 +++++++++++++++++++
.../runtime/webmonitor/files/MimeTypesTest.java | 71 +++++
5 files changed, 589 insertions(+), 60 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/flink/blob/e86f4517/flink-dist/src/main/assemblies/bin.xml
----------------------------------------------------------------------
diff --git a/flink-dist/src/main/assemblies/bin.xml b/flink-dist/src/main/assemblies/bin.xml
index 1cd1935..7480f79 100644
--- a/flink-dist/src/main/assemblies/bin.xml
+++ b/flink-dist/src/main/assemblies/bin.xml
@@ -60,33 +60,36 @@ under the License.
</files>
<fileSets>
+ <!-- copy start scripts -->
<fileSet>
- <!-- copy start scripts -->
<directory>src/main/flink-bin/bin</directory>
<outputDirectory>bin</outputDirectory>
<fileMode>0755</fileMode>
</fileSet>
+
<!-- flink scala shell-->
<fileSet>
<directory>../flink-staging/flink-scala-shell/start-script/</directory>
<outputDirectory>bin</outputDirectory>
<fileMode>755</fileMode>
</fileSet>
+
+ <!-- copy yarn start scripts -->
<fileSet>
- <!-- copy yarn start scripts -->
<directory>src/main/flink-bin/yarn-bin</directory>
<outputDirectory>bin</outputDirectory>
<fileMode>0755</fileMode>
</fileSet>
+
+ <!-- copy default configuration -->
<fileSet>
- <!-- copy default configuration -->
<directory>src/main/flink-bin/conf</directory>
<outputDirectory>conf</outputDirectory>
<fileMode>0644</fileMode>
</fileSet>
+ <!-- create an empty log directory -->
<fileSet>
- <!-- create an empty log directory -->
<directory>src/main/flink-bin/</directory>
<outputDirectory>log</outputDirectory>
<fileMode>0644</fileMode>
@@ -95,8 +98,8 @@ under the License.
</excludes>
</fileSet>
+ <!-- copy *.txt files -->
<fileSet>
- <!-- copy *.txt files -->
<directory>src/main/flink-bin/</directory>
<outputDirectory></outputDirectory>
<fileMode>0644</fileMode>
@@ -107,8 +110,8 @@ under the License.
</includes>
</fileSet>
+ <!-- copy JavaDocs -->
<fileSet>
- <!-- copy JavaDocs -->
<!-- <directory>../target/apidocs</directory -->
<directory>../target</directory>
<includes>
@@ -118,6 +121,13 @@ under the License.
<fileMode>0644</fileMode>
</fileSet>
+ <!-- copy the web documents -->
+ <fileSet>
+ <directory>../flink-runtime-web/web-dashboard/web</directory>
+ <outputDirectory>resources/web-runtime-monitor</outputDirectory>
+ <fileMode>0644</fileMode>
+ </fileSet>
+
<!-- copy the tools -->
<fileSet>
<directory>src/main/flink-bin/tools</directory>
@@ -136,9 +146,8 @@ under the License.
</excludes>
</fileSet>
-
+ <!-- copy jar files of java examples -->
<fileSet>
- <!-- copy jar files of java examples -->
<directory>../flink-examples/flink-java-examples/target</directory>
<outputDirectory>examples</outputDirectory>
<fileMode>0644</fileMode>
@@ -153,10 +162,11 @@ under the License.
<exclude>flink-java-examples-${project.version}-javadoc.jar</exclude>
</excludes>
</fileSet>
+
+ <!-- copy python package -->
<fileSet>
- <!-- copy python package -->
<directory>../flink-staging/flink-language-binding/flink-python/src/main/python/org/apache/flink/languagebinding/api/python</directory>
- <outputDirectory>resources/python/</outputDirectory>
+ <outputDirectory>resources/python</outputDirectory>
<fileMode>0755</fileMode>
</fileSet>
</fileSets>
http://git-wip-us.apache.org/repos/asf/flink/blob/e86f4517/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/WebRuntimeMonitor.java
----------------------------------------------------------------------
diff --git a/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/WebRuntimeMonitor.java b/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/WebRuntimeMonitor.java
index a5c1c48..3a8dd83 100644
--- a/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/WebRuntimeMonitor.java
+++ b/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/WebRuntimeMonitor.java
@@ -23,17 +23,19 @@ import akka.actor.ActorRef;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
+import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
-import io.netty.handler.codec.http.router.BadClientSilencer;
import io.netty.handler.codec.http.router.Handler;
import io.netty.handler.codec.http.router.Router;
+import io.netty.handler.stream.ChunkedWriteHandler;
import org.apache.flink.configuration.ConfigConstants;
import org.apache.flink.configuration.Configuration;
+import org.apache.flink.configuration.IllegalConfigurationException;
+import org.apache.flink.runtime.webmonitor.files.StaticFileServerHandler;
import org.apache.flink.runtime.webmonitor.handlers.ExecutionPlanHandler;
import org.apache.flink.runtime.webmonitor.handlers.JobSummaryHandler;
import org.apache.flink.runtime.webmonitor.handlers.JobVerticesOverviewHandler;
@@ -47,21 +49,33 @@ import org.slf4j.LoggerFactory;
import scala.concurrent.duration.FiniteDuration;
+import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
+/**
+ * The root component of the web runtime monitor.
+ *
+ * <p>The web runtime monitor is based in Netty HTTP. It uses the Netty-Router library to route
+ * HTTP requests of different paths to different response handlers. In addition, it serves the static
+ * files of the web frontend, such as HTML, CSS, or JS files.</p>
+ */
public class WebRuntimeMonitor implements WebMonitor {
public static final FiniteDuration DEFAULT_REQUEST_TIMEOUT = new FiniteDuration(10, TimeUnit.SECONDS);
- public static final long DEFAULT_REFRESH_INTERVAL = 2000;
-
+ public static final long DEFAULT_REFRESH_INTERVAL = 5000;
+ /** Logger for web frontend startup / shutdown messages */
private static final Logger LOG = LoggerFactory.getLogger(WebRuntimeMonitor.class);
+ /** Teh default path under which the static contents is stored */
+ private static final String STATIC_CONTENTS_PATH = "resources/web-runtime-monitor";
+
// ------------------------------------------------------------------------
- // ------------------------------------------------------------------------
+
+ private final Object startupShutdownLock = new Object();
private final Router router;
@@ -73,11 +87,34 @@ public class WebRuntimeMonitor implements WebMonitor {
public WebRuntimeMonitor(Configuration config, ActorRef jobManager, ActorRef archive) throws IOException {
+ // figure out where our static contents is
+ final String configuredWebRoot = config.getString(ConfigConstants.JOB_MANAGER_WEB_DOC_ROOT_KEY, null);
+ final String flinkRoot = config.getString(ConfigConstants.FLINK_BASE_DIR_PATH_KEY, null);
+
+ final File webRootDir;
+ if (configuredWebRoot != null) {
+ webRootDir = new File(configuredWebRoot);
+ }
+ else if (flinkRoot != null) {
+ webRootDir = new File(flinkRoot, STATIC_CONTENTS_PATH);
+ }
+ else {
+ throw new IllegalConfigurationException("The given configuration provides neither the web-document root ("
+ + ConfigConstants.JOB_MANAGER_WEB_DOC_ROOT_KEY + "), not the Flink installation root ("
+ + ConfigConstants.FLINK_BASE_DIR_PATH_KEY + ").");
+ }
+ // validate that the doc root is a valid directory
+ if (!(webRootDir.exists() && webRootDir.isDirectory() && webRootDir.canRead())) {
+ throw new IllegalConfigurationException("The path to the static contents (" +
+ webRootDir.getAbsolutePath() + ") is not a readable directory.");
+ }
+
+ // port configuration
this.configuredPort = config.getInteger(ConfigConstants.JOB_MANAGER_NEW_WEB_PORT_KEY,
ConfigConstants.DEFAULT_JOB_MANAGER_NEW_WEB_FRONTEND_PORT);
if (this.configuredPort < 0) {
- throw new IllegalArgumentException("Web frontend port is " + this.configuredPort);
+ throw new IllegalArgumentException("Web frontend port is invalid: " + this.configuredPort);
}
ExecutionGraphHolder currentGraphs = new ExecutionGraphHolder(jobManager);
@@ -93,61 +130,70 @@ public class WebRuntimeMonitor implements WebMonitor {
.GET("/jobs", handler(new RequestJobIdsHandler(jobManager)))
.GET("/jobs/:jobid", handler(new JobSummaryHandler(currentGraphs)))
.GET("/jobs/:jobid/vertices", handler(new JobVerticesOverviewHandler(currentGraphs)))
- .GET("/jobs/:jobid/plan", handler(new ExecutionPlanHandler(currentGraphs)));
+ .GET("/jobs/:jobid/plan", handler(new ExecutionPlanHandler(currentGraphs)))
+
// .GET("/running/:jobid/:jobvertex", handler(new ExecutionPlanHandler(currentGraphs)))
+
+ // this handler serves all the static contents
+ .GET("/:*", new StaticFileServerHandler(webRootDir));
+
}
@Override
public void start() throws Exception {
-
- ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
-
- @Override
- protected void initChannel(SocketChannel ch) {
- Handler handler = new Handler(router);
-
- ch.pipeline()
- .addLast(new HttpServerCodec())
- .addLast(handler.name(), handler)
- .addLast(new BadClientSilencer());
+ synchronized (startupShutdownLock) {
+ if (this.bootstrap != null) {
+ throw new IllegalStateException("The server has already been started");
}
- };
-
- NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
- NioEventLoopGroup workerGroup = new NioEventLoopGroup();
-
- this.bootstrap = new ServerBootstrap();
- this.bootstrap.group(bossGroup, workerGroup)
- .childOption(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE)
- .childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE)
- .channel(NioServerSocketChannel.class)
- .childHandler(initializer);
-
- Channel ch = this.bootstrap.bind(configuredPort).sync().channel();
-
- InetSocketAddress bindAddress = (InetSocketAddress) ch.localAddress();
- String address = bindAddress.getAddress().getHostAddress();
- int port = bindAddress.getPort();
-
- LOG.info("Web frontend listening at " + address + ':' + port);
+
+ ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
+
+ @Override
+ protected void initChannel(SocketChannel ch) {
+ Handler handler = new Handler(router);
+
+ ch.pipeline()
+ .addLast(new HttpServerCodec())
+ .addLast(new HttpObjectAggregator(65536))
+ .addLast(new ChunkedWriteHandler())
+ .addLast(handler.name(), handler);
+ }
+ };
+
+ NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
+ NioEventLoopGroup workerGroup = new NioEventLoopGroup();
+
+ this.bootstrap = new ServerBootstrap();
+ this.bootstrap
+ .group(bossGroup, workerGroup)
+ .channel(NioServerSocketChannel.class)
+ .childHandler(initializer);
+
+ Channel ch = this.bootstrap.bind(configuredPort).sync().channel();
+ this.serverChannel = ch;
+
+ InetSocketAddress bindAddress = (InetSocketAddress) ch.localAddress();
+ String address = bindAddress.getAddress().getHostAddress();
+ int port = bindAddress.getPort();
+
+ LOG.info("Web frontend listening at " + address + ':' + port);
+ }
}
@Override
public void stop() throws Exception {
- Channel server = this.serverChannel;
- ServerBootstrap bootstrap = this.bootstrap;
-
- if (server != null) {
- server.close().awaitUninterruptibly();
- this.serverChannel = null;
- }
-
- if (bootstrap != null) {
- if (bootstrap.group() != null) {
- bootstrap.group().shutdownGracefully();
+ synchronized (startupShutdownLock) {
+ if (this.serverChannel != null) {
+ this.serverChannel.close().awaitUninterruptibly();
+ this.serverChannel = null;
+ }
+ if (bootstrap != null) {
+ if (bootstrap.group() != null) {
+ bootstrap.group().shutdownGracefully();
+ }
+ this.bootstrap = null;
}
- this.bootstrap = null;
}
}
@@ -166,7 +212,6 @@ public class WebRuntimeMonitor implements WebMonitor {
return -1;
}
-
// ------------------------------------------------------------------------
// Utilities
// ------------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/flink/blob/e86f4517/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/MimeTypes.java
----------------------------------------------------------------------
diff --git a/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/MimeTypes.java b/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/MimeTypes.java
new file mode 100644
index 0000000..9c3b45d
--- /dev/null
+++ b/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/MimeTypes.java
@@ -0,0 +1,118 @@
+/*
+ * 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.flink.runtime.webmonitor.files;
+
+import java.util.HashMap;
+
+/**
+ * Simple utility class that resolves file extensions to MIME types.
+ *
+ * <p>There are various solutions built into Java that depend on extra resource and configuration
+ * files. They are designed to be composable and extensible, but also unfortunately tricky to control.
+ * This is meant to be a simple solution that may eventually be subsumed by a better one.</p>
+ */
+public class MimeTypes {
+
+ /** The default mime type */
+ private static final String DEFAULT_MIME_TYPE = "application/octet-stream";
+
+ /** The map with the constants */
+ private static final HashMap<String, String> MIME_MAP = new HashMap<String, String>();
+
+ /**
+ * Gets the MIME type for the file with the given extension. If the mime type is not recognized,
+ * this method returns null.
+ *
+ * @param fileExtension The file extension.
+ * @return The MIME type, or {@code null}, if the file extension is not recognized.
+ */
+ public static String getMimeTypeForExtension(String fileExtension) {
+ return MIME_MAP.get(fileExtension.toLowerCase());
+ }
+
+ /**
+ * Gets the MIME type for the file with the given name, by extension. This method tries to extract
+ * the file extension and then use the {@link #getMimeTypeForExtension(String)} to determine the
+ * MIME type. If the extension cannot be determined, or the extension is unrecognized, this method
+ * return {@code null}.
+ *
+ * @param fileName The file name.
+ * @return The MIME type, or {@code null}, if the file's extension is not recognized.
+ */
+ public static String getMimeTypeForFileName(String fileName) {
+ int extensionPos = fileName.lastIndexOf('.');
+ if (extensionPos >= 1 && extensionPos < fileName.length() - 1) {
+ String extension = fileName.substring(extensionPos + 1);
+ return getMimeTypeForExtension(extension);
+ }
+ else {
+ return null;
+ }
+ }
+
+ /**
+ * Gets the default MIME type, which is {@code "application/octet-stream"}.
+ *
+ * @return The default MIME type.
+ */
+ public static String getDefaultMimeType() {
+ return DEFAULT_MIME_TYPE;
+ }
+
+ // ------------------------------------------------------------------------
+ // prevent instantiation
+ // ------------------------------------------------------------------------
+
+ private MimeTypes() {}
+
+ // ------------------------------------------------------------------------
+ // initialization
+ // ------------------------------------------------------------------------
+
+ static {
+ // text types
+ MIME_MAP.put("html", "text/html");
+ MIME_MAP.put("htm", "text/html");
+ MIME_MAP.put("css", "text/css");
+ MIME_MAP.put("txt", "text/plain");
+ MIME_MAP.put("xml", "text/xml");
+ MIME_MAP.put("csv", "text/csv");
+
+ // application types
+ MIME_MAP.put("js", "application/javascript");
+ MIME_MAP.put("json", "application/json");
+
+ // image types
+ MIME_MAP.put("png", "image/png");
+ MIME_MAP.put("jpg", "image/jpeg");
+ MIME_MAP.put("jpeg", "image/jpeg");
+ MIME_MAP.put("gif", "image/gif");
+ MIME_MAP.put("svg", "image/svg+xml");
+ MIME_MAP.put("tiff", "image/tiff");
+ MIME_MAP.put("tff", "image/tiff");
+ MIME_MAP.put("bmp", "image/bmp");
+
+ // fonts
+ MIME_MAP.put("woff", "application/font-woff");
+ MIME_MAP.put("woff2", "application/font-woff2");
+ MIME_MAP.put("ttf", "font/ttf");
+ MIME_MAP.put("otf", "font/opentype");
+ MIME_MAP.put("eot", "font/application/vnd.ms-fontobject");
+ }
+}
http://git-wip-us.apache.org/repos/asf/flink/blob/e86f4517/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/StaticFileServerHandler.java
----------------------------------------------------------------------
diff --git a/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/StaticFileServerHandler.java b/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/StaticFileServerHandler.java
new file mode 100644
index 0000000..e368ea9
--- /dev/null
+++ b/flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/files/StaticFileServerHandler.java
@@ -0,0 +1,285 @@
+/*
+ * 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.flink.runtime.webmonitor.files;
+
+/*****************************************************************************
+ * This code is based on the "HttpStaticFileServerHandler" from the
+ * Netty project's HTTP server example.
+ *
+ * See http://netty.io and
+ * https://github.com/netty/netty/blob/4.0/example/src/main/java/io/netty/example/http/file/HttpStaticFileServerHandler.java
+ *****************************************************************************/
+
+import io.netty.buffer.Unpooled;
+import io.netty.channel.ChannelFuture;
+import io.netty.channel.ChannelFutureListener;
+import io.netty.channel.ChannelHandler;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.DefaultFileRegion;
+import io.netty.channel.SimpleChannelInboundHandler;
+import io.netty.handler.codec.http.DefaultFullHttpResponse;
+import io.netty.handler.codec.http.DefaultHttpResponse;
+import io.netty.handler.codec.http.FullHttpResponse;
+import io.netty.handler.codec.http.HttpHeaders;
+import io.netty.handler.codec.http.HttpRequest;
+import io.netty.handler.codec.http.HttpResponse;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.netty.handler.codec.http.LastHttpContent;
+import io.netty.handler.codec.http.router.Routed;
+import io.netty.util.CharsetUtil;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.RandomAccessFile;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import static io.netty.handler.codec.http.HttpHeaders.Names.CACHE_CONTROL;
+import static io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION;
+import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
+import static io.netty.handler.codec.http.HttpHeaders.Names.DATE;
+import static io.netty.handler.codec.http.HttpHeaders.Names.EXPIRES;
+import static io.netty.handler.codec.http.HttpHeaders.Names.IF_MODIFIED_SINCE;
+import static io.netty.handler.codec.http.HttpHeaders.Names.LAST_MODIFIED;
+import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_MODIFIED;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
+/**
+ * Simple file server handler that serves requests to web frontend's static files, such as
+ * HTML, CSS, or JS files.
+ *
+ * <p>This code is based on the "HttpStaticFileServerHandler" from the Netty project's HTTP server
+ * example.</p>
+ */
+@ChannelHandler.Sharable
+public class StaticFileServerHandler extends SimpleChannelInboundHandler<Routed> {
+
+ /** Default logger, if none is specified */
+ private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(StaticFileServerHandler.class);
+
+ /** Timezone in which this server answers its "if-modified" requests */
+ private static final TimeZone GMT_TIMEZONE = TimeZone.getTimeZone("GMT");
+
+ /** Date format for HTTP */
+ private static final String HTTP_DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";
+
+ /** Be default, we allow files to be cached for 5 minutes */
+ private static final int HTTP_CACHE_SECONDS = 300;
+
+ // ------------------------------------------------------------------------
+
+ /** The path in which the static documents are */
+ private final File rootPath;
+
+ /** The log for all error reporting */
+ private final Logger logger;
+
+
+ public StaticFileServerHandler(File rootPath) {
+ this(rootPath, DEFAULT_LOGGER);
+ }
+
+ public StaticFileServerHandler(File rootPath, Logger logger) {
+ if (rootPath == null || logger == null) {
+ throw new NullPointerException();
+ }
+
+ this.rootPath = rootPath;
+ this.logger = logger;
+ }
+
+ // ------------------------------------------------------------------------
+ // Responses to requests
+ // ------------------------------------------------------------------------
+
+ @Override
+ public void channelRead0(ChannelHandlerContext ctx, Routed routed) throws Exception {
+ final HttpRequest request = routed.request();
+ String requestPath = routed.path();
+
+ // make sure we request the "index.html" in case there is a directory request
+ if (requestPath.endsWith("/")) {
+ requestPath = requestPath + "index.html";
+ }
+
+ // convert file separators.
+ if (File.separatorChar != '/') {
+ requestPath = requestPath.replace('/', File.separatorChar);
+ }
+
+ // convert to absolute path
+ final File file = new File(rootPath, requestPath);
+
+ if (!file.exists() || file.isHidden() || file.isDirectory() || !file.isFile()) {
+ sendError(ctx, NOT_FOUND);
+ return;
+ }
+
+ // cache validation
+ final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
+ if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
+ SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
+ Date ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince);
+
+ // Only compare up to the second because the datetime format we send to the client
+ // does not have milliseconds
+ long ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime() / 1000;
+ long fileLastModifiedSeconds = file.lastModified() / 1000;
+ if (ifModifiedSinceDateSeconds == fileLastModifiedSeconds) {
+ if (logger.isDebugEnabled()) {
+ logger.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
+ }
+
+ sendNotModified(ctx);
+ return;
+ }
+ }
+
+ if (logger.isDebugEnabled()) {
+ logger.debug("Responding with file '" + file.getAbsolutePath() + '\'');
+ }
+
+ final RandomAccessFile raf;
+ try {
+ raf = new RandomAccessFile(file, "r");
+ }
+ catch (FileNotFoundException e) {
+ sendError(ctx, NOT_FOUND);
+ return;
+ }
+ long fileLength = raf.length();
+
+ HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
+ setContentTypeHeader(response, file);
+ setDateAndCacheHeaders(response, file);
+ if (HttpHeaders.isKeepAlive(request)) {
+ response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
+ }
+ HttpHeaders.setContentLength(response, fileLength);
+
+ // write the initial line and the header.
+ ctx.write(response);
+
+ // write the content.
+ ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
+ ChannelFuture lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
+
+ // close the connection, if no keep-alive is needed
+ if (!HttpHeaders.isKeepAlive(request)) {
+ lastContentFuture.addListener(ChannelFutureListener.CLOSE);
+ }
+ }
+
+ @Override
+ public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+ if (ctx.channel().isActive()) {
+ logger.error("Caught exception", cause);
+ sendError(ctx, INTERNAL_SERVER_ERROR);
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // Utilities to encode headers and responses
+ // ------------------------------------------------------------------------
+
+ /**
+ * Writes a simple error response message.
+ *
+ * @param ctx The channel context to write the response to.
+ * @param status The response status.
+ */
+ private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
+ FullHttpResponse response = new DefaultFullHttpResponse(
+ HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status + "\r\n", CharsetUtil.UTF_8));
+ response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
+
+ // close the connection as soon as the error message is sent.
+ ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
+ }
+
+ /**
+ * Send the "304 Not Modified" response. This response can be used when the
+ * file timestamp is the same as what the browser is sending up.
+ *
+ * @param ctx The channel context to write the response to.
+ */
+ private static void sendNotModified(ChannelHandlerContext ctx) {
+ FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
+ setDateHeader(response);
+
+ // close the connection as soon as the error message is sent.
+ ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
+ }
+
+ /**
+ * Sets the "date" header for the HTTP response.
+ *
+ * @param response HTTP response
+ */
+ private static void setDateHeader(FullHttpResponse response) {
+ SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
+ dateFormatter.setTimeZone(GMT_TIMEZONE);
+
+ Calendar time = new GregorianCalendar();
+ response.headers().set(DATE, dateFormatter.format(time.getTime()));
+ }
+
+ /**
+ * Sets the "date" and "cache" headers for the HTTP Response.
+ *
+ * @param response The HTTP response object.
+ * @param fileToCache File to extract the modification timestamp from.
+ */
+ private static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
+ SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
+ dateFormatter.setTimeZone(GMT_TIMEZONE);
+
+ // date header
+ Calendar time = new GregorianCalendar();
+ response.headers().set(DATE, dateFormatter.format(time.getTime()));
+
+ // cache headers
+ time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
+ response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
+ response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
+ response.headers().set(LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
+ }
+
+ /**
+ * Sets the content type header for the HTTP Response.
+ *
+ * @param response HTTP response
+ * @param file file to extract content type
+ */
+ private static void setContentTypeHeader(HttpResponse response, File file) {
+ String mimeType = MimeTypes.getMimeTypeForFileName(file.getName());
+ String mimeFinal = mimeType != null ? mimeType : MimeTypes.getDefaultMimeType();
+ response.headers().set(CONTENT_TYPE, mimeFinal);
+ }
+}
http://git-wip-us.apache.org/repos/asf/flink/blob/e86f4517/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/files/MimeTypesTest.java
----------------------------------------------------------------------
diff --git a/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/files/MimeTypesTest.java b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/files/MimeTypesTest.java
new file mode 100644
index 0000000..d16b848
--- /dev/null
+++ b/flink-runtime-web/src/test/java/org/apache/flink/runtime/webmonitor/files/MimeTypesTest.java
@@ -0,0 +1,71 @@
+/*
+ * 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.flink.runtime.webmonitor.files;
+
+import org.junit.Test;
+
+import static org.junit.Assert.*;
+
+/**
+ * Tests for the MIME types map.
+ */
+public class MimeTypesTest {
+
+ @Test
+ public void testCompleteness() {
+ try {
+ assertNotNull(MimeTypes.getMimeTypeForExtension("txt"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("htm"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("html"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("css"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("js"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("json"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("png"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("jpg"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("jpeg"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("gif"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("woff"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("woff2"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("otf"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("ttf"));
+ assertNotNull(MimeTypes.getMimeTypeForExtension("eot"));
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
+
+ @Test
+ public void testFileNameExtraction() {
+ try {
+ assertNotNull(MimeTypes.getMimeTypeForFileName("test.txt"));
+ assertNotNull(MimeTypes.getMimeTypeForFileName("t.txt"));
+ assertNotNull(MimeTypes.getMimeTypeForFileName("first.second.third.txt"));
+
+ assertNull(MimeTypes.getMimeTypeForFileName(".txt"));
+ assertNull(MimeTypes.getMimeTypeForFileName("txt"));
+ assertNull(MimeTypes.getMimeTypeForFileName("test."));
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ fail(e.getMessage());
+ }
+ }
+}