Search in sources :

Example 1 with NotFoundException

use of org.apache.flink.runtime.rest.NotFoundException in project flink by apache.

the class HistoryServerStaticFileServerHandler method respondWithFile.

/**
 * Response when running with leading JobManager.
 */
private void respondWithFile(ChannelHandlerContext ctx, HttpRequest request, String requestPath) throws IOException, ParseException, RestHandlerException {
    // make sure we request the "index.html" in case there is a directory request
    if (requestPath.endsWith("/")) {
        requestPath = requestPath + "index.html";
    }
    if (!requestPath.contains(".")) {
        // we assume that the path ends in either .html or .js
        requestPath = requestPath + ".json";
    }
    // convert to absolute path
    final File file = new File(rootPath, requestPath);
    if (!file.exists()) {
        // file does not exist. Try to load it with the classloader
        ClassLoader cl = HistoryServerStaticFileServerHandler.class.getClassLoader();
        try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
            boolean success = false;
            try {
                if (resourceStream != null) {
                    URL root = cl.getResource("web");
                    URL requested = cl.getResource("web" + requestPath);
                    if (root != null && requested != null) {
                        URI rootURI = new URI(root.getPath()).normalize();
                        URI requestedURI = new URI(requested.getPath()).normalize();
                        // expected scope.
                        if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
                            LOG.debug("Loading missing file from classloader: {}", requestPath);
                            // ensure that directory to file exists.
                            file.getParentFile().mkdirs();
                            Files.copy(resourceStream, file.toPath());
                            success = true;
                        }
                    }
                }
            } catch (Throwable t) {
                LOG.error("error while responding", t);
            } finally {
                if (!success) {
                    LOG.debug("Unable to load requested file {} from classloader", requestPath);
                    throw new NotFoundException("File not found.");
                }
            }
        }
    }
    StaticFileServerHandler.checkFileValidity(file, rootPath, LOG);
    // cache validation
    final String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE);
    if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat(StaticFileServerHandler.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 (LOG.isDebugEnabled()) {
                LOG.debug("Responding 'NOT MODIFIED' for file '" + file.getAbsolutePath() + '\'');
            }
            StaticFileServerHandler.sendNotModified(ctx);
            return;
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Responding with file '" + file.getAbsolutePath() + '\'');
    }
    // Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
    final RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Could not find file {}.", file.getAbsolutePath());
        }
        HandlerUtils.sendErrorResponse(ctx, request, new ErrorResponseBody("File not found."), NOT_FOUND, Collections.emptyMap());
        return;
    }
    try {
        long fileLength = raf.length();
        HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
        StaticFileServerHandler.setContentTypeHeader(response, file);
        // the job overview should be updated as soon as possible
        if (!requestPath.equals("/joboverview.json")) {
            StaticFileServerHandler.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.
        ChannelFuture lastContentFuture;
        if (ctx.pipeline().get(SslHandler.class) == null) {
            ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
            lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        }
        // close the connection, if no keep-alive is needed
        if (!HttpHeaders.isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e) {
        raf.close();
        LOG.error("Failed to serve file.", e);
        throw new RestHandlerException("Internal server error.", INTERNAL_SERVER_ERROR);
    }
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) InputStream(java.io.InputStream) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) ErrorResponseBody(org.apache.flink.runtime.rest.messages.ErrorResponseBody) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) URI(java.net.URI) URL(java.net.URL) Date(java.util.Date) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) ParseException(java.text.ParseException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) SimpleDateFormat(java.text.SimpleDateFormat)

Example 2 with NotFoundException

use of org.apache.flink.runtime.rest.NotFoundException in project flink by apache.

the class JobVertexTaskManagersHandler method handleRequest.

@Override
protected JobVertexTaskManagersInfo handleRequest(HandlerRequest<EmptyRequestBody> request, AccessExecutionGraph executionGraph) throws RestHandlerException {
    JobID jobID = request.getPathParameter(JobIDPathParameter.class);
    JobVertexID jobVertexID = request.getPathParameter(JobVertexIdPathParameter.class);
    AccessExecutionJobVertex jobVertex = executionGraph.getJobVertex(jobVertexID);
    if (jobVertex == null) {
        throw new NotFoundException(String.format("JobVertex %s not found", jobVertexID));
    }
    return createJobVertexTaskManagersInfo(jobVertex, jobID, metricFetcher);
}
Also used : AccessExecutionJobVertex(org.apache.flink.runtime.executiongraph.AccessExecutionJobVertex) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) JobID(org.apache.flink.api.common.JobID)

Example 3 with NotFoundException

use of org.apache.flink.runtime.rest.NotFoundException in project flink by apache.

the class AbstractExecutionGraphHandler method handleRequest.

@Override
protected CompletableFuture<R> handleRequest(@Nonnull HandlerRequest<EmptyRequestBody> request, @Nonnull RestfulGateway gateway) throws RestHandlerException {
    JobID jobId = request.getPathParameter(JobIDPathParameter.class);
    CompletableFuture<ExecutionGraphInfo> executionGraphFuture = executionGraphCache.getExecutionGraphInfo(jobId, gateway);
    return executionGraphFuture.thenApplyAsync(executionGraph -> {
        try {
            return handleRequest(request, executionGraph);
        } catch (RestHandlerException rhe) {
            throw new CompletionException(rhe);
        }
    }, executor).exceptionally(throwable -> {
        throwable = ExceptionUtils.stripCompletionException(throwable);
        if (throwable instanceof FlinkJobNotFoundException) {
            throw new CompletionException(new NotFoundException(String.format("Job %s not found", jobId), throwable));
        } else {
            throw new CompletionException(throwable);
        }
    });
}
Also used : ExecutionGraphCache(org.apache.flink.runtime.rest.handler.legacy.ExecutionGraphCache) Executor(java.util.concurrent.Executor) GatewayRetriever(org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever) RestfulGateway(org.apache.flink.runtime.webmonitor.RestfulGateway) ExceptionUtils(org.apache.flink.util.ExceptionUtils) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) MessageHeaders(org.apache.flink.runtime.rest.messages.MessageHeaders) ExecutionGraphInfo(org.apache.flink.runtime.scheduler.ExecutionGraphInfo) Preconditions(org.apache.flink.util.Preconditions) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) EmptyRequestBody(org.apache.flink.runtime.rest.messages.EmptyRequestBody) JobID(org.apache.flink.api.common.JobID) JobMessageParameters(org.apache.flink.runtime.rest.messages.JobMessageParameters) ResponseBody(org.apache.flink.runtime.rest.messages.ResponseBody) FlinkJobNotFoundException(org.apache.flink.runtime.messages.FlinkJobNotFoundException) Map(java.util.Map) HandlerRequest(org.apache.flink.runtime.rest.handler.HandlerRequest) Nonnull(javax.annotation.Nonnull) Time(org.apache.flink.api.common.time.Time) AbstractRestHandler(org.apache.flink.runtime.rest.handler.AbstractRestHandler) JobIDPathParameter(org.apache.flink.runtime.rest.messages.JobIDPathParameter) ExecutionGraphInfo(org.apache.flink.runtime.scheduler.ExecutionGraphInfo) CompletionException(java.util.concurrent.CompletionException) FlinkJobNotFoundException(org.apache.flink.runtime.messages.FlinkJobNotFoundException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) FlinkJobNotFoundException(org.apache.flink.runtime.messages.FlinkJobNotFoundException) JobID(org.apache.flink.api.common.JobID) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException)

Example 4 with NotFoundException

use of org.apache.flink.runtime.rest.NotFoundException in project flink by apache.

the class StaticFileServerHandler method respondToRequest.

/**
 * Response when running with leading JobManager.
 */
private void respondToRequest(ChannelHandlerContext ctx, HttpRequest request, String requestPath) throws IOException, ParseException, URISyntaxException, RestHandlerException {
    // convert to absolute path
    final File file = new File(rootPath, requestPath);
    if (!file.exists()) {
        // file does not exist. Try to load it with the classloader
        ClassLoader cl = StaticFileServerHandler.class.getClassLoader();
        try (InputStream resourceStream = cl.getResourceAsStream("web" + requestPath)) {
            boolean success = false;
            try {
                if (resourceStream != null) {
                    URL root = cl.getResource("web");
                    URL requested = cl.getResource("web" + requestPath);
                    if (root != null && requested != null) {
                        URI rootURI = new URI(root.getPath()).normalize();
                        URI requestedURI = new URI(requested.getPath()).normalize();
                        // expected scope.
                        if (!rootURI.relativize(requestedURI).equals(requestedURI)) {
                            logger.debug("Loading missing file from classloader: {}", requestPath);
                            // ensure that directory to file exists.
                            file.getParentFile().mkdirs();
                            Files.copy(resourceStream, file.toPath());
                            success = true;
                        }
                    }
                }
            } catch (Throwable t) {
                logger.error("error while responding", t);
            } finally {
                if (!success) {
                    logger.debug("Unable to load requested file {} from classloader", requestPath);
                    throw new NotFoundException(String.format("Unable to load requested file %s.", requestPath));
                }
            }
        }
    }
    checkFileValidity(file, rootPath, logger);
    // 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() + '\'');
    }
    // Don't need to close this manually. Netty's DefaultFileRegion will take care of it.
    final RandomAccessFile raf;
    try {
        raf = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException e) {
        if (logger.isDebugEnabled()) {
            logger.debug("Could not find file {}.", file.getAbsolutePath());
        }
        throw new NotFoundException("File not found.");
    }
    try {
        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.
        ChannelFuture lastContentFuture;
        if (ctx.pipeline().get(SslHandler.class) == null) {
            ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength), ctx.newProgressivePromise());
            lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
        } else {
            lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(raf, 0, fileLength, 8192)), ctx.newProgressivePromise());
        // HttpChunkedInput will write the end marker (LastHttpContent) for us.
        }
        // close the connection, if no keep-alive is needed
        if (!HttpHeaders.isKeepAlive(request)) {
            lastContentFuture.addListener(ChannelFutureListener.CLOSE);
        }
    } catch (Exception e) {
        raf.close();
        logger.error("Failed to serve file.", e);
        throw new RestHandlerException("Internal server error.", INTERNAL_SERVER_ERROR);
    }
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) InputStream(java.io.InputStream) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) FileNotFoundException(java.io.FileNotFoundException) FullHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) DefaultFullHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpResponse) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) URI(java.net.URI) URL(java.net.URL) Date(java.util.Date) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) URISyntaxException(java.net.URISyntaxException) NotFoundException(org.apache.flink.runtime.rest.NotFoundException) ParseException(java.text.ParseException) FileNotFoundException(java.io.FileNotFoundException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) IOException(java.io.IOException) RestHandlerException(org.apache.flink.runtime.rest.handler.RestHandlerException) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) SimpleDateFormat(java.text.SimpleDateFormat)

Example 5 with NotFoundException

use of org.apache.flink.runtime.rest.NotFoundException in project flink by apache.

the class TaskCheckpointStatisticDetailsHandler method handleCheckpointRequest.

@Override
protected TaskCheckpointStatisticsWithSubtaskDetails handleCheckpointRequest(HandlerRequest<EmptyRequestBody> request, AbstractCheckpointStats checkpointStats) throws RestHandlerException {
    final JobVertexID jobVertexId = request.getPathParameter(JobVertexIdPathParameter.class);
    final TaskStateStats taskStatistics = checkpointStats.getTaskStateStats(jobVertexId);
    if (taskStatistics == null) {
        throw new NotFoundException("There is no checkpoint statistics for task " + jobVertexId + '.');
    }
    return createCheckpointDetails(checkpointStats, taskStatistics);
}
Also used : TaskStateStats(org.apache.flink.runtime.checkpoint.TaskStateStats) JobVertexID(org.apache.flink.runtime.jobgraph.JobVertexID) NotFoundException(org.apache.flink.runtime.rest.NotFoundException)

Aggregations

NotFoundException (org.apache.flink.runtime.rest.NotFoundException)7 RestHandlerException (org.apache.flink.runtime.rest.handler.RestHandlerException)4 File (java.io.File)3 IOException (java.io.IOException)3 JobID (org.apache.flink.api.common.JobID)3 JobVertexID (org.apache.flink.runtime.jobgraph.JobVertexID)3 FileNotFoundException (java.io.FileNotFoundException)2 InputStream (java.io.InputStream)2 RandomAccessFile (java.io.RandomAccessFile)2 URI (java.net.URI)2 URL (java.net.URL)2 ParseException (java.text.ParseException)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Date (java.util.Date)2 CompletionException (java.util.concurrent.CompletionException)2 AccessExecutionJobVertex (org.apache.flink.runtime.executiongraph.AccessExecutionJobVertex)2 URISyntaxException (java.net.URISyntaxException)1 Map (java.util.Map)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExecutionException (java.util.concurrent.ExecutionException)1