Search in sources :

Example 21 with DELETE

use of javax.ws.rs.DELETE in project keywhiz by square.

the class AutomationEnrollClientGroupResource method evictClientFromGroup.

/**
   * Remove Client from Group
   *
   * @param clientId the ID of the Client to unassign
   * @param groupId the ID of the Group to be removed from
   * @excludeParams automationClient
   * @description Unassigns the Client specified by the clientID from the Group specified by the
   * groupID
   * @responseMessage 200 Successfully removed Client from Group
   * @responseMessage 404 Could not find Client or Group
   */
@Timed
@ExceptionMetered
@DELETE
public Response evictClientFromGroup(@Auth AutomationClient automationClient, @PathParam("clientId") long clientId, @PathParam("groupId") long groupId) {
    try {
        Map<String, String> extraInfo = new HashMap<>();
        extraInfo.put("deprecated", "true");
        aclDAO.findAndEvictClient(clientId, groupId, auditLog, automationClient.getName(), extraInfo);
    } catch (IllegalStateException e) {
        throw new NotFoundException();
    }
    return Response.ok().build();
}
Also used : HashMap(java.util.HashMap) NotFoundException(javax.ws.rs.NotFoundException) DELETE(javax.ws.rs.DELETE) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 22 with DELETE

use of javax.ws.rs.DELETE in project keywhiz by square.

the class ClientResource method deleteClient.

/**
   * Delete a client
   *
   * @excludeParams automationClient
   * @param name Client name
   *
   * @responseMessage 204 Client deleted
   * @responseMessage 404 Client not found
   */
@Timed
@ExceptionMetered
@DELETE
@Path("{name}")
public Response deleteClient(@Auth AutomationClient automationClient, @PathParam("name") String name) {
    Client client = clientDAOReadWrite.getClient(name).orElseThrow(NotFoundException::new);
    // Group memberships are deleted automatically by DB cascading.
    clientDAOReadWrite.deleteClient(client);
    auditLog.recordEvent(new Event(Instant.now(), EventTag.CLIENT_DELETE, automationClient.getName(), client.getName()));
    return Response.noContent().build();
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) Event(keywhiz.log.Event) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 23 with DELETE

use of javax.ws.rs.DELETE in project keywhiz by square.

the class GroupsResource method deleteGroup.

/**
   * Delete Group by ID
   *
   * @excludeParams user
   * @param groupId the ID of the Group to be deleted
   *
   * @description Deletes a single Group if found.
   * Used by Keywhiz CLI and the web ui.
   * @responseMessage 200 Found and deleted Group with given ID
   * @responseMessage 404 Group with given ID not Found
   */
@Path("{groupId}")
@Timed
@ExceptionMetered
@DELETE
public Response deleteGroup(@Auth User user, @PathParam("groupId") LongParam groupId) {
    logger.info("User '{}' deleting group id={}.", user, groupId);
    Optional<Group> group = groupDAO.getGroupById(groupId.get());
    if (!group.isPresent()) {
        throw new NotFoundException("Group not found.");
    }
    groupDAO.deleteGroup(group.get());
    auditLog.recordEvent(new Event(Instant.now(), EventTag.GROUP_DELETE, user.getName(), group.get().getName()));
    return Response.noContent().build();
}
Also used : Group(keywhiz.api.model.Group) NotFoundException(javax.ws.rs.NotFoundException) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 24 with DELETE

use of javax.ws.rs.DELETE in project keywhiz by square.

the class ClientsResource method deleteClient.

/**
   * Delete Client by ID
   *
   * @excludeParams user
   * @param clientId the ID of the Client to be deleted
   *
   * @description Deletes a single Client if found.
   * Used by Keywhiz CLI and the web ui.
   * @responseMessage 200 Found and deleted Client with given ID
   * @responseMessage 404 Client with given ID not Found
   */
@Path("{clientId}")
@Timed
@ExceptionMetered
@DELETE
public Response deleteClient(@Auth User user, @PathParam("clientId") LongParam clientId) {
    logger.info("User '{}' deleting client id={}.", user, clientId);
    Optional<Client> client = clientDAO.getClientById(clientId.get());
    if (!client.isPresent()) {
        throw new NotFoundException("Client not found.");
    }
    clientDAO.deleteClient(client.get());
    auditLog.recordEvent(new Event(Instant.now(), EventTag.CLIENT_DELETE, user.getName(), client.get().getName()));
    return Response.noContent().build();
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) Event(keywhiz.log.Event) Client(keywhiz.api.model.Client) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 25 with DELETE

use of javax.ws.rs.DELETE in project pulsar by yahoo.

the class Namespaces method deleteNamespace.

@DELETE
@Path("/{property}/{cluster}/{namespace}")
@ApiOperation(value = "Delete a namespace and all the destinations under it.")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 404, message = "Property or cluster or namespace doesn't exist"), @ApiResponse(code = 409, message = "Namespace is not empty") })
public void deleteNamespace(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    NamespaceName nsName = new NamespaceName(property, cluster, namespace);
    validateAdminAccessOnProperty(property);
    validatePoliciesReadOnlyAccess();
    // ensure that non-global namespace is directed to the correct cluster
    validateClusterOwnership(cluster);
    Entry<Policies, Stat> policiesNode = null;
    Policies policies = null;
    // ensure the local cluster is the only cluster for the global namespace configuration
    try {
        policiesNode = policiesCache().getWithStat(path("policies", property, cluster, namespace)).orElseThrow(() -> new RestException(Status.NOT_FOUND, "Namespace " + nsName + " does not exist."));
        policies = policiesNode.getKey();
        if (cluster.equals(Namespaces.GLOBAL_CLUSTER)) {
            if (policies.replication_clusters.size() > 1) {
                // There are still more than one clusters configured for the global namespace
                throw new RestException(Status.PRECONDITION_FAILED, "Cannot delete the global namespace " + nsName + ". There are still more than one replication clusters configured.");
            }
            if (policies.replication_clusters.size() == 1 && !policies.replication_clusters.contains(config().getClusterName())) {
                // the only replication cluster is other cluster, redirect
                String replCluster = policies.replication_clusters.get(0);
                ClusterData replClusterData = clustersCache().get(AdminResource.path("clusters", replCluster)).orElseThrow(() -> new RestException(Status.NOT_FOUND, "Cluser " + replCluster + " does not exist"));
                URL replClusterUrl;
                if (!config().isTlsEnabled()) {
                    replClusterUrl = new URL(replClusterData.getServiceUrl());
                } else if (!replClusterData.getServiceUrlTls().isEmpty()) {
                    replClusterUrl = new URL(replClusterData.getServiceUrlTls());
                } else {
                    throw new RestException(Status.PRECONDITION_FAILED, "The replication cluster does not provide TLS encrypted service");
                }
                URI redirect = UriBuilder.fromUri(uri.getRequestUri()).host(replClusterUrl.getHost()).port(replClusterUrl.getPort()).replaceQueryParam("authoritative", false).build();
                log.debug("[{}] Redirecting the rest call to {}: cluster={}", clientAppId(), redirect, cluster);
                throw new WebApplicationException(Response.temporaryRedirect(redirect).build());
            }
        }
    } catch (WebApplicationException wae) {
        throw wae;
    } catch (Exception e) {
        throw new RestException(e);
    }
    List<String> destinations = getDestinations(property, cluster, namespace);
    if (!destinations.isEmpty()) {
        log.info("Found destinations: {}", destinations);
        throw new RestException(Status.CONFLICT, "Cannot delete non empty namespace");
    }
    // set the policies to deleted so that somebody else cannot acquire this namespace
    try {
        policies.deleted = true;
        globalZk().setData(path("policies", property, cluster, namespace), jsonMapper().writeValueAsBytes(policies), policiesNode.getValue().getVersion());
        policiesCache().invalidate(path("policies", property, cluster, namespace));
    } catch (Exception e) {
        log.error("[{}] Failed to delete namespace on global ZK {}/{}/{}", clientAppId(), property, cluster, namespace, e);
        throw new RestException(e);
    }
    // remove from owned namespace map and ephemeral node from ZK
    try {
        NamespaceBundles bundles = pulsar().getNamespaceService().getNamespaceBundleFactory().getBundles(nsName);
        for (NamespaceBundle bundle : bundles.getBundles()) {
            // check if the bundle is owned by any broker, if not then we do not need to delete the bundle
            if (pulsar().getNamespaceService().getOwner(bundle).isPresent()) {
                pulsar().getAdminClient().namespaces().deleteNamespaceBundle(nsName.toString(), bundle.getBundleRange());
            }
        }
        // we have successfully removed all the ownership for the namespace, the policies znode can be deleted now
        globalZk().delete(path("policies", property, cluster, namespace), -1);
        policiesCache().invalidate(path("policies", property, cluster, namespace));
    } catch (PulsarAdminException cae) {
        throw new RestException(cae);
    } catch (Exception e) {
        log.error(String.format("[%s] Failed to remove owned namespace %s/%s/%s", clientAppId(), property, cluster, namespace), e);
    // avoid throwing exception in case of the second failure
    }
}
Also used : NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) Policies(com.yahoo.pulsar.common.policies.data.Policies) PersistencePolicies(com.yahoo.pulsar.common.policies.data.PersistencePolicies) RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) WebApplicationException(javax.ws.rs.WebApplicationException) NamespaceBundles(com.yahoo.pulsar.common.naming.NamespaceBundles) RestException(com.yahoo.pulsar.broker.web.RestException) URI(java.net.URI) URL(java.net.URL) RestException(com.yahoo.pulsar.broker.web.RestException) WebApplicationException(javax.ws.rs.WebApplicationException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) KeeperException(org.apache.zookeeper.KeeperException) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) NoNodeException(org.apache.zookeeper.KeeperException.NoNodeException) PulsarServerException(com.yahoo.pulsar.broker.PulsarServerException) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) Stat(org.apache.zookeeper.data.Stat) ClusterData(com.yahoo.pulsar.common.policies.data.ClusterData) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

DELETE (javax.ws.rs.DELETE)202 Path (javax.ws.rs.Path)186 ApiOperation (io.swagger.annotations.ApiOperation)59 ApiResponses (io.swagger.annotations.ApiResponses)48 Produces (javax.ws.rs.Produces)43 Timed (com.codahale.metrics.annotation.Timed)31 AuditEvent (org.graylog2.audit.jersey.AuditEvent)25 IOException (java.io.IOException)20 Response (javax.ws.rs.core.Response)20 WebApplicationException (javax.ws.rs.WebApplicationException)17 HashMap (java.util.HashMap)15 NotFoundException (javax.ws.rs.NotFoundException)15 RestException (com.yahoo.pulsar.broker.web.RestException)12 Consumes (javax.ws.rs.Consumes)12 KeeperException (org.apache.zookeeper.KeeperException)12 ExceptionMetered (com.codahale.metrics.annotation.ExceptionMetered)11 ApiResponse (io.swagger.annotations.ApiResponse)11 NamespaceId (co.cask.cdap.proto.id.NamespaceId)9 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)9 Event (keywhiz.log.Event)9