Search in sources :

Example 11 with GuestMigration

use of org.candlepin.resource.util.GuestMigration 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 12 with GuestMigration

use of org.candlepin.resource.util.GuestMigration in project candlepin by candlepin.

the class ConsumerResourceCreationTest method init.

@Before
public void init() throws Exception {
    this.i18n = I18nFactory.getI18n(getClass(), Locale.US, I18nFactory.FALLBACK);
    this.modelTranslator = new StandardTranslator(this.consumerTypeCurator, this.environmentCurator, this.ownerCurator);
    testMigration = new GuestMigration(consumerCurator);
    migrationProvider = Providers.of(testMigration);
    this.config = initConfig();
    this.resource = new ConsumerResource(this.consumerCurator, this.consumerTypeCurator, null, this.subscriptionService, this.ownerService, null, this.idCertService, null, this.i18n, this.sink, null, null, null, this.userService, null, null, this.ownerCurator, this.activationKeyCurator, null, this.complianceRules, this.deletedConsumerCurator, null, null, this.config, null, null, null, this.consumerBindUtil, null, null, new FactValidator(this.config, this.i18n), null, consumerEnricher, migrationProvider, modelTranslator);
    this.system = this.initConsumerType();
    this.mockConsumerType(this.system);
    this.systemDto = this.modelTranslator.translate(this.system, ConsumerTypeDTO.class);
    owner = new Owner("test_owner");
    owner.setId(TestUtil.randomString());
    user = new User(USER, "");
    PermissionBlueprint p = new PermissionBlueprint(PermissionType.OWNER, owner, Access.ALL);
    role = new Role();
    role.addPermission(p);
    role.addUser(user);
    when(consumerCurator.create(any(Consumer.class))).thenAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getArguments()[0];
        }
    });
    when(consumerCurator.create(any(Consumer.class), any(Boolean.class))).thenAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return invocation.getArguments()[0];
        }
    });
    when(userService.findByLogin(USER)).thenReturn(user);
    IdentityCertificate cert = new IdentityCertificate();
    cert.setKey("testKey");
    cert.setCert("testCert");
    cert.setId("testId");
    cert.setSerial(new CertificateSerial(new Date()));
    when(idCertService.generateIdentityCert(any(Consumer.class))).thenReturn(cert);
    when(ownerCurator.lookupByKey(owner.getKey())).thenReturn(owner);
    when(complianceRules.getStatus(any(Consumer.class), any(Date.class), any(Boolean.class), any(Boolean.class))).thenReturn(new ComplianceStatus(new Date()));
}
Also used : FactValidator(org.candlepin.util.FactValidator) Owner(org.candlepin.model.Owner) User(org.candlepin.model.User) ComplianceStatus(org.candlepin.policy.js.compliance.ComplianceStatus) CertificateSerial(org.candlepin.model.CertificateSerial) StandardTranslator(org.candlepin.dto.StandardTranslator) ConsumerTypeDTO(org.candlepin.dto.api.v1.ConsumerTypeDTO) Date(java.util.Date) Role(org.candlepin.model.Role) GuestMigration(org.candlepin.resource.util.GuestMigration) Answer(org.mockito.stubbing.Answer) Consumer(org.candlepin.model.Consumer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) PermissionBlueprint(org.candlepin.model.PermissionBlueprint) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) IdentityCertificate(org.candlepin.model.IdentityCertificate) Before(org.junit.Before)

Aggregations

GuestMigration (org.candlepin.resource.util.GuestMigration)12 Consumer (org.candlepin.model.Consumer)10 ConsumerType (org.candlepin.model.ConsumerType)6 Before (org.junit.Before)6 StandardTranslator (org.candlepin.dto.StandardTranslator)5 Owner (org.candlepin.model.Owner)5 Date (java.util.Date)4 CandlepinCommonTestConfig (org.candlepin.config.CandlepinCommonTestConfig)4 FactValidator (org.candlepin.util.FactValidator)4 HashSet (java.util.HashSet)3 Target (org.candlepin.audit.Event.Target)3 Type (org.candlepin.audit.Event.Type)3 ComplianceStatus (org.candlepin.policy.js.compliance.ComplianceStatus)3 Transactional (com.google.inject.persist.Transactional)2 ApiOperation (io.swagger.annotations.ApiOperation)2 IOException (java.io.IOException)2 Consumes (javax.ws.rs.Consumes)2 PUT (javax.ws.rs.PUT)2 Produces (javax.ws.rs.Produces)2 Principal (org.candlepin.auth.Principal)2