Search in sources :

Example 36 with GuestId

use of org.candlepin.model.GuestId 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 37 with GuestId

use of org.candlepin.model.GuestId in project candlepin by candlepin.

the class HypervisorUpdateJob method syncGuestIds.

/**
 * Updates the GuestId objects on the incoming consumer with those found in the DB by the same guest id.
 * This allows us to update the existing guestIds directly, and avoid duplicates.
 * @param incoming
 * @param guestIdMap
 * @return
 */
private Consumer syncGuestIds(Consumer incoming, Map<String, GuestId> guestIdMap) {
    List<GuestId> current = incoming.getGuestIds();
    List<GuestId> updated = new ArrayList<>(current.size());
    for (GuestId gid : current) {
        GuestId persisted = guestIdMap.get(gid.getGuestId());
        if (persisted != null) {
            updated.add(persisted);
        } else {
            updated.add(gid);
        }
    }
    incoming.setGuestIds(updated);
    return incoming;
}
Also used : GuestId(org.candlepin.model.GuestId) ArrayList(java.util.ArrayList)

Example 38 with GuestId

use of org.candlepin.model.GuestId in project candlepin by candlepin.

the class HypervisorUpdateJob method toExecute.

/**
 * {@inheritDoc}
 *
 * Executes {@link ConsumerResource#create(org.candlepin.model.Consumer, org.candlepin.auth.Principal,
 *  java.lang.String, java.lang.String, java.lang.String)}
 * Executes (@link ConusmerResource#performConsumerUpdates(java.utl.String, org.candlepin.model.Consumer)}
 * as a pinsetter job.
 *
 * @param context the job's execution context
 */
@Transactional
@SuppressWarnings({ "checkstyle:indentation", "checkstyle:methodlength" })
public void toExecute(JobExecutionContext context) throws JobExecutionException {
    try {
        JobDataMap map = context.getMergedJobDataMap();
        String ownerKey = map.getString(JobStatus.TARGET_ID);
        Boolean create = map.getBoolean(CREATE);
        Principal principal = (Principal) map.get(PRINCIPAL);
        String jobReporterId = map.getString(REPORTER_ID);
        HypervisorUpdateResultUuids result = new HypervisorUpdateResultUuids();
        Owner owner = ownerCurator.lookupByKey(ownerKey);
        if (owner == null) {
            context.setResult("Nothing to do. Owner does not exist");
            log.warn("Hypervisor update attempted against non-existent org id \"{0}\"", ownerKey);
            return;
        }
        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()));
        }
        byte[] data = (byte[]) map.get(DATA);
        String json = decompress(data);
        HypervisorList hypervisors = (HypervisorList) Util.fromJson(json, HypervisorList.class);
        log.debug("Hypervisor consumers for create/update: {}", hypervisors.getHypervisors().size());
        log.debug("Updating hypervisor consumers for org {0}", ownerKey);
        Set<String> hosts = new HashSet<>();
        Set<String> guests = new HashSet<>();
        Map<String, Consumer> incomingHosts = new HashMap<>();
        parseHypervisorList(hypervisors, hosts, guests, incomingHosts);
        // TODO Need to ensure that we retrieve existing guestIds from the DB before continuing.
        // Maps virt hypervisor ID to registered consumer for that hypervisor, should one exist:
        VirtConsumerMap hypervisorConsumersMap = consumerCurator.getHostConsumersMap(owner, hosts);
        Map<String, GuestId> guestIds = consumerCurator.getGuestIdMap(guests, owner);
        for (String hypervisorId : hosts) {
            Consumer knownHost = hypervisorConsumersMap.get(hypervisorId);
            Consumer incoming = syncGuestIds(incomingHosts.get(hypervisorId), guestIds);
            Consumer reportedOnConsumer = null;
            if (knownHost == null) {
                if (!create) {
                    result.failed(hypervisorId, "Unable to find hypervisor with id " + hypervisorId + " in org " + ownerKey);
                } else {
                    log.debug("Registering new host consumer for hypervisor ID: {}", hypervisorId);
                    Consumer newHost = createConsumerForHypervisorId(hypervisorId, jobReporterId, owner, principal, incoming);
                    // Since we just created this new consumer, we can migrate the guests immediately
                    GuestMigration guestMigration = new GuestMigration(consumerCurator).buildMigrationManifest(incoming, newHost);
                    // Now that we have the new consumer persisted, immediately migrate the guests to it
                    if (guestMigration.isMigrationPending()) {
                        guestMigration.migrate(false);
                    }
                    hypervisorConsumersMap.add(hypervisorId, newHost);
                    result.created(newHost);
                    reportedOnConsumer = newHost;
                }
            } else {
                reportedOnConsumer = knownHost;
                if (jobReporterId != null && knownHost.getHypervisorId() != null && hypervisorId.equalsIgnoreCase(knownHost.getHypervisorId().getHypervisorId()) && knownHost.getHypervisorId().getReporterId() != null && !jobReporterId.equalsIgnoreCase(knownHost.getHypervisorId().getReporterId())) {
                    log.debug("Reporter changed for Hypervisor {} of Owner {} from {} to {}", hypervisorId, ownerKey, knownHost.getHypervisorId().getReporterId(), jobReporterId);
                }
                boolean typeUpdated = false;
                if (!hypervisorType.getId().equals(knownHost.getTypeId())) {
                    typeUpdated = true;
                    knownHost.setType(hypervisorType);
                }
                GuestMigration guestMigration = new GuestMigration(consumerCurator).buildMigrationManifest(incoming, knownHost);
                boolean factsUpdated = consumerResource.checkForFactsUpdate(knownHost, incoming);
                if (factsUpdated || guestMigration.isMigrationPending() || typeUpdated) {
                    knownHost.setLastCheckin(new Date());
                    guestMigration.migrate(false);
                    result.updated(knownHost);
                } else {
                    result.unchanged(knownHost);
                }
            }
            // update reporter id if it changed
            if (jobReporterId != null && reportedOnConsumer != null && reportedOnConsumer.getHypervisorId() != null && (reportedOnConsumer.getHypervisorId().getReporterId() == null || !jobReporterId.contentEquals(reportedOnConsumer.getHypervisorId().getReporterId()))) {
                reportedOnConsumer.getHypervisorId().setReporterId(jobReporterId);
            } else if (jobReporterId == null) {
                log.debug("hypervisor checkin reported asynchronously without reporter id " + "for hypervisor:{} of owner:{}", hypervisorId, ownerKey);
            }
        }
        for (Consumer consumer : hypervisorConsumersMap.getConsumers()) {
            consumer = result.wasCreated(consumer) ? consumerCurator.create(consumer, false) : consumerCurator.update(consumer, false);
        }
        consumerCurator.flush();
        log.info("Summary for report from {} by principal {}\n {}", jobReporterId, principal, result);
        context.setResult(result);
    } catch (Exception e) {
        log.error("HypervisorUpdateJob encountered a problem.", e);
        context.setResult(e.getMessage());
        throw new JobExecutionException(e.getMessage(), e, false);
    }
}
Also used : JobDataMap(org.quartz.JobDataMap) Owner(org.candlepin.model.Owner) HashMap(java.util.HashMap) Date(java.util.Date) JobExecutionException(org.quartz.JobExecutionException) SchedulerException(org.quartz.SchedulerException) BadRequestException(org.candlepin.common.exceptions.BadRequestException) IOException(java.io.IOException) HypervisorUpdateResultUuids(org.candlepin.resource.dto.HypervisorUpdateResultUuids) GuestMigration(org.candlepin.resource.util.GuestMigration) JobExecutionException(org.quartz.JobExecutionException) Consumer(org.candlepin.model.Consumer) VirtConsumerMap(org.candlepin.model.VirtConsumerMap) GuestId(org.candlepin.model.GuestId) BadRequestException(org.candlepin.common.exceptions.BadRequestException) Principal(org.candlepin.auth.Principal) HashSet(java.util.HashSet) Transactional(com.google.inject.persist.Transactional)

Example 39 with GuestId

use of org.candlepin.model.GuestId 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)

Example 40 with GuestId

use of org.candlepin.model.GuestId in project candlepin by candlepin.

the class ConsumerResourceUpdateTest method multipleUpdatesCanOccur.

@Test
public void multipleUpdatesCanOccur() {
    String uuid = "A Consumer";
    String expectedFactName = "FACT1";
    String expectedFactValue = "F1";
    GuestIdDTO expectedGuestId = TestUtil.createGuestIdDTO("GUEST_ID_1");
    Consumer existing = getFakeConsumer();
    existing.setFacts(new HashMap<>());
    existing.setInstalledProducts(new HashSet<>());
    ConsumerDTO updated = new ConsumerDTO();
    updated.setUuid(uuid);
    updated.setFact(expectedFactName, expectedFactValue);
    Product prod = TestUtil.createProduct("Product One");
    ConsumerInstalledProductDTO expectedInstalledProduct = new ConsumerInstalledProductDTO(prod.getId(), prod.getName());
    updated.addInstalledProduct(expectedInstalledProduct);
    updated.addGuestId(expectedGuestId);
    when(this.consumerCurator.getGuestConsumersMap(any(String.class), any(Set.class))).thenReturn(new VirtConsumerMap());
    this.resource.updateConsumer(existing.getUuid(), updated, principal);
    assertEquals(1, existing.getFacts().size());
    assertEquals(expectedFactValue, existing.getFact(expectedFactName));
    assertEquals(1, existing.getInstalledProducts().size());
    ConsumerInstalledProduct actualCIP = existing.getInstalledProducts().iterator().next();
    assertNotNull(actualCIP);
    assertEquals(actualCIP.getProductId(), expectedInstalledProduct.getProductId());
    assertEquals(actualCIP.getProductName(), expectedInstalledProduct.getProductName());
    assertEquals(actualCIP.getVersion(), expectedInstalledProduct.getVersion());
    assertEquals(actualCIP.getArch(), expectedInstalledProduct.getArch());
    assertEquals(actualCIP.getStatus(), expectedInstalledProduct.getStatus());
    assertEquals(actualCIP.getStartDate(), expectedInstalledProduct.getStartDate());
    assertEquals(actualCIP.getEndDate(), expectedInstalledProduct.getEndDate());
    assertEquals(1, existing.getGuestIds().size());
    GuestId actualGID = existing.getGuestIds().iterator().next();
    assertNotNull(actualGID);
    assertEquals(actualGID.getGuestId(), expectedGuestId.getGuestId());
    assertEquals(actualGID.getAttributes(), expectedGuestId.getAttributes());
}
Also used : GuestIdDTO(org.candlepin.dto.api.v1.GuestIdDTO) Set(java.util.Set) HashSet(java.util.HashSet) Consumer(org.candlepin.model.Consumer) VirtConsumerMap(org.candlepin.model.VirtConsumerMap) ConsumerInstalledProduct(org.candlepin.model.ConsumerInstalledProduct) GuestId(org.candlepin.model.GuestId) ConsumerDTO(org.candlepin.dto.api.v1.ConsumerDTO) Product(org.candlepin.model.Product) ConsumerInstalledProduct(org.candlepin.model.ConsumerInstalledProduct) ConsumerInstalledProductDTO(org.candlepin.dto.api.v1.ConsumerInstalledProductDTO) Test(org.junit.Test)

Aggregations

GuestId (org.candlepin.model.GuestId)49 Consumer (org.candlepin.model.Consumer)37 Test (org.junit.Test)34 LinkedList (java.util.LinkedList)15 Entitlement (org.candlepin.model.Entitlement)14 GuestIdDTO (org.candlepin.dto.api.v1.GuestIdDTO)11 Date (java.util.Date)10 HashMap (java.util.HashMap)8 Product (org.candlepin.model.Product)8 ArrayList (java.util.ArrayList)7 Owner (org.candlepin.model.Owner)7 VirtConsumerMap (org.candlepin.model.VirtConsumerMap)7 HashSet (java.util.HashSet)6 Set (java.util.Set)6 List (java.util.List)5 Pool (org.candlepin.model.Pool)5 ApiOperation (io.swagger.annotations.ApiOperation)4 Produces (javax.ws.rs.Produces)4 ConsumerDTO (org.candlepin.dto.api.v1.ConsumerDTO)4 ConsumerInstalledProduct (org.candlepin.model.ConsumerInstalledProduct)4