use of org.candlepin.common.exceptions.BadRequestException in project candlepin by candlepin.
the class ConsumerBindUtil method handleActivationKeys.
public void handleActivationKeys(Consumer consumer, List<ActivationKey> keys, boolean autoattachDisabledForOwner) throws AutobindDisabledForOwnerException {
// Process activation keys.
boolean listSuccess = false;
for (ActivationKey key : keys) {
boolean keySuccess = true;
handleActivationKeyOverrides(consumer, key.getContentOverrides());
handleActivationKeyRelease(consumer, key.getReleaseVer());
keySuccess &= handleActivationKeyServiceLevel(consumer, key.getServiceLevel(), key.getOwner());
if (key.isAutoAttach() != null && key.isAutoAttach()) {
if (autoattachDisabledForOwner) {
log.warn("Auto-attach is disabled for owner. Skipping auto-attach for consumer/key: {}/{}", consumer.getUuid(), key.getName());
} else {
handleActivationKeyAutoBind(consumer, key);
}
} else {
keySuccess &= handleActivationKeyPools(consumer, key);
}
listSuccess |= keySuccess;
}
if (!listSuccess) {
throw new BadRequestException(i18n.tr("None of the subscriptions on the activation key were available for attaching."));
}
}
use of org.candlepin.common.exceptions.BadRequestException 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);
}
}
use of org.candlepin.common.exceptions.BadRequestException in project candlepin by candlepin.
the class ImportJob method toExecute.
@Override
public void toExecute(JobExecutionContext context) throws JobExecutionException {
JobDataMap map = context.getMergedJobDataMap();
String ownerKey = (String) map.get(JobStatus.TARGET_ID);
ConflictOverrides overrides = new ConflictOverrides((String[]) map.get(CONFLICT_OVERRIDES));
String storedFileId = (String) map.get(STORED_FILE_ID);
String uploadedFileName = (String) map.get(UPLOADED_FILE_NAME);
Throwable caught = null;
Owner targetOwner = null;
try {
targetOwner = ownerCurator.lookupByKey(ownerKey);
if (targetOwner == null) {
throw new NotFoundException(String.format("Owner %s was not found.", ownerKey));
}
ImportRecord importRecord = manifestManager.importStoredManifest(targetOwner, storedFileId, overrides, uploadedFileName);
context.setResult(importRecord);
}// info about the exception that was thrown (CandlepinException).
catch (SyncDataFormatException e) {
caught = new BadRequestException(e.getMessage(), e);
} catch (ImporterException e) {
caught = new IseException(e.getMessage(), e);
} catch (Exception e) {
caught = e;
}
if (caught != null) {
log.error("ImportJob encountered a problem.", caught);
manifestManager.recordImportFailure(targetOwner, caught, uploadedFileName);
context.setResult(caught.getMessage());
// If an exception was thrown, the importer's transaction was rolled
// back. We want to make sure that the file gets deleted so that it
// doesn't take up disk space. It may be possible that the file was
// already deleted, but we attempt it anyway.
manifestManager.deleteStoredManifest(storedFileId);
throw new JobExecutionException(caught.getMessage(), caught, false);
}
}
use of org.candlepin.common.exceptions.BadRequestException in project candlepin by candlepin.
the class ActivationKeyResource method addPoolToKey.
@ApiOperation(notes = "Adds a Pool to an Activation Key", value = "Add Pool to Key")
@ApiResponses({ @ApiResponse(code = 400, message = "") })
@POST
@Path("{activation_key_id}/pools/{pool_id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.WILDCARD)
public ActivationKeyDTO addPoolToKey(@PathParam("activation_key_id") @Verify(ActivationKey.class) String activationKeyId, @PathParam("pool_id") @Verify(Pool.class) String poolId, @QueryParam("quantity") Long quantity) {
ActivationKey key = activationKeyCurator.verifyAndLookupKey(activationKeyId);
Pool pool = findPool(poolId);
// Throws a BadRequestException if adding pool to key is a bad idea
activationKeyRules.validatePoolForActKey(key, pool, quantity);
// Make sure we don't try to register the pool twice.
if (key.hasPool(pool)) {
throw new BadRequestException(i18n.tr("Pool ID \"{0}\" has already been registered with this activation key", poolId));
}
key.addPool(pool, quantity);
activationKeyCurator.update(key);
return this.translator.translate(key, ActivationKeyDTO.class);
}
Aggregations