Search in sources :

Example 51 with ArtifactStore

use of org.commonjava.indy.model.core.ArtifactStore in project indy by Commonjava.

the class StoreAdminHandler method getAll.

@ApiOperation("Retrieve the definitions of all artifact stores of a given type on the system")
@ApiResponses({ @ApiResponse(code = 200, response = StoreListingDTO.class, message = "The store definitions") })
@GET
@Produces(ApplicationContent.application_json)
public Response getAll(@ApiParam("Filter only stores that support the package type (eg. maven, npm). NOTE: '_all' returns all.") @PathParam("packageType") final String packageType, @ApiParam(allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type) {
    final StoreType st = StoreType.get(type);
    Response response;
    try {
        final List<ArtifactStore> stores = adminController.getAllOfType(packageType, st);
        logger.info("Returning listing containing stores:\n\t{}", new JoinString("\n\t", stores));
        final StoreListingDTO<ArtifactStore> dto = new StoreListingDTO<>(stores);
        response = formatOkResponseWithJsonEntity(dto, objectMapper);
    } catch (final IndyWorkflowException e) {
        logger.error(e.getMessage(), e);
        response = formatResponse(e);
    }
    return response;
}
Also used : StoreType(org.commonjava.indy.model.core.StoreType) Response(javax.ws.rs.core.Response) ResponseUtils.formatResponse(org.commonjava.indy.bind.jaxrs.util.ResponseUtils.formatResponse) ApiResponse(io.swagger.annotations.ApiResponse) StoreListingDTO(org.commonjava.indy.model.core.dto.StoreListingDTO) JoinString(org.commonjava.maven.atlas.ident.util.JoinString) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 52 with ArtifactStore

use of org.commonjava.indy.model.core.ArtifactStore in project indy by Commonjava.

the class MavenMetadataGenerator method generateDirectoryContent.

@Override
public List<StoreResource> generateDirectoryContent(final ArtifactStore store, final String path, final List<StoreResource> existing, final EventMetadata eventMetadata) throws IndyWorkflowException {
    final StoreResource mdResource = new StoreResource(LocationUtils.toLocation(store), Paths.get(path, MavenMetadataMerger.METADATA_NAME).toString());
    if (existing.contains(mdResource)) {
        return null;
    }
    int pathElementsCount = StringUtils.strip(path, "/").split("/").length;
    // if there is a possibility we are listing an artifactId
    if (pathElementsCount >= 2) {
        // regardless, we will need this first level of listings. What we do with it will depend on the logic below...
        final List<StoreResource> firstLevelFiles = fileManager.listRaw(store, path);
        ArtifactPathInfo samplePomInfo = null;
        for (final StoreResource topResource : firstLevelFiles) {
            final String topPath = topResource.getPath();
            if (topPath.endsWith(".pom")) {
                samplePomInfo = ArtifactPathInfo.parse(topPath);
                break;
            }
        }
        // if this dir does not contain a pom check if a subdir contain a pom
        if (samplePomInfo == null) {
            List<String> firstLevelDirs = firstLevelFiles.stream().map((res) -> res.getPath()).filter((subpath) -> subpath.endsWith("/")).collect(Collectors.toList());
            final Map<String, List<StoreResource>> secondLevelMap = fileManager.listRaw(store, firstLevelDirs);
            nextTopResource: for (final String topPath : firstLevelDirs) {
                final List<StoreResource> secondLevelListing = secondLevelMap.get(topPath);
                for (final StoreResource fileResource : secondLevelListing) {
                    if (fileResource.getPath().endsWith(".pom")) {
                        if (samplePomInfo == null) {
                            samplePomInfo = ArtifactPathInfo.parse(fileResource.getPath());
                            break nextTopResource;
                        }
                        continue nextTopResource;
                    }
                }
            }
        }
        // We won't worry about this for now.
        if (samplePomInfo != null) {
            final List<StoreResource> result = new ArrayList<StoreResource>();
            result.add(mdResource);
            result.add(new StoreResource(LocationUtils.toLocation(store), Paths.get(path, MavenMetadataMerger.METADATA_MD5_NAME).toString()));
            result.add(new StoreResource(LocationUtils.toLocation(store), Paths.get(path, MavenMetadataMerger.METADATA_SHA_NAME).toString()));
            return result;
        }
    }
    return null;
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) SingleVersion(org.commonjava.maven.atlas.ident.version.SingleVersion) MergedContentAction(org.commonjava.indy.content.MergedContentAction) PathUtils.normalize(org.commonjava.maven.galley.util.PathUtils.normalize) HashMap(java.util.HashMap) Group(org.commonjava.indy.model.core.Group) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) HashSet(java.util.HashSet) VersionUtils(org.commonjava.maven.atlas.ident.util.VersionUtils) Transfer(org.commonjava.maven.galley.model.Transfer) IndyWorkflowException(org.commonjava.indy.IndyWorkflowException) TransferOperation(org.commonjava.maven.galley.model.TransferOperation) Document(org.w3c.dom.Document) SimpleTypeAndClassifier(org.commonjava.maven.atlas.ident.ref.SimpleTypeAndClassifier) Map(java.util.Map) GalleyMavenXMLException(org.commonjava.maven.galley.maven.parse.GalleyMavenXMLException) PathUtils.parentPath(org.commonjava.maven.galley.util.PathUtils.parentPath) TypeAndClassifier(org.commonjava.maven.atlas.ident.ref.TypeAndClassifier) OutputStream(java.io.OutputStream) GroupMergeHelper(org.commonjava.indy.core.content.group.GroupMergeHelper) MavenMetadataMerger(org.commonjava.indy.pkg.maven.content.group.MavenMetadataMerger) LocationUtils(org.commonjava.indy.util.LocationUtils) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) IOUtils.closeQuietly(org.apache.commons.io.IOUtils.closeQuietly) StoreType(org.commonjava.indy.model.core.StoreType) Set(java.util.Set) IOException(java.io.IOException) NotFoundCache(org.commonjava.maven.galley.spi.nfc.NotFoundCache) Collectors(java.util.stream.Collectors) File(java.io.File) SnapshotPart(org.commonjava.maven.atlas.ident.version.part.SnapshotPart) List(java.util.List) Element(org.w3c.dom.Element) Paths(java.nio.file.Paths) EventMetadata(org.commonjava.maven.galley.event.EventMetadata) TypeMapper(org.commonjava.maven.galley.maven.spi.type.TypeMapper) StoreResource(org.commonjava.indy.content.StoreResource) XMLInfrastructure(org.commonjava.maven.galley.maven.parse.XMLInfrastructure) TypeMapping(org.commonjava.maven.galley.model.TypeMapping) AbstractMergedContentGenerator(org.commonjava.indy.core.content.AbstractMergedContentGenerator) ArtifactPathInfo(org.commonjava.maven.atlas.ident.util.ArtifactPathInfo) Collections(java.util.Collections) DirectContentAccess(org.commonjava.indy.content.DirectContentAccess) StoreDataManager(org.commonjava.indy.data.StoreDataManager) SnapshotUtils(org.commonjava.maven.atlas.ident.util.SnapshotUtils) StoreResource(org.commonjava.indy.content.StoreResource) ArtifactPathInfo(org.commonjava.maven.atlas.ident.util.ArtifactPathInfo) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 53 with ArtifactStore

use of org.commonjava.indy.model.core.ArtifactStore in project indy by Commonjava.

the class PromotionManager method rollbackPathsPromote.

/**
     * Attempt to rollbackPathsPromote a previously failing {@link PathsPromoteResult}. This is meant to handle cases where an unrecoverable error
     * occurs on the server side, and promotion can NOT proceed afterward. All paths in the completed paths set are deleted from the target, if
     * possible. The output {@link PathsPromoteResult} contains the previous content, with any successfully removed target paths moved back from the
     * completed-paths list to the pending-paths list. If an error occurs during rollbackPathsPromote, the error field will be set...otherwise, it will be null.
     *
     * @param result The result to rollbackPathsPromote
     *
     * @return The same result, with any successful deletions moved from the completed to pending paths list, and the error cleared (or set to a
     * new error)
     *
     * @throws PromotionException
     * @throws IndyWorkflowException
     */
public PathsPromoteResult rollbackPathsPromote(final PathsPromoteResult result) throws PromotionException, IndyWorkflowException {
    StoreKey targetKey = result.getRequest().getTarget();
    ReentrantLock lock;
    synchronized (byPathTargetLocks) {
        lock = byPathTargetLocks.get(targetKey);
        if (lock == null) {
            lock = new ReentrantLock();
            byPathTargetLocks.put(targetKey, lock);
        }
    }
    final List<Transfer> contents = getTransfersForPaths(targetKey, result.getCompletedPaths());
    final Set<String> completed = result.getCompletedPaths();
    final Set<String> skipped = result.getSkippedPaths();
    if (completed == null || completed.isEmpty()) {
        result.setError(null);
        return result;
    }
    Set<String> pending = result.getPendingPaths();
    pending = pending == null ? new HashSet<String>() : new HashSet<String>(pending);
    String error = null;
    final boolean copyToSource = result.getRequest().isPurgeSource();
    ArtifactStore source = null;
    try {
        source = storeManager.getArtifactStore(result.getRequest().getSource());
    } catch (final IndyDataException e) {
        error = String.format("Failed to retrieve artifact store: %s. Reason: %s", result.getRequest().getSource(), e.getMessage());
        logger.error(error, e);
    }
    boolean locked = false;
    try {
        if (error == null) {
            locked = lock.tryLock(config.getLockTimeoutSeconds(), TimeUnit.SECONDS);
            if (!locked) {
                error = String.format("Failed to acquire promotion lock on target: %s in %d seconds.", targetKey, config.getLockTimeoutSeconds());
                logger.warn(error);
            }
        }
        if (error == null) {
            for (final Transfer transfer : contents) {
                if (transfer != null && transfer.exists()) {
                    InputStream stream = null;
                    try {
                        if (copyToSource) {
                            stream = transfer.openInputStream(true);
                            final String path = transfer.getPath();
                            contentManager.store(source, path, stream, TransferOperation.UPLOAD, new EventMetadata());
                            stream.close();
                        }
                        transfer.delete(true);
                        completed.remove(transfer.getPath());
                        pending.add(transfer.getPath());
                    } catch (final IOException e) {
                        error = String.format("Failed to rollback path promotion of: %s from: %s. Reason: %s", transfer, result.getRequest().getSource(), e.getMessage());
                        logger.error(error, e);
                    } finally {
                        closeQuietly(stream);
                    }
                }
            }
        }
    } catch (InterruptedException e) {
        error = String.format("Interrupted waiting for promotion lock on target: %s", targetKey);
        logger.warn(error);
    } finally {
        if (locked) {
            lock.unlock();
        }
    }
    return new PathsPromoteResult(result.getRequest(), pending, completed, skipped, error, new ValidationResult());
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) InputStream(java.io.InputStream) PathsPromoteResult(org.commonjava.indy.promote.model.PathsPromoteResult) IOException(java.io.IOException) ValidationResult(org.commonjava.indy.promote.model.ValidationResult) 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) Transfer(org.commonjava.maven.galley.model.Transfer) HashSet(java.util.HashSet)

Example 54 with ArtifactStore

use of org.commonjava.indy.model.core.ArtifactStore in project indy by Commonjava.

the class PromotionValidator method getRequestStore.

private ArtifactStore getRequestStore(PromoteRequest promoteRequest, String baseUrl) throws PromotionValidationException {
    final ArtifactStore store;
    final Logger logger = LoggerFactory.getLogger(getClass());
    if (needTempRepo(promoteRequest)) {
        logger.info("Promotion temporary repo is needed for {}, points to {} ", promoteRequest.getSource(), baseUrl);
        final PathsPromoteRequest pathsReq = (PathsPromoteRequest) promoteRequest;
        String tempName = PROMOTE_REPO_PREFIX + "tmp_" + pathsReq.getSource().getName() + new SimpleDateFormat("yyyyMMdd.hhmmss.SSSZ").format(new Date());
        final RemoteRepository tempRemote = new RemoteRepository(tempName, baseUrl);
        tempRemote.setPathMaskPatterns(pathsReq.getPaths());
        store = tempRemote;
        try {
            final ChangeSummary changeSummary = new ChangeSummary(ChangeSummary.SYSTEM_USER, "create temp remote repository");
            storeDataMgr.storeArtifactStore(tempRemote, changeSummary, false, true, new EventMetadata());
        } catch (IndyDataException e) {
            throw new PromotionValidationException("Can not store the temp remote repository correctly", e);
        }
    } else {
        logger.info("Promotion temporary repo is not needed for {} ", promoteRequest.getSource());
        try {
            store = storeDataMgr.getArtifactStore(promoteRequest.getSource());
        } catch (IndyDataException e) {
            throw new PromotionValidationException("Failed to retrieve source ArtifactStore: {}. Reason: {}", e, promoteRequest.getSource(), e.getMessage());
        }
    }
    return store;
}
Also used : IndyDataException(org.commonjava.indy.data.IndyDataException) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) PathsPromoteRequest(org.commonjava.indy.promote.model.PathsPromoteRequest) RemoteRepository(org.commonjava.indy.model.core.RemoteRepository) Logger(org.slf4j.Logger) ChangeSummary(org.commonjava.indy.audit.ChangeSummary) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) EventMetadata(org.commonjava.maven.galley.event.EventMetadata)

Example 55 with ArtifactStore

use of org.commonjava.indy.model.core.ArtifactStore in project indy by Commonjava.

the class ListStoresByTypeTest method listByType.

@Test
public void listByType() throws Exception {
    final Set<ArtifactStore> hosteds = new HashSet<>();
    for (int i = 0; i < 3; i++) {
        final HostedRepository repo = new HostedRepository(newName());
        assertThat(client.stores().create(repo, name.getMethodName(), HostedRepository.class), notNullValue());
        hosteds.add(repo);
    }
    final Set<ArtifactStore> remotes = new HashSet<>();
    for (int i = 0; i < 3; i++) {
        final RemoteRepository repo = new RemoteRepository(newName(), newUrl());
        assertThat(client.stores().create(repo, name.getMethodName(), RemoteRepository.class), notNullValue());
        remotes.add(repo);
    }
    final Set<ArtifactStore> groups = new HashSet<>();
    for (int i = 0; i < 3; i++) {
        final Group repo = new Group(newName());
        assertThat(client.stores().create(repo, name.getMethodName(), Group.class), notNullValue());
        groups.add(repo);
    }
    // Now, start listing by type and verify that ONLY those of the given type are present
    checkListing(client.stores().listHostedRepositories(), hosteds, Arrays.asList(remotes, groups));
    checkListing(client.stores().listRemoteRepositories(), remotes, Arrays.asList(groups, hosteds));
    checkListing(client.stores().listGroups(), groups, Arrays.asList(hosteds, remotes));
}
Also used : Group(org.commonjava.indy.model.core.Group) ArtifactStore(org.commonjava.indy.model.core.ArtifactStore) RemoteRepository(org.commonjava.indy.model.core.RemoteRepository) HashSet(java.util.HashSet) HostedRepository(org.commonjava.indy.model.core.HostedRepository) Test(org.junit.Test)

Aggregations

ArtifactStore (org.commonjava.indy.model.core.ArtifactStore)93 IndyDataException (org.commonjava.indy.data.IndyDataException)54 StoreKey (org.commonjava.indy.model.core.StoreKey)46 IndyWorkflowException (org.commonjava.indy.IndyWorkflowException)35 Logger (org.slf4j.Logger)30 ArrayList (java.util.ArrayList)25 Transfer (org.commonjava.maven.galley.model.Transfer)25 Group (org.commonjava.indy.model.core.Group)20 StoreType (org.commonjava.indy.model.core.StoreType)19 IOException (java.io.IOException)18 EventMetadata (org.commonjava.maven.galley.event.EventMetadata)17 HashSet (java.util.HashSet)15 List (java.util.List)15 LoggerFactory (org.slf4j.LoggerFactory)11 Inject (javax.inject.Inject)10 StoreDataManager (org.commonjava.indy.data.StoreDataManager)10 RemoteRepository (org.commonjava.indy.model.core.RemoteRepository)10 JoinString (org.commonjava.maven.atlas.ident.util.JoinString)10 Test (org.junit.Test)9 ApiOperation (io.swagger.annotations.ApiOperation)8