Search in sources :

Example 31 with PUT

use of javax.ws.rs.PUT in project helios by spotify.

the class HostsResource method put.

/**
   * Registers a host with the cluster.  The {@code host} is the name of the host.  It SHOULD be
   * the hostname of the machine.  The {@code id} should be a persistent value for the host, but
   * initially randomly generated.  This way we don't have two machines claiming to be the same
   * host: at least by accident.
   * @param host The host to register.
   * @param id The randomly generated ID for the host.
   * @return The response.
   */
@PUT
@Path("{host}")
@Produces(APPLICATION_JSON)
@Timed
@ExceptionMetered
public Response.Status put(@PathParam("host") final String host, @QueryParam("id") @DefaultValue("") final String id) {
    if (isNullOrEmpty(id)) {
        throw badRequest(new HostRegisterResponse(HostRegisterResponse.Status.INVALID_ID, host));
    }
    model.registerHost(host, id);
    log.info("added host {}", host);
    return Response.Status.OK;
}
Also used : HostRegisterResponse(com.spotify.helios.common.protocol.HostRegisterResponse) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) PUT(javax.ws.rs.PUT)

Example 32 with PUT

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

the class AutomationEnrollClientGroupResource method enrollClientInGroup.

/**
   * Enroll Client in Group
   *
   * @param clientId the ID of the Client to assign
   * @param groupId the ID of the Group to be assigned to
   * @excludeParams automationClient
   * @description Assigns the Client specified by the clientID to the Group specified by the
   * groupID
   * @responseMessage 200 Successfully enrolled Client in Group
   * @responseMessage 404 Could not find Client or Group
   */
@Timed
@ExceptionMetered
@PUT
public Response enrollClientInGroup(@Auth AutomationClient automationClient, @PathParam("clientId") LongParam clientId, @PathParam("groupId") LongParam groupId) {
    try {
        Map<String, String> extraInfo = new HashMap<>();
        extraInfo.put("deprecated", "true");
        aclDAO.findAndEnrollClient(clientId.get(), groupId.get(), 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) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) PUT(javax.ws.rs.PUT)

Example 33 with PUT

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

the class ClientResource method modifyClientGroups.

/**
   * Modify groups a client has membership in
   *
   * @excludeParams automationClient
   * @param name Client name
   * @param request JSON request specifying which groups to add or remove
   * @return Listing of groups client has membership in
   *
   * @responseMessage 201 Client modified successfully
   * @responseMessage 404 Client not found
   */
@Timed
@ExceptionMetered
@PUT
@Path("{name}/groups")
@Produces(APPLICATION_JSON)
public Iterable<String> modifyClientGroups(@Auth AutomationClient automationClient, @PathParam("name") String name, @Valid ModifyGroupsRequestV2 request) {
    Client client = clientDAOReadWrite.getClient(name).orElseThrow(NotFoundException::new);
    String user = automationClient.getName();
    long clientId = client.getId();
    Set<String> oldGroups = aclDAOReadWrite.getGroupsFor(client).stream().map(Group::getName).collect(toSet());
    Set<String> groupsToAdd = Sets.difference(request.addGroups(), oldGroups);
    Set<String> groupsToRemove = Sets.intersection(request.removeGroups(), oldGroups);
    // TODO: should optimize AclDAO to use names and return only name column
    groupsToGroupIds(groupsToAdd).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEnrollClient(clientId, groupId, auditLog, user, new HashMap<>())));
    groupsToGroupIds(groupsToRemove).forEach((maybeGroupId) -> maybeGroupId.ifPresent((groupId) -> aclDAOReadWrite.findAndEvictClient(clientId, groupId, auditLog, user, new HashMap<>())));
    return aclDAOReadWrite.getGroupsFor(client).stream().map(Group::getName).collect(toSet());
}
Also used : NotImplementedException(org.apache.commons.lang3.NotImplementedException) PathParam(javax.ws.rs.PathParam) AclDAO(keywhiz.service.daos.AclDAO) Produces(javax.ws.rs.Produces) ClientDAO(keywhiz.service.daos.ClientDAO) GET(javax.ws.rs.GET) ClientDetailResponseV2(keywhiz.api.automation.v2.ClientDetailResponseV2) Event(keywhiz.log.Event) Path(javax.ws.rs.Path) LoggerFactory(org.slf4j.LoggerFactory) Auth(io.dropwizard.auth.Auth) GroupDAOFactory(keywhiz.service.daos.GroupDAO.GroupDAOFactory) HashMap(java.util.HashMap) Inject(javax.inject.Inject) Valid(javax.validation.Valid) AutomationClient(keywhiz.api.model.AutomationClient) ClientDAOFactory(keywhiz.service.daos.ClientDAO.ClientDAOFactory) Consumes(javax.ws.rs.Consumes) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) ModifyGroupsRequestV2(keywhiz.api.automation.v2.ModifyGroupsRequestV2) UriBuilder(javax.ws.rs.core.UriBuilder) URI(java.net.URI) Client(keywhiz.api.model.Client) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) GroupDAO(keywhiz.service.daos.GroupDAO) Collectors.toSet(java.util.stream.Collectors.toSet) DELETE(javax.ws.rs.DELETE) CreateClientRequestV2(keywhiz.api.automation.v2.CreateClientRequestV2) AuditLog(keywhiz.log.AuditLog) ModifyClientRequestV2(keywhiz.api.automation.v2.ModifyClientRequestV2) Group(keywhiz.api.model.Group) POST(javax.ws.rs.POST) Logger(org.slf4j.Logger) Set(java.util.Set) AclDAOFactory(keywhiz.service.daos.AclDAO.AclDAOFactory) ConflictException(keywhiz.service.exceptions.ConflictException) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) NotFoundException(javax.ws.rs.NotFoundException) String.format(java.lang.String.format) Timed(com.codahale.metrics.annotation.Timed) EventTag(keywhiz.log.EventTag) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) SanitizedSecret(keywhiz.api.model.SanitizedSecret) PUT(javax.ws.rs.PUT) NotFoundException(javax.ws.rs.NotFoundException) AutomationClient(keywhiz.api.model.AutomationClient) Client(keywhiz.api.model.Client) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered) PUT(javax.ws.rs.PUT)

Example 34 with PUT

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

the class Namespaces method unloadNamespace.

@PUT
@Path("/{property}/{cluster}/{namespace}/unload")
@ApiOperation(value = "Unload namespace", notes = "Unload an active namespace from the current broker serving it. Performing this operation will let the broker" + "removes all producers, consumers, and connections using this namespace, and close all destinations (including" + "their persistent store). During that operation, the namespace is marked as tentatively unavailable until the" + "broker completes the unloading action. This operation requires strictly super user privileges, since it would" + "result in non-persistent message loss and unexpected connection closure to the clients.")
@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 = 412, message = "Namespace is already unloaded or Namespace has bundles activated") })
public void unloadNamespace(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace) {
    log.info("[{}] Unloading namespace {}/{}/{}", clientAppId(), property, cluster, namespace);
    validateSuperUserAccess();
    if (!cluster.equals(Namespaces.GLOBAL_CLUSTER)) {
        validateClusterOwnership(cluster);
        validateClusterForProperty(property, cluster);
    }
    Policies policies = getNamespacePolicies(property, cluster, namespace);
    NamespaceName nsName = new NamespaceName(property, cluster, namespace);
    List<String> boundaries = policies.bundles.getBoundaries();
    for (int i = 0; i < boundaries.size() - 1; i++) {
        String bundle = String.format("%s_%s", boundaries.get(i), boundaries.get(i + 1));
        try {
            pulsar().getAdminClient().namespaces().unloadNamespaceBundle(nsName.toString(), bundle);
        } catch (PulsarServerException | PulsarAdminException e) {
            log.error(String.format("[%s] Failed to unload namespace %s/%s/%s", clientAppId(), property, cluster, namespace), e);
            throw new RestException(e);
        }
    }
    log.info("[{}] Successfully unloaded all the bundles in namespace {}/{}/{}", clientAppId(), property, cluster, namespace);
}
Also used : PulsarServerException(com.yahoo.pulsar.broker.PulsarServerException) NamespaceName(com.yahoo.pulsar.common.naming.NamespaceName) Policies(com.yahoo.pulsar.common.policies.data.Policies) PersistencePolicies(com.yahoo.pulsar.common.policies.data.PersistencePolicies) RetentionPolicies(com.yahoo.pulsar.common.policies.data.RetentionPolicies) RestException(com.yahoo.pulsar.broker.web.RestException) PulsarAdminException(com.yahoo.pulsar.client.admin.PulsarAdminException) Path(javax.ws.rs.Path) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Example 35 with PUT

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

the class PersistentTopics method createPartitionedTopic.

@PUT
@Path("/{property}/{cluster}/{namespace}/{destination}/partitions")
@ApiOperation(value = "Create a partitioned topic.", notes = "It needs to be called before creating a producer on a partitioned topic.")
@ApiResponses(value = { @ApiResponse(code = 403, message = "Don't have admin permission"), @ApiResponse(code = 409, message = "Partitioned topic already exist") })
public void createPartitionedTopic(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("destination") @Encoded String destination, int numPartitions, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative) {
    destination = decode(destination);
    DestinationName dn = DestinationName.get(domain(), property, cluster, namespace, destination);
    validateAdminAccessOnProperty(dn.getProperty());
    if (numPartitions <= 1) {
        throw new RestException(Status.NOT_ACCEPTABLE, "Number of partitions should be more than 1");
    }
    try {
        String path = path(PARTITIONED_TOPIC_PATH_ZNODE, property, cluster, namespace, domain(), dn.getEncodedLocalName());
        byte[] data = jsonMapper().writeValueAsBytes(new PartitionedTopicMetadata(numPartitions));
        zkCreateOptimistic(path, data);
        // we wait for the data to be synced in all quorums and the observers
        Thread.sleep(PARTITIONED_TOPIC_WAIT_SYNC_TIME_MS);
        log.info("[{}] Successfully created partitioned topic {}", clientAppId(), dn);
    } catch (KeeperException.NodeExistsException e) {
        log.warn("[{}] Failed to create already existing partitioned topic {}", clientAppId(), dn);
        throw new RestException(Status.CONFLICT, "Partitioned topic already exist");
    } catch (Exception e) {
        log.error("[{}] Failed to create partitioned topic {}", clientAppId(), dn, e);
        throw new RestException(e);
    }
}
Also used : DestinationName(com.yahoo.pulsar.common.naming.DestinationName) RestException(com.yahoo.pulsar.broker.web.RestException) PartitionedTopicMetadata(com.yahoo.pulsar.common.partition.PartitionedTopicMetadata) KeeperException(org.apache.zookeeper.KeeperException) RestException(com.yahoo.pulsar.broker.web.RestException) TopicBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.TopicBusyException) WebApplicationException(javax.ws.rs.WebApplicationException) PulsarClientException(com.yahoo.pulsar.client.api.PulsarClientException) PreconditionFailedException(com.yahoo.pulsar.client.admin.PulsarAdminException.PreconditionFailedException) SubscriptionBusyException(com.yahoo.pulsar.broker.service.BrokerServiceException.SubscriptionBusyException) NotFoundException(com.yahoo.pulsar.client.admin.PulsarAdminException.NotFoundException) NotAllowedException(com.yahoo.pulsar.broker.service.BrokerServiceException.NotAllowedException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) Path(javax.ws.rs.Path) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT) ApiResponses(io.swagger.annotations.ApiResponses)

Aggregations

PUT (javax.ws.rs.PUT)203 Path (javax.ws.rs.Path)172 Consumes (javax.ws.rs.Consumes)108 Produces (javax.ws.rs.Produces)72 ApiOperation (io.swagger.annotations.ApiOperation)70 ApiResponses (io.swagger.annotations.ApiResponses)53 Timed (com.codahale.metrics.annotation.Timed)36 AuditEvent (org.graylog2.audit.jersey.AuditEvent)36 URI (java.net.URI)24 Response (javax.ws.rs.core.Response)23 AuditPolicy (co.cask.cdap.common.security.AuditPolicy)19 IOException (java.io.IOException)18 BeanWrapper (org.springframework.beans.BeanWrapper)16 BadRequestException (javax.ws.rs.BadRequestException)14 NotFoundException (javax.ws.rs.NotFoundException)14 WebApplicationException (javax.ws.rs.WebApplicationException)12 UriBuilder (javax.ws.rs.core.UriBuilder)12 UUID (java.util.UUID)11 GET (javax.ws.rs.GET)11 POST (javax.ws.rs.POST)11