Search in sources :

Example 51 with NoRouteToCellException

use of dmg.cells.nucleus.NoRouteToCellException in project dcache by dCache.

the class DCacheAwareJdbcFs method pin.

/**
 * This method sends a request to the pin manager to pin a given file.
 */
@Override
public void pin(FsInode inode, long lifetime) throws ChimeraFsException {
    Subject subject = getSubjectFromContext();
    InetAddress client = Subjects.getOrigin(subject).getAddress();
    ProtocolInfo protocolInfo = new DCapProtocolInfo("DCap", 3, 0, new InetSocketAddress(client, 0));
    try {
        PinManagerPinMessage message = new PinManagerPinMessage(FileAttributes.ofPnfsId(inode.getId()), protocolInfo, getRequestId(subject), lifetime);
        message.setSubject(subject);
        message.setReplyWhenStarted(true);
        pinManagerStub.sendAndWait(message);
    } catch (NoRouteToCellException | InterruptedException | CacheException e) {
        /* We "notify" the client that there was a problem pinning the
             * the file by returning NFSERR_INVAL back to the client.  The Linux
             * kernel should convert this to an EINVAL response; e.g.,
             *
             *     paul@sprocket:/mnt/tape$ touch ".(fset)(test.dat)(pin)(60)"
             *     touch: setting times of '.(fset)(test.dat)(pin)(60)': Invalid argument
             */
        throw new InvalidArgumentChimeraException(e.getMessage());
    }
}
Also used : DCapProtocolInfo(diskCacheV111.vehicles.DCapProtocolInfo) CacheException(diskCacheV111.util.CacheException) PermissionDeniedCacheException(diskCacheV111.util.PermissionDeniedCacheException) InetSocketAddress(java.net.InetSocketAddress) NoRouteToCellException(dmg.cells.nucleus.NoRouteToCellException) ProtocolInfo(diskCacheV111.vehicles.ProtocolInfo) DCapProtocolInfo(diskCacheV111.vehicles.DCapProtocolInfo) PinManagerPinMessage(org.dcache.pinmanager.PinManagerPinMessage) InetAddress(java.net.InetAddress) Subject(javax.security.auth.Subject)

Example 52 with NoRouteToCellException

use of dmg.cells.nucleus.NoRouteToCellException in project dcache by dCache.

the class CellStub method addCallback.

/**
 * Registers a callback to be run when the {@code Future}'s computation is {@linkplain
 * java.util.concurrent.Future#isDone() complete} or, if the computation is already complete,
 * immediately.
 *
 * <p>There is no guaranteed ordering of execution of callbacks, but any
 * callback added through this method is guaranteed to be called once the computation is
 * complete.
 *
 * <p>Note: For fast, lightweight listeners that would be safe to execute in
 * any thread, consider {@link MoreExecutors#directExecutor}. For heavier listeners, {@code
 * directExecutor()} carries some caveats. See {@link ListenableFuture#addListener} for
 * details.
 *
 * <p>In is important the the executor isn't blocked by tasks waiting for
 * the callback; such tasks could lead to a deadlock.
 *
 * <p>If not using {@code directExecutor()}, it is advisable to use a
 * CDC preserving executor.
 *
 * @param future   The future attach the callback to.
 * @param callback The callback to invoke when {@code future} is completed.
 * @param executor The executor to run {@code callback} when the future completes.
 * @see com.google.common.util.concurrent.Futures#addCallback
 * @see ListenableFuture#addListener
 */
public static <T extends Message> void addCallback(final ListenableFuture<T> future, final MessageCallback<? super T> callback, Executor executor) {
    future.addListener(() -> {
        try {
            T reply = getUninterruptibly(future);
            callback.setReply(reply);
            if (reply.getReturnCode() != 0) {
                callback.failure(reply.getReturnCode(), reply.getErrorObject());
            } else {
                callback.success();
            }
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause instanceof TimeoutCacheException) {
                callback.timeout(cause.getMessage());
            } else if (cause instanceof CacheException) {
                CacheException cacheException = (CacheException) cause;
                callback.failure(cacheException.getRc(), cacheException.getMessage());
            } else if (cause instanceof NoRouteToCellException) {
                callback.noroute(((NoRouteToCellException) cause).getDestinationPath());
            } else {
                callback.failure(CacheException.UNEXPECTED_SYSTEM_EXCEPTION, cause);
            }
        }
    }, executor);
}
Also used : CacheException(diskCacheV111.util.CacheException) TimeoutCacheException(diskCacheV111.util.TimeoutCacheException) NoRouteToCellException(dmg.cells.nucleus.NoRouteToCellException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutCacheException(diskCacheV111.util.TimeoutCacheException)

Example 53 with NoRouteToCellException

use of dmg.cells.nucleus.NoRouteToCellException in project dcache by dCache.

the class CredentialServiceClient method getDelegatedCredential.

public X509Credential getDelegatedCredential(String dn, String primaryFqan, int minimumValidity, TimeUnit units) throws InterruptedException, ErrorResponseException {
    Instant deadline = Instant.now().plus(Duration.ofMillis(units.toMillis(minimumValidity)));
    Optional<X509Credential> bestCredential = Optional.empty();
    Optional<Instant> bestExpiry = Optional.empty();
    for (CellAddressCore address : cache.asMap().keySet()) {
        CellPath path = new CellPath(address);
        SrmRequestCredentialMessage msg = new SrmRequestCredentialMessage(dn, primaryFqan);
        try {
            msg = topic.sendAndWait(path, msg);
            if (msg.hasCredential()) {
                X509Credential credential = new KeyAndCertCredential(msg.getPrivateKey(), msg.getCertificateChain());
                Optional<Instant> expiry = X509Credentials.calculateExpiry(credential);
                if (!bestExpiry.isPresent() || (expiry.isPresent() && expiry.get().isAfter(bestExpiry.get()))) {
                    bestExpiry = expiry;
                    bestCredential = Optional.of(credential);
                }
            }
        } catch (CacheException | NoRouteToCellException e) {
            LOGGER.debug("failed to contact {} querying for {}, {}: {}", path, dn, primaryFqan, e.getMessage());
        } catch (KeyStoreException e) {
            LOGGER.warn("Received invalid key pair from {} for {}, {}: {}", path, dn, primaryFqan, e.getMessage());
        }
    }
    if (bestExpiry.isPresent() && bestExpiry.get().isBefore(deadline)) {
        bestCredential = Optional.empty();
    }
    return bestCredential.orElse(null);
}
Also used : CellPath(dmg.cells.nucleus.CellPath) CellAddressCore(dmg.cells.nucleus.CellAddressCore) X509Credential(eu.emi.security.authn.x509.X509Credential) CacheException(diskCacheV111.util.CacheException) Instant(java.time.Instant) NoRouteToCellException(dmg.cells.nucleus.NoRouteToCellException) KeyAndCertCredential(eu.emi.security.authn.x509.impl.KeyAndCertCredential) SrmRequestCredentialMessage(diskCacheV111.srm.dcache.SrmRequestCredentialMessage) KeyStoreException(java.security.KeyStoreException)

Example 54 with NoRouteToCellException

use of dmg.cells.nucleus.NoRouteToCellException in project dcache by dCache.

the class BillingResources method getRestores.

@GET
@ApiOperation("Provide a list of tape reads for a specific PNFS-ID.")
@ApiResponses({ @ApiResponse(code = 400, message = "Bad request"), @ApiResponse(code = 403, message = "restore records are only available to admin users."), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal Server Error") })
@Produces(MediaType.APPLICATION_JSON)
@Path("restores/{pnfsid}")
public List<HSMTransferRecord> getRestores(@ApiParam("The file to list.") @PathParam("pnfsid") PnfsId pnfsid, @ApiParam("Return no tape reads after this datestamp.") @QueryParam("before") String before, @ApiParam("Return no tape reads before this datestamp.") @QueryParam("after") String after, @ApiParam("Maximum number of tape reads to return.") @QueryParam("limit") Integer limit, @ApiParam("Number of tape reads to skip.") @DefaultValue("0") @QueryParam("offset") int offset, @ApiParam("Only select tape reads involving the specified pool.") @QueryParam("pool") String pool, @ApiParam("How to sort responses.") @DefaultValue("date") @QueryParam("sort") String sort) {
    if (!RequestUser.canViewFileOperations(unlimitedOperationVisibility)) {
        throw new ForbiddenException("Restore records are only available to admin users.");
    }
    try {
        limit = limit == null ? Integer.MAX_VALUE : limit;
        PagedList<HSMTransferRecord> result = service.getRestores(pnfsid, before, after, limit, offset, pool, sort);
        response.addIntHeader(TOTAL_COUNT_HEADER, result.total);
        return result.contents;
    } catch (FileNotFoundCacheException e) {
        throw new NotFoundException(e);
    } catch (NoRouteToCellException | InterruptedException | CacheException e) {
        LOGGER.warn(Exceptions.meaningfulMessage(e));
        throw new InternalServerErrorException(e);
    } catch (IllegalArgumentException | ParseException e) {
        throw new BadRequestException(e.getMessage(), e);
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) CacheException(diskCacheV111.util.CacheException) FileNotFoundCacheException(diskCacheV111.util.FileNotFoundCacheException) NotFoundException(javax.ws.rs.NotFoundException) HSMTransferRecord(org.dcache.restful.providers.billing.HSMTransferRecord) NoRouteToCellException(dmg.cells.nucleus.NoRouteToCellException) FileNotFoundCacheException(diskCacheV111.util.FileNotFoundCacheException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) BadRequestException(javax.ws.rs.BadRequestException) ParseException(java.text.ParseException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 55 with NoRouteToCellException

use of dmg.cells.nucleus.NoRouteToCellException in project dcache by dCache.

the class LabelsResources method getFileAttributes.

@GET
@ApiOperation(value = "Find metadata and optionally virtual directory contents.", notes = "The method offers the possibility to list the content of a virtual" + "directory for labels.")
@ApiResponses({ @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 403, message = "Forbidden"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal Server Error") })
@Path("{path : .*}")
@Produces(MediaType.APPLICATION_JSON)
public JsonFileAttributes getFileAttributes(@ApiParam("Path of file or directory.") @PathParam("path") String requestPath, @ApiParam("Whether to include directory listing.") @DefaultValue("false") @QueryParam("children") boolean isList, @ApiParam("List virtual dir.") @DefaultValue("false") @QueryParam("locality") boolean isLocality, @ApiParam(value = "Whether to include replica locations.") @QueryParam("locations") boolean isLocations, @ApiParam(value = "Whether to include quality of service.") @DefaultValue("false") @QueryParam("qos") boolean isQos, @ApiParam("Whether to include extended attributes.") @QueryParam("xattr") boolean isXattr, @ApiParam("Whether to include labels.") @QueryParam("labels") boolean isLabels, @ApiParam("Limit number of replies in directory listing.") @QueryParam("limit") String limit, @ApiParam("Number of entries to skip in directory listing.") @QueryParam("offset") String offset) throws CacheException {
    JsonFileAttributes fileAttributes = new JsonFileAttributes();
    Set<FileAttribute> attributes = NamespaceUtils.getRequestedAttributes(isLocality, isLocations, false, false, false);
    FsPath path = pathMapper.asDcachePath(request, requestPath, ForbiddenException::new);
    Range<Integer> range;
    try {
        int lower = (offset == null) ? 0 : Integer.parseInt(offset);
        int ceiling = (limit == null) ? Integer.MAX_VALUE : Integer.parseInt(limit);
        if (ceiling < 0 || lower < 0) {
            throw new BadRequestException("limit and offset can not be less than zero.");
        }
        range = (Integer.MAX_VALUE - lower < ceiling) ? Range.atLeast(lower) : Range.closedOpen(lower, lower + ceiling);
    } catch (NumberFormatException e) {
        throw new BadRequestException("limit and offset must be an integer value.");
    }
    try {
        List<JsonFileAttributes> children = new ArrayList<>();
        DirectoryStream stream = listDirectoryHandler.listVirtualDirectory(HttpServletRequests.roleAwareSubject(request), HttpServletRequests.roleAwareRestriction(request), path, range, attributes);
        for (DirectoryEntry entry : stream) {
            String fPath = entry.getName();
            String fName = entry.getName();
            JsonFileAttributes childrenAttributes = new JsonFileAttributes();
            NamespaceUtils.chimeraToJsonAttributes(fPath, childrenAttributes, entry.getFileAttributes(), isLocality, isLocations, isLabels, false, isXattr, false, request, poolMonitor);
            childrenAttributes.setSourcePath(fPath);
            childrenAttributes.setFileName(fName);
            if (isQos) {
                NamespaceUtils.addQoSAttributes(childrenAttributes, entry.getFileAttributes(), request, poolMonitor, pinmanager);
            }
            children.add(childrenAttributes);
        }
        fileAttributes.setChildren(children);
    } catch (FileNotFoundCacheException e) {
        throw new NotFoundException(e);
    } catch (PermissionDeniedCacheException e) {
        if (RequestUser.isAnonymous()) {
            throw new NotAuthorizedException(e);
        } else {
            throw new ForbiddenException(e);
        }
    } catch (CacheException | InterruptedException | NoRouteToCellException ex) {
        LOGGER.warn(Exceptions.meaningfulMessage(ex));
        throw new InternalServerErrorException(ex);
    }
    return fileAttributes;
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) CacheException(diskCacheV111.util.CacheException) FileNotFoundCacheException(diskCacheV111.util.FileNotFoundCacheException) PermissionDeniedCacheException(diskCacheV111.util.PermissionDeniedCacheException) ArrayList(java.util.ArrayList) DirectoryStream(org.dcache.util.list.DirectoryStream) NotFoundException(javax.ws.rs.NotFoundException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) DirectoryEntry(org.dcache.util.list.DirectoryEntry) PermissionDeniedCacheException(diskCacheV111.util.PermissionDeniedCacheException) JsonFileAttributes(org.dcache.restful.providers.JsonFileAttributes) NoRouteToCellException(dmg.cells.nucleus.NoRouteToCellException) BadRequestException(javax.ws.rs.BadRequestException) FileNotFoundCacheException(diskCacheV111.util.FileNotFoundCacheException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) FileAttribute(org.dcache.namespace.FileAttribute) FsPath(diskCacheV111.util.FsPath) FsPath(diskCacheV111.util.FsPath) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

NoRouteToCellException (dmg.cells.nucleus.NoRouteToCellException)67 CacheException (diskCacheV111.util.CacheException)55 TimeoutCacheException (diskCacheV111.util.TimeoutCacheException)25 PermissionDeniedCacheException (diskCacheV111.util.PermissionDeniedCacheException)22 FileNotFoundCacheException (diskCacheV111.util.FileNotFoundCacheException)19 ArrayList (java.util.ArrayList)15 ApiOperation (io.swagger.annotations.ApiOperation)14 ApiResponses (io.swagger.annotations.ApiResponses)14 Produces (javax.ws.rs.Produces)14 BadRequestException (javax.ws.rs.BadRequestException)13 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)13 Path (javax.ws.rs.Path)13 CellPath (dmg.cells.nucleus.CellPath)11 ExecutionException (java.util.concurrent.ExecutionException)11 ForbiddenException (javax.ws.rs.ForbiddenException)11 GET (javax.ws.rs.GET)11 FsPath (diskCacheV111.util.FsPath)10 PnfsId (diskCacheV111.util.PnfsId)10 SRMException (org.dcache.srm.SRMException)10 SRMInternalErrorException (org.dcache.srm.SRMInternalErrorException)10