Skip to content

Commit

Permalink
[Build-trigger-45] Providing more robust messages
Browse files Browse the repository at this point in the history
  • Loading branch information
khermano committed Oct 10, 2024
1 parent d97ee64 commit 31b8845
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 24 deletions.
7 changes: 6 additions & 1 deletion src/main/java/org/jboss/set/BuildTrigger.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.logging.Logger;
import org.jboss.set.model.json.BuildJMSTriggerPayload;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
Expand All @@ -13,6 +14,8 @@
@ApplicationScoped
public class BuildTrigger {

Logger logger = Logger.getLogger(BuildTrigger.class);

@ConfigProperty(name = "build-trigger.topic")
String triggerTopic;

Expand All @@ -25,7 +28,9 @@ public void triggerBuild(BuildJMSTriggerPayload payloadMessage) {
try (JMSContext context = connectionFactory.createContext(Session.AUTO_ACKNOWLEDGE)) {
context.createProducer().send(context.createTopic(triggerTopic), objectMapper.writeValueAsString(payloadMessage));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
logger.errorf("Failed to serialize BuildJMSTriggerPayload to JSON: "
+ e.getMessage() + ". Payload: " + payloadMessage);
throw new RuntimeException("Failed to serialize BuildJMSTriggerPayload to JSON: " + e.getMessage(), e);
}
}
}
20 changes: 14 additions & 6 deletions src/main/java/org/jboss/set/BuildTriggerResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,27 +38,35 @@ public class BuildTriggerResource {
public Response triggerBuild(@NotNull @Valid BuildInfo buildInfo) {
String email = idToken.claim(Claims.email).orElse("Email not provided in the token").toString();
if (buildInfo.streams == null || buildInfo.streams.isEmpty()) {
return Response.status(400, "List of streams is empty").build();
return Response.status(400, "The list of streams cannot be null or empty. "
+ "Please provide valid streams.").build();
}
logger.infof("Triggering build for product %s by %s", buildInfo, email);

buildTrigger.triggerBuild(BuildJMSTriggerPayload.from(buildInfo, email));

return Response.ok("Triggered build for " + buildInfo.gitRepo + ":" + buildInfo.projectVersion).build();
return Response.ok("Build triggered successfully for repository " + buildInfo.gitRepo
+ ", version: " + buildInfo.projectVersion).build();
}

@GET
@Path("/getBuildInfo")
public Response getBuildInfoFromGit(@NotNull @Valid @QueryParam("tag") String url) {
logger.info("Fetching remote repository: " + url);
logger.infof("Fetching remote repository: " + url);
try {
BuildInfo buildInfo = gitBuildInfoAssembler.constructBuildFromURL(new URL(url));
if (buildInfo == null) {
return Response.noContent().build();
return Response.status(Response.Status.NO_CONTENT)
.entity(String.format("No build information available for the given URL: %s", url))
.build();
}
return Response.ok(buildInfo).build();

logger.infof("Successfully fetched build information for URL: %s", url);
return Response.ok(buildInfo)
.entity(String.format("Build information fetched successfully for URL: %s", url))
.build();
} catch (MalformedURLException e) {
logger.error("Invalid URL. Cannot obtain tag data.");
logger.errorf("Invalid URL format provided: %s. Exception: %s", url, e.getMessage());
return null;
}
}
Expand Down
23 changes: 12 additions & 11 deletions src/main/java/org/jboss/set/GitBuildInfoAssembler.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@ public BuildInfo constructBuildFromURL(URL tagUrl) {
if (splitURL.length < 3) {
// Valid URL is always <host>/<repo>/<project>/../<tag>
// This applies to Github and Gitlab
logger.warn("Invalid URL, returning null");
logger.warnf("Invalid URL format provided. The URL must be in the format <host>/<repo>/<project>/../<tag> for Gitlab/Github. "
+ "URL: " + tagUrl + ". Returning null.");
return null;
}
if (tagUrl.getHost().equals("gitlab.cee.redhat.com")) {
Expand All @@ -64,7 +65,7 @@ public BuildInfo constructBuildFromURL(URL tagUrl) {
if (tagUrl.getHost().contains("gitlab.")) {
return constructGitlabBuild(splitURL, tagUrl, false);
}
logger.warnf("%s is unsupported, only Github and Gitlab are supported at this moment.", tagUrl.getHost());
logger.warnf("Unsupported host: %s. Currently, only GitHub and GitLab hosts are supported.", tagUrl.getHost());
return null;
}

Expand All @@ -77,12 +78,12 @@ private BuildInfo constructGithubBuild(String[] splitUrl, URL tagUrl) {
try {
refsJson = githubRestClient.getRefsInfo(codeSpace, repository, version, "Bearer " + githubKey);
} catch (ClientWebApplicationException e) {
logger.errorf("Failed to retrieve refs info for %s in constructGithubBuild", tagUrl.toString());
throw new GitRestClientException("Failed to retrieve refs info from Github: " + e.getMessage(), e, e.getResponse());
logger.errorf("Failed to retrieve reference info for URL: %s from GitHub. Exception: %s", tagUrl.toString(), e.getMessage());
throw new GitRestClientException("Failed to retrieve refs info from Github. " + e.getMessage(), e, e.getResponse());
}

if (refsJson == null) {
logger.warnf("Failed to create BuildInfo for %s", tagUrl.toString());
logger.warnf("GitHub API returned null for reference info for URL: %s", tagUrl.toString());
return null;
}

Expand All @@ -93,12 +94,12 @@ private BuildInfo constructGithubBuild(String[] splitUrl, URL tagUrl) {
try {
tagJson = githubRestClient.getTagInfo(codeSpace, repository, commitSHA, "Bearer " + githubKey);
} catch (ClientWebApplicationException e) {
logger.errorf("Failed to retrieve tag info for %s in constructGithubBuild", tagUrl.toString());
throw new GitRestClientException("Failed to retrieve tag info from Github: " + e.getMessage(), e, e.getResponse());
logger.errorf("Failed to retrieve tag info for URL: %s from GitHub. Exception: %s", tagUrl.toString(), e.getMessage());
throw new GitRestClientException("Failed to retrieve tag info from Github. " + e.getMessage(), e, e.getResponse());
}

if (tagJson == null) {
logger.warnf("Failed to retrieve tag info for %s", tagUrl.toString());
logger.warnf("GitHub API returned null for tag info for URL: %s", tagUrl.toString());
return null;
}
commitSHA = tagJson.path(OBJECT).path(SHA).asText(); // Update SHA from tag info
Expand All @@ -117,14 +118,14 @@ private BuildInfo constructGitlabBuild(String[] splitUrl, URL tagUrl, boolean is
gitlabCeeRestClient.getTagInfo(codeSpace + "/" + repository, version, "Bearer " + gitlabKey) :
gitlabRestClient.getTagInfo(codeSpace + "/" + repository, version);
} catch (ClientWebApplicationException e) {
logger.errorf("Failed to retrieve tag info for %s in constructGitlabBuild", tagUrl.toString());
throw new GitRestClientException("Failed to retrieve tag info from Gitlab: " + e.getMessage(), e, e.getResponse());
logger.errorf("Failed to retrieve tag info for URL: %s from GitLab. Exception: %s", tagUrl.toString(), e.getMessage());
throw new GitRestClientException("Failed to retrieve tag info from Gitlab. " + e.getMessage(), e, e.getResponse());
}

if (tagJson != null) {
return buildBuildInfo(tagUrl, codeSpace, repository, tagJson.get(NAME).textValue(), tagJson.get(COMMIT).get(ID).textValue());
}
logger.warnf("Failed to create BuildInfo for %s", tagUrl.toString());
logger.warnf("GitLab API returned null for tag info for URL: %s", tagUrl.toString());
return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,24 @@ public class GitRestClientExceptionMapper implements ExceptionMapper<GitRestClie
public Response toResponse(GitRestClientException exception) {
int responseCode = exception.getResponse().getStatus();

logger.error(String.format("Invocation returned HTTP %s %s", responseCode, exception.getResponse().getStatusInfo().getReasonPhrase()));
logger.errorf(String.format("Invocation returned HTTP %s %s", responseCode, exception.getResponse().getStatusInfo().getReasonPhrase()));

switch (responseCode) {
case 404 -> {
logger.warn("Requested tag not found");
logger.warnf("Requested tag not found. %s", exception.getMessage());
return Response.status(404)
.entity(exception.getMessage())
.build();
}
case 403 -> {
logger.warn("Access denied. This is likely caused by expired token, please contact Build Trigger owners");
logger.warnf("Access denied. This is likely caused by expired token, please contact Build Trigger owners. %s"
, exception.getMessage());
return Response.status(403)
.entity(exception.getMessage())
.build();
}
default -> {
logger.warnf("An unexpected error occurred. %s", exception.getMessage());
return Response.status(500)
.entity(exception.getMessage())
.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,12 @@ public HealthCheckResponse call() {
connection.stop();
return HealthCheckResponse.up(HC_NAME);
} catch (JMSException e) {
String errorMessage = String.format("JMS connection failed in HealthCheck for %s. Cause: %s", HC_NAME, e.getMessage());
return HealthCheckResponse.builder()
.name(HC_NAME)
.down()
.withData("exception", e.toString())
.withData("error", errorMessage)
.withData("exception", e.getClass().getName())
.build();
}
}
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/org/jboss/set/model/json/Stream.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.jboss.set.model.json;

import org.jboss.logging.Logger;
import org.jboss.set.exception.UnknownStreamException;

public enum Stream {
Expand All @@ -9,6 +10,8 @@ public enum Stream {
XP_4_0_X("XP 4.0.x", "eap-xp:4.0.x"),
XP_5_0_X("XP 5.0.x", "eap-xp:5.0.x");

static final Logger logger = Logger.getLogger(Stream.class);

public final String frontEnd;
public final String backEnd;

Expand All @@ -23,6 +26,7 @@ public static String getJsonStreamName(String streamFromFrontend) {
return stream.backEnd;
}
}
throw new UnknownStreamException("Unknown stream");
logger.errorf("Unknown stream: '%s'.", streamFromFrontend);
throw new UnknownStreamException("Unknown stream: '" + streamFromFrontend + "'.");
}
}
2 changes: 1 addition & 1 deletion src/test/java/org/jboss/set/BuildTriggerResourceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ public void testTriggerEndpoint() throws Exception {
.when().post("/build-trigger/trigger")
.then()
.statusCode(200)
.body(is("Triggered build for " + BUILD_INFO_GIT_REPO + ":" + BUILD_INFO_PROJECT_VERSION));
.body(is("Build triggered successfully for repository " + BUILD_INFO_GIT_REPO + ", version: " + BUILD_INFO_PROJECT_VERSION));

Mockito.verify(buildTrigger, Mockito.times(1))
.triggerBuild(Mockito.argThat(x -> {
Expand Down

0 comments on commit 31b8845

Please sign in to comment.