Search in sources :

Example 1 with UIFileInfo

use of alluxio.util.webui.UIFileInfo in project alluxio by Alluxio.

the class AlluxioMasterRestServiceHandler method getWebUILogs.

/**
 * Gets Web UI logs page data.
 *
 * @param requestPath the request path
 * @param requestOffset the request offset
 * @param requestEnd the request end
 * @param requestLimit the request limit
 * @return the response object
 */
@GET
@Path(WEBUI_LOGS)
public Response getWebUILogs(@DefaultValue("") @QueryParam("path") String requestPath, @DefaultValue("0") @QueryParam("offset") String requestOffset, @DefaultValue("") @QueryParam("end") String requestEnd, @DefaultValue("20") @QueryParam("limit") String requestLimit) {
    return RestUtils.call(() -> {
        FilenameFilter filenameFilter = (dir, name) -> name.toLowerCase().endsWith(".log");
        MasterWebUILogs response = new MasterWebUILogs();
        if (!ServerConfiguration.getBoolean(PropertyKey.WEB_FILE_INFO_ENABLED)) {
            return response;
        }
        response.setDebug(ServerConfiguration.getBoolean(PropertyKey.DEBUG)).setInvalidPathError("").setViewingOffset(0).setCurrentPath("");
        // response.setDownloadLogFile(1);
        // response.setBaseUrl("./browseLogs");
        // response.setShowPermissions(false);
        String logsPath = ServerConfiguration.getString(PropertyKey.LOGS_DIR);
        File logsDir = new File(logsPath);
        String requestFile = requestPath;
        if (requestFile == null || requestFile.isEmpty()) {
            // List all log files in the log/ directory.
            List<UIFileInfo> fileInfos = new ArrayList<>();
            File[] logFiles = logsDir.listFiles(filenameFilter);
            if (logFiles != null) {
                for (File logFile : logFiles) {
                    String logFileName = logFile.getName();
                    fileInfos.add(new UIFileInfo(new UIFileInfo.LocalFileInfo(logFileName, logFileName, logFile.length(), UIFileInfo.LocalFileInfo.EMPTY_CREATION_TIME, logFile.lastModified(), logFile.isDirectory()), ServerConfiguration.global(), new MasterStorageTierAssoc().getOrderedStorageAliases()));
                }
            }
            fileInfos.sort(UIFileInfo.PATH_STRING_COMPARE);
            response.setNTotalFile(fileInfos.size());
            try {
                int offset = Integer.parseInt(requestOffset);
                int limit = Integer.parseInt(requestLimit);
                limit = offset == 0 && limit > fileInfos.size() ? fileInfos.size() : limit;
                limit = offset + limit > fileInfos.size() ? fileInfos.size() - offset : limit;
                int sum = Math.addExact(offset, limit);
                fileInfos = fileInfos.subList(offset, sum);
                response.setFileInfos(fileInfos);
            } catch (NumberFormatException e) {
                response.setFatalError("Error: offset or limit parse error, " + e.getLocalizedMessage());
                return response;
            } catch (ArithmeticException e) {
                response.setFatalError("Error: offset or offset + limit is out of bound, " + e.getLocalizedMessage());
                return response;
            } catch (IllegalArgumentException e) {
                response.setFatalError(e.getLocalizedMessage());
                return response;
            }
        } else {
            // Request a specific log file.
            // Only allow filenames as the path, to avoid arbitrary local path lookups.
            requestFile = new File(requestFile).getName();
            response.setCurrentPath(requestFile);
            File logFile = new File(logsDir, requestFile);
            try {
                long fileSize = logFile.length();
                long relativeOffset = 0;
                long offset;
                try {
                    if (requestOffset != null) {
                        relativeOffset = Long.parseLong(requestOffset);
                    }
                } catch (NumberFormatException e) {
                // ignore the exception
                }
                // relative to the end of the file.
                if (requestEnd.equals("")) {
                    offset = relativeOffset;
                } else {
                    offset = fileSize - relativeOffset;
                }
                if (offset < 0) {
                    offset = 0;
                } else if (offset > fileSize) {
                    offset = fileSize;
                }
                String fileData;
                try (InputStream is = new FileInputStream(logFile)) {
                    fileSize = logFile.length();
                    int len = (int) Math.min(5L * Constants.KB, fileSize - offset);
                    byte[] data = new byte[len];
                    long skipped = is.skip(offset);
                    if (skipped < 0) {
                        // Nothing was skipped.
                        fileData = "Unable to traverse to offset; is file empty?";
                    } else if (skipped < offset) {
                        // Couldn't skip all the way to offset.
                        fileData = "Unable to traverse to offset; is offset larger than the file?";
                    } else {
                        // Read may not read up to len, so only convert what was read.
                        int read = is.read(data, 0, len);
                        if (read < 0) {
                            // Stream couldn't read anything, skip went to EOF?
                            fileData = "Unable to read file";
                        } else {
                            fileData = WebUtils.convertByteArrayToStringWithoutEscape(data, 0, read);
                        }
                    }
                }
                response.setFileData(fileData).setViewingOffset(offset);
            } catch (IOException e) {
                response.setInvalidPathError("Error: File " + logFile + " is not available " + e.getMessage());
            }
        }
        return response;
    }, ServerConfiguration.global());
}
Also used : Produces(javax.ws.rs.Produces) MasterWebServer(alluxio.web.MasterWebServer) ZonedDateTime(java.time.ZonedDateTime) DefaultFileSystemMaster(alluxio.master.file.DefaultFileSystemMaster) PropertyKey(alluxio.conf.PropertyKey) MediaType(javax.ws.rs.core.MediaType) FileSystem(alluxio.client.file.FileSystem) WorkerInfo(alluxio.wire.WorkerInfo) Map(java.util.Map) AlluxioMasterProcess(alluxio.master.AlluxioMasterProcess) WebUtils(alluxio.util.webui.WebUtils) ZoneOffset(java.time.ZoneOffset) Triple(org.apache.commons.lang3.tuple.Triple) ReadPType(alluxio.grpc.ReadPType) RestUtils(alluxio.RestUtils) Metric(com.codahale.metrics.Metric) Set(java.util.Set) AlluxioException(alluxio.exception.AlluxioException) ConfigProperty(alluxio.grpc.ConfigProperty) UIFileBlockInfo(alluxio.util.webui.UIFileBlockInfo) RuntimeConstants(alluxio.RuntimeConstants) FilenameFilter(java.io.FilenameFilter) ServerUserState(alluxio.security.user.ServerUserState) GET(javax.ws.rs.GET) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) MasterWebUIInit(alluxio.wire.MasterWebUIInit) AlluxioURI(alluxio.AlluxioURI) FileInStream(alluxio.client.file.FileInStream) FormatUtils(alluxio.util.FormatUtils) MetricsSystem(alluxio.metrics.MetricsSystem) Api(io.swagger.annotations.Api) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) MetricRegistry(com.codahale.metrics.MetricRegistry) MasterWebUIBrowse(alluxio.wire.MasterWebUIBrowse) MasterWebUIWorkers(alluxio.wire.MasterWebUIWorkers) IOException(java.io.IOException) OpenFilePOptions(alluxio.grpc.OpenFilePOptions) UFS_OP_PREFIX(alluxio.metrics.MetricInfo.UFS_OP_PREFIX) File(java.io.File) StorageTierInfo(alluxio.util.webui.StorageTierInfo) URIStatus(alluxio.client.file.URIStatus) TreeMap(java.util.TreeMap) ServletContext(javax.servlet.ServletContext) MasterWebUIMountTable(alluxio.wire.MasterWebUIMountTable) MountTable(alluxio.master.file.meta.MountTable) CommonUtils(alluxio.util.CommonUtils) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) URLDecoder(java.net.URLDecoder) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) FileBlockInfo(alluxio.wire.FileBlockInfo) FileSystemMaster(alluxio.master.file.FileSystemMaster) LogUtils(alluxio.util.LogUtils) UIFileInfo(alluxio.util.webui.UIFileInfo) ApiOperation(io.swagger.annotations.ApiOperation) InvalidPathException(alluxio.exception.InvalidPathException) QueryParam(javax.ws.rs.QueryParam) MasterStorageTierAssoc(alluxio.MasterStorageTierAssoc) ListStatusContext(alluxio.master.file.contexts.ListStatusContext) MetricKey(alluxio.metrics.MetricKey) Counter(com.codahale.metrics.Counter) DefaultValue(javax.ws.rs.DefaultValue) AlluxioMasterInfo(alluxio.wire.AlluxioMasterInfo) MasterWebUIConfiguration(alluxio.wire.MasterWebUIConfiguration) MasterWebUIMetrics(alluxio.wire.MasterWebUIMetrics) Context(javax.ws.rs.core.Context) ServerConfiguration(alluxio.conf.ServerConfiguration) StorageTierAssoc(alluxio.StorageTierAssoc) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) AccessControlException(alluxio.exception.AccessControlException) List(java.util.List) Capacity(alluxio.wire.Capacity) Response(javax.ws.rs.core.Response) SecurityUtils(alluxio.util.SecurityUtils) MasterWebUIOverview(alluxio.wire.MasterWebUIOverview) FileDoesNotExistException(alluxio.exception.FileDoesNotExistException) Gauge(com.codahale.metrics.Gauge) UFS_OP_SAVED_PREFIX(alluxio.metrics.MetricInfo.UFS_OP_SAVED_PREFIX) SortedMap(java.util.SortedMap) UnavailableException(alluxio.exception.status.UnavailableException) MountPointInfo(alluxio.wire.MountPointInfo) NodeInfo(alluxio.util.webui.NodeInfo) GetConfigurationPOptions(alluxio.grpc.GetConfigurationPOptions) WorkerNetAddress(alluxio.wire.WorkerNetAddress) HashMap(java.util.HashMap) NetworkAddressUtils(alluxio.util.network.NetworkAddressUtils) BlockMaster(alluxio.master.block.BlockMaster) PathUtils(alluxio.util.io.PathUtils) Constants(alluxio.Constants) ConfigurationValueOptions(alluxio.conf.ConfigurationValueOptions) AuthenticatedClientUser(alluxio.security.authentication.AuthenticatedClientUser) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) RaftProtos(org.apache.ratis.proto.RaftProtos) MasterWebUIData(alluxio.wire.MasterWebUIData) FileInputStream(java.io.FileInputStream) ConfigurationUtils(alluxio.util.ConfigurationUtils) BlockLocation(alluxio.wire.BlockLocation) MasterWebUILogs(alluxio.wire.MasterWebUILogs) FileInfo(alluxio.wire.FileInfo) DateTimeFormatter(java.time.format.DateTimeFormatter) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Comparator(java.util.Comparator) Collections(java.util.Collections) ConfigCheckReport(alluxio.wire.ConfigCheckReport) InputStream(java.io.InputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FilenameFilter(java.io.FilenameFilter) MasterStorageTierAssoc(alluxio.MasterStorageTierAssoc) MasterWebUILogs(alluxio.wire.MasterWebUILogs) UIFileInfo(alluxio.util.webui.UIFileInfo) File(java.io.File) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 2 with UIFileInfo

use of alluxio.util.webui.UIFileInfo in project alluxio by Alluxio.

the class AlluxioMasterRestServiceHandler method getWebUIBrowse.

/**
 * Gets Web UI browse page data.
 *
 * @param requestPath the request path
 * @param requestOffset the request offset
 * @param requestEnd the request end
 * @param requestLimit the request limit
 * @return the response object
 */
@GET
@Path(WEBUI_BROWSE)
public Response getWebUIBrowse(@DefaultValue("/") @QueryParam("path") String requestPath, @DefaultValue("0") @QueryParam("offset") String requestOffset, @DefaultValue("") @QueryParam("end") String requestEnd, @DefaultValue("20") @QueryParam("limit") String requestLimit) {
    return RestUtils.call(() -> {
        MasterWebUIBrowse response = new MasterWebUIBrowse();
        if (!ServerConfiguration.getBoolean(PropertyKey.WEB_FILE_INFO_ENABLED)) {
            return response;
        }
        if (SecurityUtils.isSecurityEnabled(ServerConfiguration.global()) && AuthenticatedClientUser.get(ServerConfiguration.global()) == null) {
            AuthenticatedClientUser.set(ServerUserState.global().getUser().getName());
        }
        response.setDebug(ServerConfiguration.getBoolean(PropertyKey.DEBUG)).setShowPermissions(ServerConfiguration.getBoolean(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_ENABLED)).setMasterNodeAddress(mMasterProcess.getRpcAddress().toString()).setInvalidPathError("");
        List<FileInfo> filesInfo;
        String path = URLDecoder.decode(requestPath, "UTF-8");
        if (path.isEmpty()) {
            path = AlluxioURI.SEPARATOR;
        }
        AlluxioURI currentPath = new AlluxioURI(path);
        response.setCurrentPath(currentPath.toString()).setViewingOffset(0);
        try {
            long fileId = mFileSystemMaster.getFileId(currentPath);
            FileInfo fileInfo = mFileSystemMaster.getFileInfo(fileId);
            UIFileInfo currentFileInfo = new UIFileInfo(fileInfo, ServerConfiguration.global(), new MasterStorageTierAssoc().getOrderedStorageAliases());
            if (currentFileInfo.getAbsolutePath() == null) {
                throw new FileDoesNotExistException(currentPath.toString());
            }
            response.setCurrentDirectory(currentFileInfo).setBlockSizeBytes(currentFileInfo.getBlockSizeBytes());
            if (!currentFileInfo.getIsDirectory()) {
                long relativeOffset = 0;
                long offset;
                try {
                    if (requestOffset != null) {
                        relativeOffset = Long.parseLong(requestOffset);
                    }
                } catch (NumberFormatException e) {
                // ignore the exception
                }
                // relative to the end of the file.
                if (requestEnd.equals("")) {
                    offset = relativeOffset;
                } else {
                    offset = fileInfo.getLength() - relativeOffset;
                }
                if (offset < 0) {
                    offset = 0;
                } else if (offset > fileInfo.getLength()) {
                    offset = fileInfo.getLength();
                }
                try {
                    AlluxioURI absolutePath = new AlluxioURI(currentFileInfo.getAbsolutePath());
                    FileSystem fs = mFsClient;
                    String fileData;
                    URIStatus status = fs.getStatus(absolutePath);
                    if (status.isCompleted()) {
                        OpenFilePOptions options = OpenFilePOptions.newBuilder().setReadType(ReadPType.NO_CACHE).build();
                        try (FileInStream is = fs.openFile(absolutePath, options)) {
                            int len = (int) Math.min(5L * Constants.KB, status.getLength() - offset);
                            byte[] data = new byte[len];
                            long skipped = is.skip(offset);
                            if (skipped < 0) {
                                // nothing was skipped
                                fileData = "Unable to traverse to offset; is file empty?";
                            } else if (skipped < offset) {
                                // couldn't skip all the way to offset
                                fileData = "Unable to traverse to offset; is offset larger than the file?";
                            } else {
                                // read may not read up to len, so only convert what was read
                                int read = is.read(data, 0, len);
                                if (read < 0) {
                                    // stream couldn't read anything, skip went to EOF?
                                    fileData = "Unable to read file";
                                } else {
                                    fileData = WebUtils.convertByteArrayToStringWithoutEscape(data, 0, read);
                                }
                            }
                        }
                    } else {
                        fileData = "The requested file is not complete yet.";
                    }
                    List<UIFileBlockInfo> uiBlockInfo = new ArrayList<>();
                    for (FileBlockInfo fileBlockInfo : mFileSystemMaster.getFileBlockInfoList(absolutePath)) {
                        uiBlockInfo.add(new UIFileBlockInfo(fileBlockInfo, ServerConfiguration.global()));
                    }
                    response.setFileBlocks(uiBlockInfo).setFileData(fileData).setHighestTierAlias(mBlockMaster.getGlobalStorageTierAssoc().getAlias(0));
                } catch (AlluxioException e) {
                    throw new IOException(e);
                }
                response.setViewingOffset(offset);
                return response;
            }
            if (currentPath.isRoot()) {
                response.setPathInfos(new UIFileInfo[0]);
            } else {
                String[] splitPath = PathUtils.getPathComponents(currentPath.toString());
                UIFileInfo[] pathInfos = new UIFileInfo[splitPath.length - 1];
                fileId = mFileSystemMaster.getFileId(currentPath);
                pathInfos[0] = new UIFileInfo(mFileSystemMaster.getFileInfo(fileId), ServerConfiguration.global(), new MasterStorageTierAssoc().getOrderedStorageAliases());
                AlluxioURI breadcrumb = new AlluxioURI(AlluxioURI.SEPARATOR);
                for (int i = 1; i < splitPath.length - 1; i++) {
                    breadcrumb = breadcrumb.join(splitPath[i]);
                    fileId = mFileSystemMaster.getFileId(breadcrumb);
                    pathInfos[i] = new UIFileInfo(mFileSystemMaster.getFileInfo(fileId), ServerConfiguration.global(), new MasterStorageTierAssoc().getOrderedStorageAliases());
                }
                response.setPathInfos(pathInfos);
            }
            filesInfo = mFileSystemMaster.listStatus(currentPath, ListStatusContext.defaults());
        } catch (FileDoesNotExistException e) {
            response.setInvalidPathError("Error: Invalid Path " + e.getMessage());
            return response;
        } catch (InvalidPathException e) {
            response.setInvalidPathError("Error: Invalid Path " + e.getLocalizedMessage());
            return response;
        } catch (UnavailableException e) {
            response.setInvalidPathError("The service is temporarily unavailable. " + e.getMessage());
            return response;
        } catch (IOException e) {
            response.setInvalidPathError("Error: File " + currentPath + " is not available " + e.getMessage());
            return response;
        } catch (AccessControlException e) {
            response.setInvalidPathError("Error: File " + currentPath + " cannot be accessed " + e.getMessage());
            return response;
        }
        List<UIFileInfo> fileInfos = new ArrayList<>(filesInfo.size());
        for (FileInfo fileInfo : filesInfo) {
            UIFileInfo toAdd = new UIFileInfo(fileInfo, ServerConfiguration.global(), new MasterStorageTierAssoc().getOrderedStorageAliases());
            try {
                if (!toAdd.getIsDirectory() && fileInfo.getLength() > 0) {
                    FileBlockInfo blockInfo = mFileSystemMaster.getFileBlockInfoList(new AlluxioURI(toAdd.getAbsolutePath())).get(0);
                    List<String> locations = new ArrayList<>();
                    // add the in-Alluxio block locations
                    for (BlockLocation location : blockInfo.getBlockInfo().getLocations()) {
                        WorkerNetAddress address = location.getWorkerAddress();
                        locations.add(address.getHost() + ":" + address.getDataPort());
                    }
                    // add underFS locations
                    locations.addAll(blockInfo.getUfsLocations());
                    toAdd.setFileLocations(locations);
                }
            } catch (FileDoesNotExistException e) {
                response.setFileDoesNotExistException("Error: non-existing file " + e.getMessage());
                return response;
            } catch (InvalidPathException e) {
                response.setInvalidPathException("Error: invalid path " + e.getMessage());
                return response;
            } catch (AccessControlException e) {
                response.setAccessControlException("Error: File " + currentPath + " cannot be accessed " + e.getMessage());
                return response;
            }
            fileInfos.add(toAdd);
        }
        fileInfos.sort(UIFileInfo.PATH_STRING_COMPARE);
        response.setNTotalFile(fileInfos.size());
        try {
            int offset = Integer.parseInt(requestOffset);
            int limit = Integer.parseInt(requestLimit);
            limit = offset == 0 && limit > fileInfos.size() ? fileInfos.size() : limit;
            limit = offset + limit > fileInfos.size() ? fileInfos.size() - offset : limit;
            int sum = Math.addExact(offset, limit);
            fileInfos = fileInfos.subList(offset, sum);
            response.setFileInfos(fileInfos);
        } catch (NumberFormatException e) {
            response.setFatalError("Error: offset or limit parse error, " + e.getLocalizedMessage());
            return response;
        } catch (ArithmeticException e) {
            response.setFatalError("Error: offset or offset + limit is out of bound, " + e.getLocalizedMessage());
            return response;
        } catch (IllegalArgumentException e) {
            response.setFatalError(e.getLocalizedMessage());
            return response;
        }
        return response;
    }, ServerConfiguration.global());
}
Also used : FileDoesNotExistException(alluxio.exception.FileDoesNotExistException) ArrayList(java.util.ArrayList) UnavailableException(alluxio.exception.status.UnavailableException) UIFileBlockInfo(alluxio.util.webui.UIFileBlockInfo) FileBlockInfo(alluxio.wire.FileBlockInfo) BlockLocation(alluxio.wire.BlockLocation) InvalidPathException(alluxio.exception.InvalidPathException) MasterWebUIBrowse(alluxio.wire.MasterWebUIBrowse) UIFileInfo(alluxio.util.webui.UIFileInfo) FileInfo(alluxio.wire.FileInfo) FileSystem(alluxio.client.file.FileSystem) UIFileInfo(alluxio.util.webui.UIFileInfo) AlluxioException(alluxio.exception.AlluxioException) UIFileBlockInfo(alluxio.util.webui.UIFileBlockInfo) AccessControlException(alluxio.exception.AccessControlException) IOException(java.io.IOException) URIStatus(alluxio.client.file.URIStatus) MasterStorageTierAssoc(alluxio.MasterStorageTierAssoc) WorkerNetAddress(alluxio.wire.WorkerNetAddress) FileInStream(alluxio.client.file.FileInStream) OpenFilePOptions(alluxio.grpc.OpenFilePOptions) AlluxioURI(alluxio.AlluxioURI) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 3 with UIFileInfo

use of alluxio.util.webui.UIFileInfo in project alluxio by Alluxio.

the class AlluxioWorkerRestServiceHandler method getWebUIBlockInfo.

/**
 * Gets web ui block info page data.
 *
 * @param requestPath the request path
 * @param requestOffset the request offset
 * @param requestLimit the request limit
 * @return the response object
 */
@GET
@Path(WEBUI_BLOCKINFO)
public Response getWebUIBlockInfo(@QueryParam("path") String requestPath, @DefaultValue("0") @QueryParam("offset") String requestOffset, @DefaultValue("20") @QueryParam("limit") String requestLimit) {
    return RestUtils.call(() -> {
        WorkerWebUIBlockInfo response = new WorkerWebUIBlockInfo();
        if (!ServerConfiguration.getBoolean(PropertyKey.WEB_FILE_INFO_ENABLED)) {
            return response;
        }
        response.setFatalError("").setInvalidPathError("");
        if (!(requestPath == null || requestPath.isEmpty())) {
            // Display file block info
            try {
                URIStatus status = mFsClient.getStatus(new AlluxioURI(requestPath));
                UIFileInfo uiFileInfo = new UIFileInfo(status, ServerConfiguration.global(), new WorkerStorageTierAssoc().getOrderedStorageAliases());
                for (long blockId : status.getBlockIds()) {
                    if (mBlockWorker.hasBlockMeta(blockId)) {
                        BlockMeta blockMeta = mBlockWorker.getVolatileBlockMeta(blockId);
                        long blockSize = blockMeta.getBlockSize();
                        // The block last access time is not available. Use -1 for now.
                        // It's not necessary to show location information here since
                        // we are viewing at the context of this worker.
                        uiFileInfo.addBlock(blockMeta.getBlockLocation().tierAlias(), blockId, blockSize, -1);
                    }
                }
                List<ImmutablePair<String, List<UIFileBlockInfo>>> fileBlocksOnTier = new ArrayList<>();
                for (Map.Entry<String, List<UIFileBlockInfo>> e : uiFileInfo.getBlocksOnTier().entrySet()) {
                    fileBlocksOnTier.add(new ImmutablePair<>(e.getKey(), e.getValue()));
                }
                response.setFileBlocksOnTier(fileBlocksOnTier).setBlockSizeBytes(uiFileInfo.getBlockSizeBytes()).setPath(requestPath);
            } catch (FileDoesNotExistException e) {
                response.setFatalError("Error: Invalid Path " + e.getMessage());
            } catch (IOException e) {
                response.setInvalidPathError("Error: File " + requestPath + " is not available " + e.getMessage());
            } catch (BlockDoesNotExistException e) {
                response.setFatalError("Error: block not found. " + e.getMessage());
            } catch (AlluxioException e) {
                response.setFatalError("Error: alluxio exception. " + e.getMessage());
            }
        }
        Set<Long> unsortedFileIds = new HashSet<>();
        BlockStoreMeta storeMeta = mBlockWorker.getStoreMetaFull();
        for (List<Long> blockIds : storeMeta.getBlockList().values()) {
            for (long blockId : blockIds) {
                unsortedFileIds.add(BlockId.getFileId(blockId));
            }
        }
        List<Long> fileIds = new ArrayList<>(unsortedFileIds);
        Collections.sort(fileIds);
        response.setNTotalFile(unsortedFileIds.size()).setOrderedTierAliases(new WorkerStorageTierAssoc().getOrderedStorageAliases());
        try {
            int offset = Integer.parseInt(requestOffset);
            int limit = Integer.parseInt(requestLimit);
            // make the limit the total number of files if request limit is > than what is available
            limit = offset == 0 && limit > fileIds.size() ? fileIds.size() : limit;
            // offset+limit can't be greater than the size of the list
            limit = offset + limit > fileIds.size() ? fileIds.size() - offset : limit;
            int sum = Math.addExact(offset, limit);
            List<Long> subFileIds = fileIds.subList(offset, sum);
            List<UIFileInfo> uiFileInfos = new ArrayList<>(subFileIds.size());
            for (long fileId : subFileIds) {
                try {
                    URIStatus status = new URIStatus(mBlockWorker.getFileInfo(fileId));
                    UIFileInfo uiFileInfo = new UIFileInfo(status, ServerConfiguration.global(), new WorkerStorageTierAssoc().getOrderedStorageAliases());
                    for (long blockId : status.getBlockIds()) {
                        if (mBlockWorker.hasBlockMeta(blockId)) {
                            BlockMeta blockMeta = mBlockWorker.getVolatileBlockMeta(blockId);
                            long blockSize = blockMeta.getBlockSize();
                            // The block last access time is not available. Use -1 for now.
                            // It's not necessary to show location information here since
                            // we are viewing at the context of this worker.
                            uiFileInfo.addBlock(blockMeta.getBlockLocation().tierAlias(), blockId, blockSize, -1);
                        }
                    }
                    if (!uiFileInfo.getBlockIds().isEmpty()) {
                        uiFileInfos.add(uiFileInfo);
                    }
                } catch (Exception e) {
                    // The file might have been deleted, log a warning and ignore this file.
                    LOG.warn("Unable to get file info for fileId {}. {}", fileId, e.toString());
                }
            }
            response.setFileInfos(uiFileInfos);
        } catch (NumberFormatException e) {
            response.setFatalError("Error: offset or limit parse error, " + e.getLocalizedMessage());
        } catch (ArithmeticException e) {
            response.setFatalError("Error: offset or offset + limit is out ofbound, " + e.getLocalizedMessage());
        } catch (Exception e) {
            response.setFatalError(e.getLocalizedMessage());
        }
        return response;
    }, ServerConfiguration.global());
}
Also used : FileDoesNotExistException(alluxio.exception.FileDoesNotExistException) ArrayList(java.util.ArrayList) UIFileInfo(alluxio.util.webui.UIFileInfo) List(java.util.List) ArrayList(java.util.ArrayList) BlockDoesNotExistException(alluxio.exception.BlockDoesNotExistException) AlluxioException(alluxio.exception.AlluxioException) HashSet(java.util.HashSet) UIFileBlockInfo(alluxio.util.webui.UIFileBlockInfo) WorkerWebUIBlockInfo(alluxio.wire.WorkerWebUIBlockInfo) WorkerStorageTierAssoc(alluxio.WorkerStorageTierAssoc) IOException(java.io.IOException) URIStatus(alluxio.client.file.URIStatus) AlluxioException(alluxio.exception.AlluxioException) FileDoesNotExistException(alluxio.exception.FileDoesNotExistException) IOException(java.io.IOException) BlockDoesNotExistException(alluxio.exception.BlockDoesNotExistException) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) BlockMeta(alluxio.worker.block.meta.BlockMeta) Map(java.util.Map) SortedMap(java.util.SortedMap) TreeMap(java.util.TreeMap) BlockStoreMeta(alluxio.worker.block.BlockStoreMeta) AlluxioURI(alluxio.AlluxioURI) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 4 with UIFileInfo

use of alluxio.util.webui.UIFileInfo in project alluxio by Alluxio.

the class AlluxioWorkerRestServiceHandler method getWebUILogs.

/**
 * Gets web ui logs page data.
 *
 * @param requestPath the request path
 * @param requestOffset the request offset
 * @param requestEnd the request end
 * @param requestLimit the request limit
 * @return the response object
 */
@GET
@Path(WEBUI_LOGS)
public Response getWebUILogs(@DefaultValue("") @QueryParam("path") String requestPath, @DefaultValue("0") @QueryParam("offset") String requestOffset, @QueryParam("end") String requestEnd, @DefaultValue("20") @QueryParam("limit") String requestLimit) {
    return RestUtils.call(() -> {
        FilenameFilter filenameFilter = (dir, name) -> name.toLowerCase().endsWith(".log");
        WorkerWebUILogs response = new WorkerWebUILogs();
        if (!ServerConfiguration.getBoolean(PropertyKey.WEB_FILE_INFO_ENABLED)) {
            return response;
        }
        response.setDebug(ServerConfiguration.getBoolean(PropertyKey.DEBUG)).setInvalidPathError("").setViewingOffset(0).setCurrentPath("");
        // response.setDownloadLogFile(1);
        // response.setBaseUrl("./browseLogs");
        // response.setShowPermissions(false);
        String logsPath = ServerConfiguration.getString(PropertyKey.LOGS_DIR);
        File logsDir = new File(logsPath);
        String requestFile = requestPath;
        if (requestFile == null || requestFile.isEmpty()) {
            // List all log files in the log/ directory.
            List<UIFileInfo> fileInfos = new ArrayList<>();
            File[] logFiles = logsDir.listFiles(filenameFilter);
            if (logFiles != null) {
                for (File logFile : logFiles) {
                    String logFileName = logFile.getName();
                    fileInfos.add(new UIFileInfo(new UIFileInfo.LocalFileInfo(logFileName, logFileName, logFile.length(), UIFileInfo.LocalFileInfo.EMPTY_CREATION_TIME, logFile.lastModified(), logFile.isDirectory()), ServerConfiguration.global(), new WorkerStorageTierAssoc().getOrderedStorageAliases()));
                }
            }
            Collections.sort(fileInfos, UIFileInfo.PATH_STRING_COMPARE);
            response.setNTotalFile(fileInfos.size());
            try {
                int offset = Integer.parseInt(requestOffset);
                int limit = Integer.parseInt(requestLimit);
                limit = offset == 0 && limit > fileInfos.size() ? fileInfos.size() : limit;
                limit = offset + limit > fileInfos.size() ? fileInfos.size() - offset : limit;
                int sum = Math.addExact(offset, limit);
                fileInfos = fileInfos.subList(offset, sum);
                response.setFileInfos(fileInfos);
            } catch (NumberFormatException e) {
                response.setFatalError("Error: offset or limit parse error, " + e.getLocalizedMessage());
                return response;
            } catch (ArithmeticException e) {
                response.setFatalError("Error: offset or offset + limit is out of bound, " + e.getLocalizedMessage());
                return response;
            } catch (IllegalArgumentException e) {
                response.setFatalError(e.getLocalizedMessage());
                return response;
            }
        } else {
            // Request a specific log file.
            // Only allow filenames as the path, to avoid arbitrary local path lookups.
            requestFile = new File(requestFile).getName();
            response.setCurrentPath(requestFile);
            File logFile = new File(logsDir, requestFile);
            try {
                long fileSize = logFile.length();
                String offsetParam = requestOffset;
                long relativeOffset = 0;
                long offset;
                try {
                    if (offsetParam != null) {
                        relativeOffset = Long.parseLong(offsetParam);
                    }
                } catch (NumberFormatException e) {
                    relativeOffset = 0;
                }
                String endParam = requestEnd;
                // relative to the end of the file.
                if (endParam == null) {
                    offset = relativeOffset;
                } else {
                    offset = fileSize - relativeOffset;
                }
                if (offset < 0) {
                    offset = 0;
                } else if (offset > fileSize) {
                    offset = fileSize;
                }
                String fileData;
                try (InputStream is = new FileInputStream(logFile)) {
                    fileSize = logFile.length();
                    int len = (int) Math.min(5L * Constants.KB, fileSize - offset);
                    byte[] data = new byte[len];
                    long skipped = is.skip(offset);
                    if (skipped < 0) {
                        // Nothing was skipped.
                        fileData = "Unable to traverse to offset; is file empty?";
                    } else if (skipped < offset) {
                        // Couldn't skip all the way to offset.
                        fileData = "Unable to traverse to offset; is offset larger than the file?";
                    } else {
                        // Read may not read up to len, so only convert what was read.
                        int read = is.read(data, 0, len);
                        if (read < 0) {
                            // Stream couldn't read anything, skip went to EOF?
                            fileData = "Unable to read file";
                        } else {
                            fileData = WebUtils.convertByteArrayToStringWithoutEscape(data, 0, read);
                        }
                    }
                }
                response.setFileData(fileData).setViewingOffset(offset);
            } catch (IOException e) {
                response.setInvalidPathError("Error: File " + logFile + " is not available " + e.getMessage());
            }
        }
        return response;
    }, ServerConfiguration.global());
}
Also used : Produces(javax.ws.rs.Produces) LoggerFactory(org.slf4j.LoggerFactory) Path(javax.ws.rs.Path) WorkerWebUIMetrics(alluxio.wire.WorkerWebUIMetrics) PropertyKey(alluxio.conf.PropertyKey) LogUtils(alluxio.util.LogUtils) UIFileInfo(alluxio.util.webui.UIFileInfo) ApiOperation(io.swagger.annotations.ApiOperation) MediaType(javax.ws.rs.core.MediaType) FileSystem(alluxio.client.file.FileSystem) QueryParam(javax.ws.rs.QueryParam) WorkerWebUIBlockInfo(alluxio.wire.WorkerWebUIBlockInfo) MetricKey(alluxio.metrics.MetricKey) Map(java.util.Map) Counter(com.codahale.metrics.Counter) DefaultValue(javax.ws.rs.DefaultValue) WebUtils(alluxio.util.webui.WebUtils) Triple(org.apache.commons.lang3.tuple.Triple) WorkerWebUILogs(alluxio.wire.WorkerWebUILogs) Context(javax.ws.rs.core.Context) RestUtils(alluxio.RestUtils) ServerConfiguration(alluxio.conf.ServerConfiguration) WorkerWebUIConfiguration(alluxio.wire.WorkerWebUIConfiguration) Metric(com.codahale.metrics.Metric) Set(java.util.Set) AlluxioException(alluxio.exception.AlluxioException) ConfigProperty(alluxio.grpc.ConfigProperty) Sets(com.google.common.collect.Sets) List(java.util.List) Capacity(alluxio.wire.Capacity) Response(javax.ws.rs.core.Response) UIFileBlockInfo(alluxio.util.webui.UIFileBlockInfo) FileDoesNotExistException(alluxio.exception.FileDoesNotExistException) UIStorageDir(alluxio.util.webui.UIStorageDir) WorkerWebServer(alluxio.web.WorkerWebServer) BlockStoreMeta(alluxio.worker.block.BlockStoreMeta) Gauge(com.codahale.metrics.Gauge) RuntimeConstants(alluxio.RuntimeConstants) SortedMap(java.util.SortedMap) BlockWorker(alluxio.worker.block.BlockWorker) FilenameFilter(java.io.FilenameFilter) GET(javax.ws.rs.GET) GetConfigurationPOptions(alluxio.grpc.GetConfigurationPOptions) WorkerWebUIInit(alluxio.wire.WorkerWebUIInit) BlockId(alluxio.master.block.BlockId) NetworkAddressUtils(alluxio.util.network.NetworkAddressUtils) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Constants(alluxio.Constants) AlluxioURI(alluxio.AlluxioURI) FormatUtils(alluxio.util.FormatUtils) MetricsSystem(alluxio.metrics.MetricsSystem) Api(io.swagger.annotations.Api) ConfigurationValueOptions(alluxio.conf.ConfigurationValueOptions) ImmutableTriple(org.apache.commons.lang3.tuple.ImmutableTriple) MetricRegistry(com.codahale.metrics.MetricRegistry) Logger(org.slf4j.Logger) POST(javax.ws.rs.POST) UIUsageOnTier(alluxio.util.webui.UIUsageOnTier) AlluxioWorkerInfo(alluxio.wire.AlluxioWorkerInfo) IOException(java.io.IOException) BlockMeta(alluxio.worker.block.meta.BlockMeta) FileInputStream(java.io.FileInputStream) Pair(alluxio.collections.Pair) ConfigurationUtils(alluxio.util.ConfigurationUtils) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) File(java.io.File) URIStatus(alluxio.client.file.URIStatus) TreeMap(java.util.TreeMap) UIWorkerInfo(alluxio.util.webui.UIWorkerInfo) ServletContext(javax.servlet.ServletContext) WorkerStorageTierAssoc(alluxio.WorkerStorageTierAssoc) WorkerWebUIOverview(alluxio.wire.WorkerWebUIOverview) Comparator(java.util.Comparator) BlockDoesNotExistException(alluxio.exception.BlockDoesNotExistException) Collections(java.util.Collections) InputStream(java.io.InputStream) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) WorkerStorageTierAssoc(alluxio.WorkerStorageTierAssoc) WorkerWebUILogs(alluxio.wire.WorkerWebUILogs) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FilenameFilter(java.io.FilenameFilter) UIFileInfo(alluxio.util.webui.UIFileInfo) File(java.io.File) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 5 with UIFileInfo

use of alluxio.util.webui.UIFileInfo in project alluxio by Alluxio.

the class AlluxioMasterRestServiceHandler method getWebUIData.

/**
 * Gets Web UI data page data.
 *
 * @param requestOffset the request offset
 * @param requestLimit the request limit
 * @return the response object
 */
@GET
@Path(WEBUI_DATA)
public Response getWebUIData(@DefaultValue("0") @QueryParam("offset") String requestOffset, @DefaultValue("20") @QueryParam("limit") String requestLimit) {
    return RestUtils.call(() -> {
        MasterWebUIData response = new MasterWebUIData();
        if (!ServerConfiguration.getBoolean(PropertyKey.WEB_FILE_INFO_ENABLED)) {
            return response;
        }
        if (SecurityUtils.isSecurityEnabled(ServerConfiguration.global()) && AuthenticatedClientUser.get(ServerConfiguration.global()) == null) {
            AuthenticatedClientUser.set(ServerUserState.global().getUser().getName());
        }
        response.setMasterNodeAddress(mMasterProcess.getRpcAddress().toString()).setFatalError("").setShowPermissions(ServerConfiguration.getBoolean(PropertyKey.SECURITY_AUTHORIZATION_PERMISSION_ENABLED));
        List<AlluxioURI> inAlluxioFiles = mFileSystemMaster.getInAlluxioFiles();
        Collections.sort(inAlluxioFiles);
        List<UIFileInfo> fileInfos = new ArrayList<>(inAlluxioFiles.size());
        for (AlluxioURI file : inAlluxioFiles) {
            try {
                long fileId = mFileSystemMaster.getFileId(file);
                FileInfo fileInfo = mFileSystemMaster.getFileInfo(fileId);
                if (fileInfo != null && fileInfo.getInAlluxioPercentage() == 100) {
                    fileInfos.add(new UIFileInfo(fileInfo, ServerConfiguration.global(), new MasterStorageTierAssoc().getOrderedStorageAliases()));
                }
            } catch (FileDoesNotExistException e) {
                response.setFatalError("Error: File does not exist " + e.getLocalizedMessage());
                return response;
            } catch (AccessControlException e) {
                response.setPermissionError("Error: File " + file + " cannot be accessed " + e.getMessage());
                return response;
            }
        }
        response.setInAlluxioFileNum(fileInfos.size());
        try {
            int offset = Integer.parseInt(requestOffset);
            int limit = Integer.parseInt(requestLimit);
            limit = offset == 0 && limit > fileInfos.size() ? fileInfos.size() : limit;
            limit = offset + limit > fileInfos.size() ? fileInfos.size() - offset : limit;
            int sum = Math.addExact(offset, limit);
            fileInfos = fileInfos.subList(offset, sum);
            response.setFileInfos(fileInfos);
        } catch (NumberFormatException e) {
            response.setFatalError("Error: offset or limit parse error, " + e.getLocalizedMessage());
            return response;
        } catch (ArithmeticException e) {
            response.setFatalError("Error: offset or offset + limit is out of bound, " + e.getLocalizedMessage());
            return response;
        } catch (IllegalArgumentException e) {
            response.setFatalError(e.getLocalizedMessage());
            return response;
        }
        return response;
    }, ServerConfiguration.global());
}
Also used : FileDoesNotExistException(alluxio.exception.FileDoesNotExistException) ArrayList(java.util.ArrayList) AccessControlException(alluxio.exception.AccessControlException) MasterWebUIData(alluxio.wire.MasterWebUIData) MasterStorageTierAssoc(alluxio.MasterStorageTierAssoc) UIFileInfo(alluxio.util.webui.UIFileInfo) FileInfo(alluxio.wire.FileInfo) UIFileInfo(alluxio.util.webui.UIFileInfo) AlluxioURI(alluxio.AlluxioURI) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Aggregations

AlluxioURI (alluxio.AlluxioURI)5 FileDoesNotExistException (alluxio.exception.FileDoesNotExistException)5 UIFileInfo (alluxio.util.webui.UIFileInfo)5 ArrayList (java.util.ArrayList)5 GET (javax.ws.rs.GET)5 Path (javax.ws.rs.Path)5 URIStatus (alluxio.client.file.URIStatus)4 AlluxioException (alluxio.exception.AlluxioException)4 UIFileBlockInfo (alluxio.util.webui.UIFileBlockInfo)4 MasterStorageTierAssoc (alluxio.MasterStorageTierAssoc)3 FileSystem (alluxio.client.file.FileSystem)3 AccessControlException (alluxio.exception.AccessControlException)3 FileInfo (alluxio.wire.FileInfo)3 IOException (java.io.IOException)3 Constants (alluxio.Constants)2 RestUtils (alluxio.RestUtils)2 RuntimeConstants (alluxio.RuntimeConstants)2 WorkerStorageTierAssoc (alluxio.WorkerStorageTierAssoc)2 FileInStream (alluxio.client.file.FileInStream)2 ConfigurationValueOptions (alluxio.conf.ConfigurationValueOptions)2