Search in sources :

Example 26 with IndyDataException

use of org.commonjava.indy.data.IndyDataException in project indy by Commonjava.

the class FoloPomDownloadListener method onFileUpload.

public void onFileUpload(@Observes final FileStorageEvent event) {
    // check for a TransferOperation of DOWNLOAD
    final TransferOperation op = event.getType();
    if (op != TransferOperation.DOWNLOAD) {
        logger.trace("Not a download transfer operation. No pom existence check performed.");
        return;
    }
    // check if it is a path that doesn't end in with ".pom"
    final Transfer transfer = event.getTransfer();
    if (transfer == null) {
        logger.trace("No transfer. No pom existence check performed.");
        return;
    }
    String txfrPath = transfer.getPath();
    if (txfrPath.endsWith(".pom")) {
        logger.trace("This is a pom download.");
        return;
    }
    // use ArtifactPathInfo to parse into a GAV, just to verify that it's looking at an artifact download
    ArtifactPathInfo artPathInfo = ArtifactPathInfo.parse(txfrPath);
    if (artPathInfo == null) {
        logger.trace("Not an artifact download ({}). No pom existence check performed.", txfrPath);
        return;
    }
    // verify that the associated .pom file exists
    String pomFilename = String.format("%s-%s.pom", artPathInfo.getArtifactId(), artPathInfo.getVersion());
    ConcreteResource pomResource = transfer.getResource().getParent().getChild(pomFilename);
    if (cacheProvider.exists(pomResource)) {
        logger.trace("Pom {} already exists.", cacheProvider.getFilePath(pomResource));
        return;
    }
    // trigger pom download by requesting it from the same repository as the original artifact
    StoreKey storeKey = StoreKey.fromString(transfer.getLocation().getName());
    ArtifactStore store;
    try {
        store = storeManager.getArtifactStore(storeKey);
    } catch (final IndyDataException ex) {
        logger.error("Error retrieving artifactStore with key " + storeKey, ex);
        return;
    }
    try {
        logger.debug("Downloading POM as automatic response to associated artifact download: {}/{}", storeKey, pomResource.getPath());
        contentManager.retrieve(store, pomResource.getPath(), event.getEventMetadata());
    } catch (final IndyWorkflowException ex) {
        logger.error("Error while retrieving pom artifact " + pomResource.getPath() + " from store " + store, ex);
        return;
    }
}
Also used : IndyDataException(org.commonjava.indy.data.IndyDataException) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) Transfer(org.commonjava.maven.galley.model.Transfer) ArtifactPathInfo(org.commonjava.maven.atlas.ident.util.ArtifactPathInfo) ConcreteResource(org.commonjava.maven.galley.model.ConcreteResource) TransferOperation(org.commonjava.maven.galley.model.TransferOperation) StoreKey(org.commonjava.indy.model.core.StoreKey)

Example 27 with IndyDataException

use of org.commonjava.indy.data.IndyDataException in project indy by Commonjava.

the class PromotionManager method runPathPromotions.

private PathsPromoteResult runPathPromotions(final PathsPromoteRequest request, final Set<String> pending, final Set<String> prevComplete, final Set<String> prevSkipped, final List<Transfer> contents, ValidationResult validation) {
    if (pending == null || pending.isEmpty()) {
        return new PathsPromoteResult(request, pending, prevComplete, prevSkipped, validation);
    }
    StoreKey targetKey = request.getTarget();
    ReentrantLock lock;
    synchronized (byPathTargetLocks) {
        lock = byPathTargetLocks.get(targetKey);
        if (lock == null) {
            lock = new ReentrantLock();
            byPathTargetLocks.put(targetKey, lock);
        }
    }
    final Set<String> complete = prevComplete == null ? new HashSet<>() : new HashSet<>(prevComplete);
    final Set<String> skipped = prevSkipped == null ? new HashSet<>() : new HashSet<>(prevSkipped);
    List<String> errors = new ArrayList<>();
    boolean locked = false;
    try {
        ArtifactStore sourceStore = storeManager.getArtifactStore(request.getSource());
        ArtifactStore targetStore = storeManager.getArtifactStore(request.getTarget());
        if (errors.isEmpty()) {
            locked = lock.tryLock(config.getLockTimeoutSeconds(), TimeUnit.SECONDS);
            if (!locked) {
                String error = String.format("Failed to acquire promotion lock on target: %s in %d seconds.", targetKey, config.getLockTimeoutSeconds());
                errors.add(error);
                logger.warn(error);
            }
        }
        if (errors.isEmpty()) {
            logger.info("Running promotions from: {} (key: {})\n  to: {} (key: {})", sourceStore, request.getSource(), targetStore, request.getTarget());
            final boolean purgeSource = request.isPurgeSource();
            contents.forEach((transfer) -> {
                try {
                    final String path = transfer.getPath();
                    Transfer target = contentManager.getTransfer(targetStore, path, TransferOperation.UPLOAD);
                    // TODO: Should the request object have an overwrite attribute? Is that something the user is qualified to decide?
                    if (target != null && target.exists()) {
                        logger.warn("NOT promoting: {} from: {} to: {}. Target file already exists.", path, request.getSource(), request.getTarget());
                        // TODO: There's no guarantee that the pre-existing content is the same!
                        pending.remove(path);
                        skipped.add(path);
                    } else {
                        try (InputStream stream = transfer.openInputStream(true)) {
                            contentManager.store(targetStore, path, stream, TransferOperation.UPLOAD, new EventMetadata());
                            pending.remove(path);
                            complete.add(path);
                            stream.close();
                            if (purgeSource) {
                                contentManager.delete(sourceStore, path, new EventMetadata());
                            }
                        } catch (final IOException e) {
                            String msg = String.format("Failed to open input stream for: %s. Reason: %s", transfer, e.getMessage());
                            errors.add(msg);
                            logger.error(msg, e);
                        }
                    }
                } catch (final IndyWorkflowException e) {
                    String msg = String.format("Failed to promote path: %s to: %s. Reason: %s", transfer, targetStore, e.getMessage());
                    errors.add(msg);
                    logger.error(msg, e);
                }
            });
        }
    } catch (InterruptedException e) {
        String error = String.format("Interrupted waiting for promotion lock on target: %s", targetKey);
        errors.add(error);
        logger.warn(error);
    } catch (final IndyDataException e) {
        String msg = String.format("Failed to retrieve artifact store: %s. Reason: %s", request.getSource(), e.getMessage());
        errors.add(msg);
        logger.error(msg, e);
    } finally {
        if (locked) {
            lock.unlock();
        }
    }
    String error = null;
    if (!errors.isEmpty()) {
        error = StringUtils.join(errors, "\n");
    }
    return new PathsPromoteResult(request, pending, complete, skipped, error, validation);
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) PathsPromoteResult(org.commonjava.indy.promote.model.PathsPromoteResult) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) StoreKey(org.commonjava.indy.model.core.StoreKey) EventMetadata(org.commonjava.maven.galley.event.EventMetadata) IndyDataException(org.commonjava.indy.data.IndyDataException) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) Transfer(org.commonjava.maven.galley.model.Transfer)

Example 28 with IndyDataException

use of org.commonjava.indy.data.IndyDataException in project indy by Commonjava.

the class KojiContentManagerDecorator method createRemoteRepository.

private RemoteRepository createRemoteRepository(StoreKey inStore, ArtifactRef artifactRef, final KojiBuildInfo build, final KojiSessionInfo session) throws KojiClientException {
    Logger logger = LoggerFactory.getLogger(getClass());
    try {
        KojiBuildArchiveCollection archiveCollection = kojiClient.listArchivesForBuild(build, session);
        boolean isBinaryBuild = isBinaryBuild(build);
        String name = getRepositoryName(build, isBinaryBuild);
        // Using a RemoteRepository allows us to use the higher-level APIs in Indy, as opposed to TransferManager
        final KojiRepositoryCreator creator = createRepoCreator();
        if (creator == null) {
            throw new KojiClientException("Cannot proceed without a valid KojiRepositoryCreator instance.");
        }
        RemoteRepository remote = creator.createRemoteRepository(inStore.getPackageType(), name, formatStorageUrl(build), config.getDownloadTimeoutSeconds());
        remote.setServerCertPem(config.getServerPemContent());
        if (isBinaryBuild) {
            remote.setMetadata(ArtifactStore.METADATA_ORIGIN, KOJI_ORIGIN_BINARY);
        } else {
            remote.setMetadata(ArtifactStore.METADATA_ORIGIN, KOJI_ORIGIN);
        }
        // set pathMaskPatterns using build output paths
        Set<String> patterns = new HashSet<>();
        patterns.addAll(archiveCollection.getArchives().stream().map(a -> a.getGroupId().replace('.', '/') + "/" + a.getArtifactId() + "/" + a.getVersion() + "/" + a.getFilename()).collect(Collectors.toSet()));
        remote.setPathMaskPatterns(patterns);
        remote.setMetadata(CREATION_TRIGGER_GAV, artifactRef.toString());
        remote.setMetadata(NVR, build.getNvr());
        final ChangeSummary changeSummary = new ChangeSummary(ChangeSummary.SYSTEM_USER, "Creating remote repository for Koji build: " + build.getNvr());
        storeDataManager.storeArtifactStore(remote, changeSummary, false, true, new EventMetadata());
        logger.debug("Koji {}, add pathMaskPatterns: {}", name, patterns);
        return remote;
    } catch (MalformedURLException e) {
        throw new KojiClientException("Koji add-on seems misconifigured. Could not generate URL to repo for " + "build: %s\nBase URL: %s\nError: %s", e, build.getNvr(), config.getStorageRootUrl(), e.getMessage());
    } catch (IOException e) {
        throw new KojiClientException("Failed to read server SSL PEM information from Koji configuration for new hosted repo: %s", e, e.getMessage());
    } catch (IndyDataException e) {
        throw new KojiClientException("Failed to store temporary remote repo: %s", e, e.getMessage());
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) RemoteRepository(org.commonjava.indy.model.core.RemoteRepository) IOException(java.io.IOException) Logger(org.slf4j.Logger) EventMetadata(org.commonjava.maven.galley.event.EventMetadata) IndyDataException(org.commonjava.indy.data.IndyDataException) KojiBuildArchiveCollection(com.redhat.red.build.koji.model.xmlrpc.KojiBuildArchiveCollection) KojiClientException(com.redhat.red.build.koji.KojiClientException) ChangeSummary(org.commonjava.indy.audit.ChangeSummary) HashSet(java.util.HashSet)

Example 29 with IndyDataException

use of org.commonjava.indy.data.IndyDataException in project indy by Commonjava.

the class KojiContentManagerDecorator method getTransfer.

@Override
public Transfer getTransfer(StoreKey storeKey, String path, TransferOperation op) throws IndyWorkflowException {
    ArtifactStore store;
    try {
        store = storeDataManager.getArtifactStore(storeKey);
    } catch (IndyDataException e) {
        throw new IndyWorkflowException("Cannot retrieve artifact store definition for: %s. Reason: %s", e, storeKey, e.getMessage());
    }
    if (store == null) {
        Logger logger = LoggerFactory.getLogger(getClass());
        logger.warn("No such store: {} (while retrieving transfer for path: {} (op: {})", storeKey, path, op);
        return null;
    }
    return getTransfer(store, path, op);
}
Also used : IndyDataException(org.commonjava.indy.data.IndyDataException) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) Logger(org.slf4j.Logger)

Example 30 with IndyDataException

use of org.commonjava.indy.data.IndyDataException in project indy by Commonjava.

the class IndyLocationResolver method resolve.

@Override
public Location resolve(final String spec) throws TransferException {
    ArtifactStore store;
    try {
        final StoreKey source = StoreKey.fromString(spec);
        if (source == null) {
            throw new TransferException("Failed to parse StoreKey (format: '[remote|hosted|group]:name') from: '%s'.");
        }
        store = dataManager.getArtifactStore(source);
    } catch (final IndyDataException e) {
        throw new TransferException("Cannot find ArtifactStore to match source key: %s. Reason: %s", e, spec, e.getMessage());
    }
    if (store == null) {
        throw new TransferException("Cannot find ArtifactStore to match source key: %s.", spec);
    }
    final KeyedLocation location = LocationUtils.toLocation(store);
    logger.debug("resolved source location: '{}' to: '{}'", spec, location);
    return location;
}
Also used : IndyDataException(org.commonjava.indy.data.IndyDataException) TransferException(org.commonjava.maven.galley.TransferException) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) StoreKey(org.commonjava.indy.model.core.StoreKey)

Aggregations

IndyDataException (org.commonjava.indy.data.IndyDataException)75 ArtifactStore (org.commonjava.indy.model.core.ArtifactStore)50 StoreKey (org.commonjava.indy.model.core.StoreKey)30 EventMetadata (org.commonjava.maven.galley.event.EventMetadata)26 IndyWorkflowException (org.commonjava.indy.IndyWorkflowException)24 ChangeSummary (org.commonjava.indy.audit.ChangeSummary)24 Transfer (org.commonjava.maven.galley.model.Transfer)19 ArrayList (java.util.ArrayList)17 Group (org.commonjava.indy.model.core.Group)17 IOException (java.io.IOException)16 Logger (org.slf4j.Logger)16 RemoteRepository (org.commonjava.indy.model.core.RemoteRepository)14 HashSet (java.util.HashSet)10 List (java.util.List)7 StoreType (org.commonjava.indy.model.core.StoreType)7 KeyedLocation (org.commonjava.indy.model.galley.KeyedLocation)7 HostedRepository (org.commonjava.indy.model.core.HostedRepository)6 ConcreteResource (org.commonjava.maven.galley.model.ConcreteResource)6 ContentGenerator (org.commonjava.indy.content.ContentGenerator)5 InputStream (java.io.InputStream)4