Search in sources :

Example 6 with GuestIdDTO

use of org.candlepin.dto.api.v1.GuestIdDTO in project candlepin by candlepin.

the class GuestIdResource method updateGuests.

@ApiOperation(notes = "Updates the List of Guests on a Consumer This method should work " + "just like updating the consumer, except that it only updates GuestIds. " + " Eventually we should move All the logic here, and depricate updating guests " + "through the consumer update.", value = "updateGuests")
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public void updateGuests(@PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid, @ApiParam(name = "guestIds", required = true) List<GuestIdDTO> guestIdDTOs) {
    Consumer toUpdate = consumerCurator.findByUuid(consumerUuid);
    // Create a skeleton consumer for consumerResource.performConsumerUpdates
    ConsumerDTO consumer = new ConsumerDTO();
    consumer.setGuestIds(guestIdDTOs);
    Set<String> allGuestIds = new HashSet<>();
    for (GuestIdDTO gid : consumer.getGuestIds()) {
        allGuestIds.add(gid.getGuestId());
    }
    VirtConsumerMap guestConsumerMap = consumerCurator.getGuestConsumersMap(toUpdate.getOwnerId(), allGuestIds);
    GuestMigration guestMigration = migrationProvider.get().buildMigrationManifest(consumer, toUpdate);
    if (consumerResource.performConsumerUpdates(consumer, toUpdate, guestMigration)) {
        if (guestMigration.isMigrationPending()) {
            guestMigration.migrate();
        } else {
            consumerCurator.update(toUpdate);
        }
    }
}
Also used : GuestIdDTO(org.candlepin.dto.api.v1.GuestIdDTO) GuestMigration(org.candlepin.resource.util.GuestMigration) Consumer(org.candlepin.model.Consumer) VirtConsumerMap(org.candlepin.model.VirtConsumerMap) ConsumerDTO(org.candlepin.dto.api.v1.ConsumerDTO) HashSet(java.util.HashSet) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT)

Example 7 with GuestIdDTO

use of org.candlepin.dto.api.v1.GuestIdDTO in project candlepin by candlepin.

the class GuestIdResource method updateGuest.

@ApiOperation(notes = "Updates a single Guest on a Consumer. Allows virt-who to avoid uploading" + " an entire list of guests", value = "updateGuest")
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{guest_id}")
public void updateGuest(@ApiParam("consumer who owns or hosts the guest in question") @PathParam("consumer_uuid") @Verify(Consumer.class) String consumerUuid, @ApiParam("guest virtual uuid") @PathParam("guest_id") String guestId, @ApiParam(name = "updated", required = true, value = "updated guest data to use") GuestIdDTO updatedDTO) {
    // I'm not sure this can happen
    if (guestId == null || guestId.isEmpty()) {
        throw new BadRequestException(i18n.tr("Please supply a valid guest id"));
    }
    if (updatedDTO == null) {
        // If they're not sending attributes, we can get the guestId from the url
        updatedDTO = new GuestIdDTO().setGuestId(guestId);
    }
    // Allow the id to be left out in this case, we can use the path param
    if (updatedDTO.getGuestId() == null) {
        updatedDTO.setGuestId(guestId);
    }
    // If the guest uuids do not match, something is wrong
    if (!guestId.equalsIgnoreCase(updatedDTO.getGuestId())) {
        throw new BadRequestException(i18n.tr("Guest ID in json \"{0}\" does not match path guest ID \"{1}\"", updatedDTO.getGuestId(), guestId));
    }
    Consumer consumer = consumerCurator.verifyAndLookupConsumer(consumerUuid);
    GuestId guestIdEntity = new GuestId();
    populateEntity(guestIdEntity, updatedDTO);
    guestIdEntity.setConsumer(consumer);
    GuestId toUpdate = guestIdCurator.findByGuestIdAndOrg(guestId, consumer.getOwnerId());
    if (toUpdate != null) {
        guestIdEntity.setId(toUpdate.getId());
    }
    guestIdCurator.merge(guestIdEntity);
}
Also used : GuestIdDTO(org.candlepin.dto.api.v1.GuestIdDTO) Consumer(org.candlepin.model.Consumer) GuestId(org.candlepin.model.GuestId) BadRequestException(org.candlepin.common.exceptions.BadRequestException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) PUT(javax.ws.rs.PUT)

Example 8 with GuestIdDTO

use of org.candlepin.dto.api.v1.GuestIdDTO in project candlepin by candlepin.

the class HypervisorResource method hypervisorUpdate.

/**
 * @deprecated Use the asynchronous method
 * @return HypervisorCheckInResult
 */
@ApiOperation(notes = "Updates the list of Hypervisor Guests Allows agents such as " + "virt-who to update its host list and associate the guests for each host. This is " + "typically used when a host is unable to register to candlepin via subscription" + " manager.  In situations where consumers already exist it is probably best not " + "to allow creation of new hypervisor consumers.  Most consumers do not have a" + " hypervisorId attribute, so that should be added manually when necessary by the " + "management environment. @deprecated Use the asynchronous method", value = "hypervisorUpdate")
@ApiResponses({ @ApiResponse(code = 202, message = "") })
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Deprecated
@Transactional
@UpdateConsumerCheckIn
@SuppressWarnings("checkstyle:indentation")
public HypervisorCheckInResult hypervisorUpdate(Map<String, List<GuestIdDTO>> hostGuestDTOMap, @Context Principal principal, @QueryParam("owner") @Verify(value = Owner.class, require = Access.READ_ONLY, subResource = SubResource.HYPERVISOR) String ownerKey, @ApiParam("specify whether or not to create missing hypervisors." + "Default is true.  If false is specified, hypervisorIds that are not found" + "will result in failed entries in the resulting HypervisorCheckInResult") @QueryParam("create_missing") @DefaultValue("true") boolean createMissing) {
    log.debug("Hypervisor check-in by principal: {}", principal);
    if (hostGuestDTOMap == null) {
        log.debug("Host/Guest mapping provided during hypervisor checkin was null.");
        throw new BadRequestException(i18n.tr("Host to guest mapping was not provided for hypervisor check-in."));
    }
    Owner owner = this.getOwner(ownerKey);
    if (owner.isAutobindDisabled()) {
        log.debug("Could not update host/guest mapping. Auto-attach is disabled for owner {}", owner.getKey());
        throw new BadRequestException(i18n.tr("Could not update host/guest mapping. Auto-attach is disabled for owner {0}.", owner.getKey()));
    }
    if (hostGuestDTOMap.remove("") != null) {
        log.warn("Ignoring empty hypervisor id");
    }
    // Maps virt hypervisor ID to registered consumer for that hypervisor, should one exist:
    VirtConsumerMap hypervisorConsumersMap = consumerCurator.getHostConsumersMap(owner, hostGuestDTOMap.keySet());
    int emptyGuestIdCount = 0;
    Set<String> allGuestIds = new HashSet<>();
    Collection<List<GuestIdDTO>> idsLists = hostGuestDTOMap.values();
    for (List<GuestIdDTO> guestIds : idsLists) {
        // See bzs 1332637, 1332635
        if (guestIds == null) {
            continue;
        }
        for (Iterator<GuestIdDTO> guestIdsItr = guestIds.iterator(); guestIdsItr.hasNext(); ) {
            String id = guestIdsItr.next().getGuestId();
            if (StringUtils.isEmpty(id)) {
                emptyGuestIdCount++;
                guestIdsItr.remove();
            } else {
                allGuestIds.add(id);
            }
        }
    }
    if (emptyGuestIdCount > 0) {
        log.warn("Ignoring {} empty/null guest id(s).", emptyGuestIdCount);
    }
    HypervisorCheckInResult result = new HypervisorCheckInResult();
    for (Entry<String, List<GuestIdDTO>> hostEntry : hostGuestDTOMap.entrySet()) {
        String hypervisorId = hostEntry.getKey();
        // See bzs 1332637, 1332635
        if (hostEntry.getValue() == null) {
            hostEntry.setValue(new ArrayList<>());
        }
        try {
            log.debug("Syncing virt host: {} ({} guest IDs)", hypervisorId, hostEntry.getValue().size());
            boolean hostConsumerCreated = false;
            boolean updatedType = false;
            // Attempt to find a consumer for the given hypervisorId
            Consumer consumer = null;
            if (hypervisorConsumersMap.get(hypervisorId) == null) {
                if (!createMissing) {
                    log.info("Unable to find hypervisor with id {} in org {}", hypervisorId, ownerKey);
                    result.failed(hypervisorId, i18n.tr("Unable to find hypervisor in org \"{0}\"", ownerKey));
                    continue;
                }
                log.debug("Registering new host consumer for hypervisor ID: {}", hypervisorId);
                consumer = createConsumerForHypervisorId(hypervisorId, owner, principal);
                hostConsumerCreated = true;
            } else {
                consumer = hypervisorConsumersMap.get(hypervisorId);
                if (!hypervisorType.getId().equals(consumer.getTypeId())) {
                    consumer.setType(hypervisorType);
                    updatedType = true;
                }
            }
            List<GuestId> guestIds = new ArrayList<>();
            guestIdResource.populateEntities(guestIds, hostEntry.getValue());
            boolean guestIdsUpdated = addGuestIds(consumer, guestIds);
            Date now = new Date();
            consumerCurator.updateLastCheckin(consumer, now);
            consumer.setLastCheckin(now);
            // Populate the result with the processed consumer.
            if (hostConsumerCreated) {
                result.created(consumer);
            } else if (guestIdsUpdated || updatedType) {
                result.updated(consumer);
            } else {
                result.unchanged(consumer);
            }
        } catch (Exception e) {
            log.error("Hypervisor checkin failed", e);
            result.failed(hypervisorId, e.getMessage());
        }
    }
    log.info("Summary of hypervisor checkin by principal \"{}\": {}", principal, result);
    return result;
}
Also used : GuestIdDTO(org.candlepin.dto.api.v1.GuestIdDTO) Owner(org.candlepin.model.Owner) ArrayList(java.util.ArrayList) Date(java.util.Date) NotFoundException(org.candlepin.common.exceptions.NotFoundException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) Consumer(org.candlepin.model.Consumer) VirtConsumerMap(org.candlepin.model.VirtConsumerMap) GuestId(org.candlepin.model.GuestId) BadRequestException(org.candlepin.common.exceptions.BadRequestException) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) HypervisorCheckInResult(org.candlepin.resource.dto.HypervisorCheckInResult) UpdateConsumerCheckIn(org.candlepin.auth.UpdateConsumerCheckIn) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses) Transactional(com.google.inject.persist.Transactional)

Example 9 with GuestIdDTO

use of org.candlepin.dto.api.v1.GuestIdDTO in project candlepin by candlepin.

the class GuestMigration method buildMigrationManifest.

/**
 * Build a manifest detailing any guest migrations occurring due to a host consumer update.
 *
 * If a consumer's guest was already reported by another host consumer, record that host in the
 * manifest as well so that the migration can be made atomically.
 *
 * @param incoming incoming consumer in DTO form
 * @param existing existing consumer in model form
 * @return guestMigration object that contains all information related to the migration
 */
public GuestMigration buildMigrationManifest(ConsumerDTO incoming, Consumer existing) {
    if (incoming.getGuestIds() == null) {
        log.debug("Guests not included in this consumer update, skipping update.");
        migrationPending = false;
        return this;
    }
    manifest = new MigrationManifest(existing);
    log.debug("Updating {} guest IDs.", incoming.getGuestIds().size());
    List<GuestId> existingGuests = existing.getGuestIds();
    // Transform incoming GuestIdDTOs to GuestIds
    List<GuestId> incomingGuestIds = incoming.getGuestIds().stream().filter(Objects::nonNull).map(guestIdDTO -> new GuestId(guestIdDTO.getGuestId(), existing, guestIdDTO.getAttributes())).collect(Collectors.toList());
    List<GuestId> removedGuests = getRemovedGuestIds(existing, incomingGuestIds);
    List<GuestId> addedGuests = getAddedGuestIds(existing, incomingGuestIds);
    // remove guests that are missing.
    if (existingGuests != null) {
        for (GuestId guestId : removedGuests) {
            existingGuests.remove(guestId);
            log.debug("Guest ID removed: {}", guestId);
        }
    }
    // Check guests that are existing/added.
    for (GuestId guestId : incomingGuestIds) {
        if (addedGuests.contains(guestId)) {
            manifest.addGuestId(guestId);
            log.debug("New guest ID added: {}", guestId);
        }
    }
    migrationPending = removedGuests.size() != 0 || addedGuests.size() != 0;
    return this;
}
Also used : ConsumerDTO(org.candlepin.dto.api.v1.ConsumerDTO) Logger(org.slf4j.Logger) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Objects(java.util.Objects) Inject(javax.inject.Inject) ConsumerCurator(org.candlepin.model.ConsumerCurator) List(java.util.List) Map(java.util.Map) Consumer(org.candlepin.model.Consumer) GuestId(org.candlepin.model.GuestId) GuestId(org.candlepin.model.GuestId) Objects(java.util.Objects)

Example 10 with GuestIdDTO

use of org.candlepin.dto.api.v1.GuestIdDTO in project candlepin by candlepin.

the class ConsumerResourceUpdateTest method createConsumerDTOWithGuests.

private ConsumerDTO createConsumerDTOWithGuests(String... guestIds) {
    Consumer consumer = createConsumerWithGuests(createOwner(), guestIds);
    // re-add guestIds as consumer translator removes them.
    List<GuestIdDTO> guestIdDTOS = new LinkedList<>();
    for (GuestId guestId : consumer.getGuestIds()) {
        guestIdDTOS.add(translator.translate(guestId, GuestIdDTO.class));
    }
    return translator.translate(consumer, ConsumerDTO.class).setGuestIds(guestIdDTOS);
}
Also used : GuestIdDTO(org.candlepin.dto.api.v1.GuestIdDTO) Consumer(org.candlepin.model.Consumer) GuestId(org.candlepin.model.GuestId) ConsumerDTO(org.candlepin.dto.api.v1.ConsumerDTO) LinkedList(java.util.LinkedList)

Aggregations

GuestIdDTO (org.candlepin.dto.api.v1.GuestIdDTO)14 GuestId (org.candlepin.model.GuestId)12 Consumer (org.candlepin.model.Consumer)8 Test (org.junit.Test)8 HashSet (java.util.HashSet)5 ConsumerDTO (org.candlepin.dto.api.v1.ConsumerDTO)5 VirtConsumerMap (org.candlepin.model.VirtConsumerMap)4 ApiOperation (io.swagger.annotations.ApiOperation)3 ArrayList (java.util.ArrayList)3 Set (java.util.Set)3 Consumes (javax.ws.rs.Consumes)3 Produces (javax.ws.rs.Produces)3 Mockito.anyString (org.mockito.Mockito.anyString)3 List (java.util.List)2 PUT (javax.ws.rs.PUT)2 BadRequestException (org.candlepin.common.exceptions.BadRequestException)2 NotFoundException (org.candlepin.common.exceptions.NotFoundException)2 ConsumerInstalledProduct (org.candlepin.model.ConsumerInstalledProduct)2 Transactional (com.google.inject.persist.Transactional)1 ApiResponses (io.swagger.annotations.ApiResponses)1