use of org.commonjava.indy.IndyWorkflowException 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);
}
use of org.commonjava.indy.IndyWorkflowException in project indy by Commonjava.
the class KojiMavenMetadataProvider method getMetadata.
@Override
@IndyMetrics(measure = @Measure(timers = @MetricNamed(name = IndyMetricsKojiNames.METHOD_MAVENMETADATA_GETMETADATA + IndyMetricsNames.TIMER), meters = @MetricNamed(name = IndyMetricsKojiNames.METHOD_MAVENMETADATA_GETMETADATA + IndyMetricsNames.METER)))
public Metadata getMetadata(StoreKey targetKey, String path) throws IndyWorkflowException {
Logger logger = LoggerFactory.getLogger(getClass());
if (group != targetKey.getType()) {
logger.debug("Not a group. Cannot supplement with metadata from Koji builds");
return null;
}
if (!kojiConfig.isEnabled()) {
logger.debug("Koji add-on is disabled.");
return null;
}
if (!kojiConfig.isEnabledFor(targetKey.getName())) {
logger.debug("Koji integration is not enabled for group: {}", targetKey);
return null;
}
File mdFile = new File(path);
File artifactDir = mdFile.getParentFile();
File groupDir = artifactDir == null ? null : artifactDir.getParentFile();
if (artifactDir == null || groupDir == null) {
logger.debug("Invalid groupId / artifactId directory structure: '{}' / '{}'", groupDir, artifactDir);
return null;
}
String groupId = groupDir.getPath().replace(File.separatorChar, '.');
String artifactId = artifactDir.getName();
ProjectRef ga = null;
try {
ga = new SimpleProjectRef(groupId, artifactId);
} catch (InvalidRefException e) {
logger.debug("Not a valid Maven GA: {}:{}. Skipping Koji metadata retrieval.", groupId, artifactId);
}
if (ga == null) {
logger.debug("Could not render a valid Maven GA for path: '{}'", path);
return null;
}
ReentrantLock lock;
synchronized (versionMetadataLocks) {
lock = versionMetadataLocks.get(ga);
if (lock == null) {
lock = new ReentrantLock();
versionMetadataLocks.put(ga, lock);
}
}
boolean locked = false;
try {
locked = lock.tryLock(kojiConfig.getLockTimeoutSeconds(), TimeUnit.SECONDS);
if (!locked) {
throw new IndyWorkflowException("Failed to acquire Koji GA version metadata lock on: %s in %d seconds.", ga, kojiConfig.getLockTimeoutSeconds());
}
Metadata metadata = versionMetadata.get(ga);
ProjectRef ref = ga;
if (metadata == null) {
try {
metadata = kojiClient.withKojiSession((session) -> {
// short-term caches to help improve performance a bit by avoiding xml-rpc calls.
Map<Integer, KojiBuildArchiveCollection> seenBuildArchives = new HashMap<>();
Set<Integer> seenBuilds = new HashSet<>();
List<KojiArchiveInfo> archives = kojiClient.listArchivesMatching(ref, session);
Set<SingleVersion> versions = new HashSet<>();
for (KojiArchiveInfo archive : archives) {
if (!archive.getFilename().endsWith(".pom")) {
logger.debug("Skipping non-POM: {}", archive.getFilename());
continue;
}
SingleVersion singleVersion = VersionUtils.createSingleVersion(archive.getVersion());
if (versions.contains(singleVersion)) {
logger.debug("Skipping already collected version: {}", archive.getVersion());
continue;
}
KojiBuildInfo build;
if (seenBuilds.contains(archive.getBuildId())) {
logger.debug("Skipping already seen build: {}", archive.getBuildId());
continue;
} else {
build = kojiClient.getBuildInfo(archive.getBuildId(), session);
seenBuilds.add(archive.getBuildId());
}
if (build == null) {
logger.debug("Cannot retrieve build info: {}. Skipping: {}", archive.getBuildId(), archive.getFilename());
continue;
}
if (build.getBuildState() != KojiBuildState.COMPLETE) {
logger.debug("Build: {} is not completed. The state is {}. Skipping.", build.getNvr(), build.getBuildState());
continue;
}
if (build.getTaskId() == null) {
logger.debug("Build: {} is not a real build. It looks like a binary import. Skipping.", build.getNvr());
// This is not a real build, it's a binary import.
continue;
}
boolean buildAllowed = false;
if (!kojiConfig.isTagPatternsEnabled()) {
buildAllowed = true;
} else {
logger.debug("Checking for builds/tags of: {}", archive);
List<KojiTagInfo> tags = kojiClient.listTags(build.getId(), session);
for (KojiTagInfo tag : tags) {
if (kojiConfig.isTagAllowed(tag.getName())) {
logger.debug("Koji tag: {} is allowed for proxying.", tag.getName());
buildAllowed = true;
break;
} else {
logger.debug("Koji tag: {} is not allowed for proxying.", tag.getName());
}
}
}
logger.debug("Checking if build passed tag whitelist check and doesn't collide with something in authority store (if configured)...");
if (buildAllowed && buildAuthority.isAuthorized(path, new EventMetadata(), ref, build, session, seenBuildArchives)) {
try {
logger.debug("Adding version: {} for: {}", archive.getVersion(), path);
versions.add(singleVersion);
} catch (InvalidVersionSpecificationException e) {
logger.warn(String.format("Encountered invalid version: %s for archive: %s. Reason: %s", archive.getVersion(), archive.getArchiveId(), e.getMessage()), e);
}
}
}
if (versions.isEmpty()) {
logger.debug("No versions found in Koji builds for metadata: {}", path);
return null;
}
List<SingleVersion> sortedVersions = new ArrayList<>(versions);
Collections.sort(sortedVersions);
Metadata md = new Metadata();
md.setGroupId(ref.getGroupId());
md.setArtifactId(ref.getArtifactId());
Versioning versioning = new Versioning();
versioning.setRelease(sortedVersions.get(versions.size() - 1).renderStandard());
versioning.setLatest(sortedVersions.get(versions.size() - 1).renderStandard());
versioning.setVersions(sortedVersions.stream().map(SingleVersion::renderStandard).collect(Collectors.toList()));
Date lastUpdated = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime();
versioning.setLastUpdated(new SimpleDateFormat(LAST_UPDATED_FORMAT).format(lastUpdated));
md.setVersioning(versioning);
return md;
});
} catch (KojiClientException e) {
throw new IndyWorkflowException("Failed to retrieve version metadata for: %s from Koji. Reason: %s", e, ga, e.getMessage());
}
Metadata md = metadata;
if (metadata != null) {
// FIXME: Need a way to listen for cache expiration and re-request this?
versionMetadata.execute((cache) -> cache.getAdvancedCache().put(ref, md, kojiConfig.getMetadataTimeoutSeconds(), TimeUnit.SECONDS));
}
}
return metadata;
} catch (InterruptedException e) {
logger.warn("Interrupted waiting for Koji GA version metadata lock on target: {}", ga);
} finally {
if (locked) {
lock.unlock();
}
}
logger.debug("Returning null metadata result for unknown reason (path: '{}')", path);
return null;
}
use of org.commonjava.indy.IndyWorkflowException in project indy by Commonjava.
the class MaintenanceHandler method deprecatedRescan.
@ApiOperation("[Deprecated] Rescan all content in the specified repository to re-initialize metadata, capture missing index keys, etc.")
@ApiResponse(code = 200, message = "Rescan was started successfully. (NOTE: There currently is no way to determine when rescanning is complete.)")
@Path("/rescan/{type: (hosted|group|remote)}/{name}")
@GET
@Deprecated
public Response deprecatedRescan(@ApiParam(value = "The type of store / repository", allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type, @ApiParam("The name of the store / repository") @PathParam("name") final String name) {
final StoreType storeType = StoreType.get(type);
String altPath = Paths.get("/api/admin/maint", MAVEN_PKG_KEY, type, name).toString();
final StoreKey key = new StoreKey(storeType, name);
Response response;
try {
contentController.rescan(key);
response = markDeprecated(Response.ok(), altPath).build();
} catch (final IndyWorkflowException e) {
logger.error(String.format("Failed to rescan: %s. Reason: %s", key, e.getMessage()), e);
response = formatResponse(e, rb -> markDeprecated(rb, altPath));
}
return response;
}
use of org.commonjava.indy.IndyWorkflowException in project indy by Commonjava.
the class MaintenanceHandler method rescan.
@ApiOperation("Rescan all content in the specified repository to re-initialize metadata, capture missing index keys, etc.")
@ApiResponse(code = 200, message = "Rescan was started successfully. (NOTE: There currently is no way to determine when rescanning is complete.)")
@Path("/rescan/{packageType}/{type: (hosted|group|remote)}/{name}")
@GET
public Response rescan(@ApiParam(value = "The package type (eg. maven, npm, generic-http)", required = true) @PathParam("packageType") final String packageType, @ApiParam(value = "The type of store / repository", allowableValues = "hosted,group,remote", required = true) @PathParam("type") final String type, @ApiParam("The name of the store / repository") @PathParam("name") final String name) {
final StoreKey key = new StoreKey(packageType, StoreType.get(type), name);
Response response;
try {
contentController.rescan(key);
response = Response.ok().build();
} catch (final IndyWorkflowException e) {
logger.error(String.format("Failed to rescan: %s. Reason: %s", key, e.getMessage()), e);
response = formatResponse(e);
}
return response;
}
use of org.commonjava.indy.IndyWorkflowException in project indy by Commonjava.
the class ReplicationHandler method replicate.
@ApiOperation("Replicate the stores of a remote Indy")
@ApiImplicitParams({ @ApiImplicitParam(paramType = "body", name = "body", dataType = "org.commonjava.indy.model.core.dto.ReplicationDTO", required = true, value = "The configuration determining how replication should be handled, and what remote site to replicate.") })
@POST
@Produces(ApplicationContent.application_json)
public Response replicate(@Context final HttpServletRequest request, @Context final SecurityContext securityContext) {
Response response;
try {
String user = securityManager.getUser(securityContext, request);
final ReplicationDTO dto = serializer.readValue(request.getInputStream(), ReplicationDTO.class);
final Set<StoreKey> replicated = controller.replicate(dto, user);
final Map<String, Object> params = new LinkedHashMap<String, Object>();
params.put("replicationCount", replicated.size());
params.put("items", replicated);
response = formatOkResponseWithJsonEntity(params, serializer);
} catch (final IndyWorkflowException | IOException e) {
logger.error(String.format("Replication failed: %s", e.getMessage()), e);
response = formatResponse(e);
}
return response;
}
Aggregations