use of org.candlepin.model.Consumer in project candlepin by candlepin.
the class Entitler method bindByProducts.
/**
* Force option is used to heal entire org
*
* @param data AutobindData encapsulating data required for an autobind request
* @param force heal host even if it has autoheal disabled
* @return List of Entitlements
* @throws AutobindDisabledForOwnerException when an autobind attempt is made and the owner
* has it disabled.
*/
@Transactional
public List<Entitlement> bindByProducts(AutobindData data, boolean force) throws AutobindDisabledForOwnerException {
Consumer consumer = data.getConsumer();
Owner owner = data.getOwner();
if (!consumer.isDev() && owner.isAutobindDisabled()) {
log.info("Skipping auto-attach for consumer '{}'. Auto-attach is disabled for owner {}.", consumer, owner.getKey());
throw new AutobindDisabledForOwnerException(i18n.tr("Auto-attach is disabled for owner \"{0}\".", owner.getKey()));
}
// entitlements based on the planned design of the subscriptions
if (consumer.hasFact("virt.uuid") && !consumer.isDev()) {
String guestUuid = consumer.getFact("virt.uuid");
// Remove any expired unmapped guest entitlements
revokeUnmappedGuestEntitlements(consumer);
// Scoped to the consumer's organization. Even in the event of sharing, a guest in one
// organization should not be able to compel a heal in an another organization
Consumer host = consumerCurator.getHost(consumer, consumer.getOwnerId());
if (host != null && (force || host.isAutoheal())) {
log.info("Attempting to heal host machine with UUID \"{}\" for guest with UUID \"{}\"", host.getUuid(), consumer.getUuid());
if (!StringUtils.equals(host.getServiceLevel(), consumer.getServiceLevel())) {
log.warn("Host with UUID \"{}\" has a service level \"{}\" that does not match" + " that of the guest with UUID \"{}\" and service level \"{}\"", host.getUuid(), host.getServiceLevel(), consumer.getUuid(), consumer.getServiceLevel());
}
try {
List<Entitlement> hostEntitlements = poolManager.entitleByProductsForHost(consumer, host, data.getOnDate(), data.getPossiblePools());
log.debug("Granted host {} entitlements", hostEntitlements.size());
sendEvents(hostEntitlements);
} catch (Exception e) {
// log and continue, this should NEVER block
log.debug("Healing failed for host UUID {} with message: {}", host.getUuid(), e.getMessage());
}
/* Consumer is stale at this point. Note that we use find() instead of
* findByUuid() or getConsumer() since the latter two methods are secured
* to a specific host principal and bindByProducts can get called when
* a guest is switching hosts */
consumer = consumerCurator.find(consumer.getId());
data.setConsumer(consumer);
}
}
if (consumer.isDev()) {
if (config.getBoolean(ConfigProperties.STANDALONE) || !poolCurator.hasActiveEntitlementPools(consumer.getOwnerId(), null)) {
throw new ForbiddenException(i18n.tr("Development units may only be used on hosted servers" + " and with orgs that have active subscriptions."));
}
// Look up the dev pool for this consumer, and if not found
// create one. If a dev pool already exists, remove it and
// create a new one.
String sku = consumer.getFact("dev_sku");
Pool devPool = poolCurator.findDevPool(consumer);
if (devPool != null) {
poolManager.deletePool(devPool);
}
devPool = poolManager.createPool(assembleDevPool(consumer, owner, sku));
data.setPossiblePools(Arrays.asList(devPool.getId()));
data.setProductIds(new String[] { sku });
}
// Attempt to create entitlements:
try {
// the pools are only used to bind the guest
List<Entitlement> entitlements = poolManager.entitleByProducts(data);
log.debug("Created entitlements: {}", entitlements);
return entitlements;
} catch (EntitlementRefusedException e) {
// TODO: Could be multiple errors, but we'll just report the first one for now
String productId = "Unknown Product";
if (data.getProductIds().length > 0) {
productId = data.getProductIds()[0];
}
throw new ForbiddenException(messageTranslator.productErrorToMessage(productId, e.getResults().values().iterator().next().getErrors().get(0)));
}
}
use of org.candlepin.model.Consumer in project candlepin by candlepin.
the class ManifestManager method generateManifestAsync.
/**
* Asynchronously generates a manifest for the target consumer.
*
* @param consumerUuid the target consumer's UUID.
* @param cdnLabel the CDN label to store in the meta file.
* @param webUrl the URL pointing to the manifest's originating web application.
* @param apiUrl the API URL pointing to the manifest's originating candlepin API.
* @param extensionData data to be passed to the {@link ExportExtensionAdapter} when creating
* a new export of the target consumer.
* @return the details of the async export job.
*/
public JobDetail generateManifestAsync(String consumerUuid, String ownerKey, String cdnLabel, String webUrl, String apiUrl, Map<String, String> extensionData) {
log.info("Scheduling Async Export for consumer {}", consumerUuid);
Consumer consumer = validateConsumerForExport(consumerUuid, cdnLabel);
return ExportJob.scheduleExport(consumer, ownerKey, cdnLabel, webUrl, apiUrl, extensionData);
}
use of org.candlepin.model.Consumer in project candlepin by candlepin.
the class ManifestManager method validateConsumerForExport.
private Consumer validateConsumerForExport(String consumerUuid, String cdnLabel) {
// FIXME Should this be testing the CdnLabel as well?
Consumer consumer = consumerCurator.verifyAndLookupConsumer(consumerUuid);
ConsumerType ctype = this.consumerTypeCurator.getConsumerType(consumer);
if (ctype == null || !ctype.isManifest()) {
throw new ForbiddenException(i18n.tr("Unit {0} cannot be exported. A manifest cannot be made for units of type \"{1}\".", consumerUuid, ctype != null ? ctype.getLabel() : "unknown type"));
}
if (!StringUtils.isBlank(cdnLabel) && cdnCurator.lookupByLabel(cdnLabel) == null) {
throw new ForbiddenException(i18n.tr("A CDN with label {0} does not exist on this system.", cdnLabel));
}
return consumer;
}
use of org.candlepin.model.Consumer in project candlepin by candlepin.
the class ManifestManager method writeStoredExportToResponse.
/**
* Write the stored manifest file to the specified response output stream and update
* the appropriate response data.
*
* @param exportId the id of the manifest file to find.
* @param exportedConsumerUuid the UUID of the consumer the export was generated for.
* @param response the response to write the file to.
* @throws ManifestFileServiceException if there was an issue getting the file from the service
* @throws NotFoundException if the manifest file is not found
* @throws BadRequestException if the manifests target consumer does not match the specified
* consumer.
* @throws IseException if there was an issue writing the file to the response.
*/
@Transactional
public void writeStoredExportToResponse(String exportId, String exportedConsumerUuid, HttpServletResponse response) throws ManifestFileServiceException, NotFoundException, BadRequestException, IseException {
Consumer exportedConsumer = consumerCurator.verifyAndLookupConsumer(exportedConsumerUuid);
// In order to stream the results from the DB to the client
// we write the file contents directly to the response output stream.
//
// NOTE: Passing the database input stream to the response builder seems
// like it would be a correct approach here, but large object streaming
// can only be done inside a single transaction, so we have to stream it
// manually.
ManifestFile manifest = manifestFileService.get(exportId);
if (manifest == null) {
throw new NotFoundException(i18n.tr("Unable to find specified manifest by id: {0}", exportId));
}
// The specified consumer must match that of the manifest.
if (!exportedConsumer.getUuid().equals(manifest.getTargetId())) {
throw new BadRequestException(i18n.tr("Could not validate export against specifed consumer: {0}", exportedConsumer.getUuid()));
}
BufferedOutputStream output = null;
InputStream input = null;
try {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=" + manifest.getName());
// NOTE: Input and output streams are expected to be closed by their creators.
input = manifest.getInputStream();
output = new BufferedOutputStream(response.getOutputStream());
int data = input.read();
while (data != -1) {
output.write(data);
data = input.read();
}
output.flush();
} catch (Exception e) {
// Reset the response data so that a json response can be returned,
// by RestEasy.
response.setContentType("text/json");
response.setHeader("Content-Disposition", "");
throw new IseException(i18n.tr("Unable to download manifest: {0}", exportId), e);
}
}
use of org.candlepin.model.Consumer in project candlepin by candlepin.
the class ManifestManager method generateManifest.
/**
* Generates a manifest for the specified consumer.
*
* @param consumerUuid the target consumer's UUID.
* @param cdnLabel the CDN label to store in the meta file.
* @param webUrl the URL pointing to the manifest's originating web application.
* @param apiUrl the API URL pointing to the manifest's originating candlepin API.
* @param extensionData data to be passed to the {@link ExportExtensionAdapter} when creating
* a new export of the target consumer.
* @return an archive of the target consumer
* @throws ExportCreationException when an export fails.
*/
public File generateManifest(String consumerUuid, String cdnLabel, String webUrl, String apiUrl, Map<String, String> extensionData) throws ExportCreationException {
log.info("Exporting consumer {}", consumerUuid);
Consumer consumer = validateConsumerForExport(consumerUuid, cdnLabel);
poolManager.regenerateDirtyEntitlements(entitlementCurator.listByConsumer(consumer));
File export = exporter.getFullExport(consumer, cdnLabel, webUrl, apiUrl, extensionData);
sink.queueEvent(eventFactory.exportCreated(consumer));
return export;
}
Aggregations