Skip to content

Commit

Permalink
Add apis for gitlab retry (#191)
Browse files Browse the repository at this point in the history
* code style

* add gitlab retry get and put apis
  • Loading branch information
mcanoy authored Jul 5, 2022
1 parent cdabcee commit e394fbe
Show file tree
Hide file tree
Showing 20 changed files with 89 additions and 30 deletions.
1 change: 0 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
<sonar.organization>rht-labs</sonar.organization>
<sonar.host.url>https://sonarcloud.io</sonar.host.url>
<sonar.coverage.jacoco.xmlReportPaths>./target/jacoco-report/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
<jacoco.version>0.8.7</jacoco.version>
</properties>
<dependencyManagement>
<dependencies>
Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/redhat/labs/lodestar/model/Author.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.redhat.labs.lodestar.model;

import lombok.*;
import lombok.experimental.SuperBuilder;

@Data
@NoArgsConstructor
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/com/redhat/labs/lodestar/model/Engagement.java
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,11 @@ public class Engagement {
//also checked before PUT/POST actions
@DiffIgnore
private Boolean writeable;

@Deprecated

/*
@deprecated - delivered in a separate api separately
*/
@Deprecated(since = "2.0.0")
@DiffIgnore
private List<Commit> commits;
@JsonbProperty("creation_details")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import lombok.ToString;
import lombok.experimental.SuperBuilder;
import org.javers.core.metamodel.annotation.DiffIgnore;
import org.javers.core.metamodel.annotation.Id;

@Data
@ToString
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.javers.core.metamodel.annotation.Id;
import org.javers.core.metamodel.annotation.ValueObject;

@Data
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public Response getArtifacts(@Context UriInfo uriInfo,
}
}

return artifactService.getArtifacts(filterOptions, engagementUuid, type, region, dashboardView);
return artifactService.getArtifacts(filterOptions, engagementUuid, type, region);
}

@GET
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,36 @@ public Response delete(@PathParam("id") String uuid) {
engagementService.deleteEngagement(uuid);
return Response.accepted().build();
}

@GET
@Path("/gitlab/check")
@SecurityRequirement(name = "jwt")
@APIResponses(value = { @APIResponse(responseCode = "200", description = "Gitlab / DB comparison fetched") })
@Operation(summary = "Checks all engagements in the database vs what is in gitlab")
public Set<String> getGitlabSet() {
LOGGER.debug("checking gitlab");
return engagementService.getGitlabSet();
}

@PUT
@SecurityRequirement(name = "jwt")
@Path("/gitlab/repush")
@APIResponses(value = { @APIResponse(responseCode = "401", description = "Missing or Invalid JWT"),
@APIResponse(responseCode = "403", description = "Not authorized for engagement type"),
@APIResponse(responseCode = "404", description = "Engagement resource not found to update"),
@APIResponse(responseCode = "200", description = "Engagement resent to gitlab") })
@Operation(summary = "Resends engagement data to gitlab.")
public Response rePushChangesToGitlab(@QueryParam("uuid") String uuid, @QueryParam(value = "message") String message) {
LOGGER.debug("re-pushing {} to gitlab", uuid);

Engagement engagement = engagementService.getByUuid(uuid);
boolean writer = jwtUtils.isAllowedToWriteEngagement(jwt, configService.getPermission(engagement.getType()));
if(!writer) {
return forbiddenResponse(engagement.getType());
}

return engagementService.rePushChangesToGitlab(uuid, message);
}

private Response forbiddenResponse(String type) {
String message = String.format("{\"message\": \"You cannot modify %s engagements\"}", type);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,14 @@ List<Engagement> getEngagementsWithCategory(@QueryParam("page") int page, @Query
@Path("refresh/state")
Response refreshStates();

@GET
@Path("gitlab")
Set<String> getGitlabSet();

@PUT
@Path("retry")
Response rePushChangesToGitlab(@QueryParam("uuid") String uuid, @QueryParam("message") String message);

@GET
@Path("suggest")
Response suggest(@QueryParam("partial") String partial);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.List;
import java.util.Set;

@ApplicationScoped
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import javax.enterprise.context.*;
import javax.inject.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.time.Instant;
import java.util.*;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ public List<Artifact> getArtifacts(String engagementUuid) {
} catch (WebApplicationException wex) {
if(wex.getResponse().getStatus() >= 500) {
LOGGER.error("Artifact Server error ({}) from hosting env for euuid {}", wex.getResponse().getStatus(), engagementUuid);
return Collections.EMPTY_LIST;
return Collections.emptyList();
}
throw wex;
}
}

public Response getArtifacts(ListFilterOptions filterOptions, String engagementUuid, String type, List<String> region, boolean dashboardView) {
public Response getArtifacts(ListFilterOptions filterOptions, String engagementUuid, String type, List<String> region) {
Optional<Integer> pageO = filterOptions.getPage();
Optional<Integer> pageSizeO = filterOptions.getPerPage();
int page = pageO.orElse(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import org.eclipse.microprofile.rest.client.inject.RestClient;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,16 +199,16 @@ public Engagement update(Engagement engagement) {

//Validate participant options
Set<String> allowed = configService.getParticipantOptions(engagement.getType()).keySet();
String errors = "";
StringBuilder errors = new StringBuilder();
for(EngagementUser p : engagement.getEngagementUsers()) {
if(!allowed.contains(p.getRole())) {
errors += String.format("Participant %s has invalid role %s. ", p.getEmail(), p.getRole());
errors.append(String.format("Participant %s has invalid role %s. ", p.getEmail(), p.getRole()));
LOGGER.error("Participant {} has invalid role {} for engagement type {} - {}", p.getEmail(), p.getRole(), engagement.getType(), engagement.getUuid());
}
}

if(!errors.isEmpty()) {
throw new WebApplicationException(Response.status(400).entity(Map.of("lodestarMessage", errors.trim())).build());
if(!errors.toString().isEmpty()) {
throw new WebApplicationException(Response.status(400).entity(Map.of("lodestarMessage", errors.toString().trim())).build());
}
participants = participantService.updateParticipantsAndReload(engagementUuid, author, authorEmail,
engagement.getEngagementUsers());
Expand Down Expand Up @@ -296,7 +296,7 @@ public void updateStatusAndCommits(Hook hook) {
if (hook.didFileChange(statusFile)) {
LOGGER.debug("Status update {}", hook.getProjectId());
engagementStatusApiClient.updateEngagementStatus(engagement.getUuid());
Status status = engagementStatusApiClient.getEngagementStatus(engagement.getUuid());
//Status status = engagementStatusApiClient.getEngagementStatus(engagement.getUuid());
//engagementService.setStatus(engagement.getUuid(), status);
//TODO put this status in the magical cache
}
Expand Down Expand Up @@ -441,4 +441,12 @@ public Response refreshState() {
return engagementApiClient.refreshStates();
}

public Set<String> getGitlabSet() {
return engagementApiClient.getGitlabSet();
}

public Response rePushChangesToGitlab(String uuid, String message) {
return engagementApiClient.rePushChangesToGitlab(uuid, message);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import com.redhat.labs.lodestar.model.Engagement;
import com.redhat.labs.lodestar.model.EngagementUser;
import com.redhat.labs.lodestar.model.event.EventType;
import com.redhat.labs.lodestar.model.filter.FilterOptions;
import com.redhat.labs.lodestar.rest.client.ParticipantApiClient;

import io.quarkus.vertx.ConsumeEvent;
Expand All @@ -39,7 +38,7 @@ public List<EngagementUser> getParticipantsForEngagement(String engagementUuid)
} catch (WebApplicationException wex) {
if(wex.getResponse().getStatus() >= 500) {
LOGGER.error("Participant Server error ({}) from hosting env for euuid {}", wex.getResponse().getStatus(), engagementUuid);
return Collections.EMPTY_LIST;
return Collections.emptyList();
}
throw wex;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,6 @@ void testGetEngagementUserSummary() {
@Test
void testGetEngagementUserSummaryRegion() {

String token = TokenUtils.generateTokenString("/JwtClaimsWriter.json");

Map<String, Long> enabled = new HashMap<>();
enabled.put("Red Hat", 1000000000L);
enabled.put("Others", 6L);
Expand All @@ -290,7 +288,7 @@ void testGetEngagementUserSummaryRegion() {
.queryParam("search", "engagement_region=na")
.when()
.auth()
.oauth2(token)
.oauth2(validToken)
.get("/engagements/users/summary")
.then()
.statusCode(200).body("all_users_count", equalTo(1000000006))
Expand All @@ -309,12 +307,20 @@ void testGetEngagementUserSummaryRegion() {
.queryParam("search", "not_engagement_region=na")
.when()
.auth()
.oauth2(token)
.oauth2(validToken)
.get("/engagements/users/summary")
.then()
.statusCode(200).body("all_users_count", equalTo(12))
.body("other_users_count", equalTo(5))
.body("rh_users_count", equalTo(7));

}

@Test
void testGitlabCheck() {
Mockito.when(engagementApiClient.getGitlabSet()).thenReturn(Set.of("yo"));

given().when().auth().oauth2(validToken).get("/engagements/gitlab/check").then()
.statusCode(200).body("size()", equalTo(1)).body("[0]", equalTo("yo"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -348,5 +348,21 @@ void testPutEngagementWithConflictingSubdomain() {
.statusCode(409);

}

@Test
void retryGitlabEngagement() {
Engagement engagement = Engagement.builder().uuid("1234").customerName("Customer").projectName("Project").type("Residency").build();
Mockito.when(engagementApiClient.getEngagement("1234")).thenReturn(engagement);
Mockito.when(engagementApiClient.rePushChangesToGitlab("1234", "message")).thenReturn(Response.ok().build());

given().when().auth().oauth2(validToken).queryParam("uuid", "1234").queryParam("message", "message")
.put("/engagements/gitlab/repush").then().statusCode(200);

engagement = Engagement.builder().uuid("1235").customerName("Customer").projectName("Project").type("xxx").build();
Mockito.when(engagementApiClient.getEngagement("1235")).thenReturn(engagement);

given().when().auth().oauth2(validToken).queryParam("uuid", "1235").queryParam("message", "message")
.put("/engagements/gitlab/repush").then().statusCode(403);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

@QuarkusTest
@Tag("nested")
public class HostingEnvironmentResourceTest {
class HostingEnvironmentResourceTest {

@InjectMock
@RestClient
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ void testStatusValid() {
Mockito.verify(engagementApiClient).getEngagementByProject(8675309);
Mockito.verify(engagementApiClient).getEngagement("uuid1");
Mockito.verify(engagementStatusApiClient).updateEngagementStatus("uuid1");
Mockito.verify(engagementStatusApiClient).getEngagementStatus("uuid1");
//Mockito.verify(engagementStatusApiClient).getEngagementStatus("uuid1");
Mockito.verify(activityApiClient).getActivityForUuid("uuid1");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ class EngagementServiceTest {
ActivityService activityService;

@BeforeEach
public void setUp() {
void setUp() {
String uuid = "uuid";
Mockito.when(engagementApiClient.getEngagement(uuid)).thenReturn(Engagement.builder().uuid("uuid").lastUpdate(lastUpdate).build());
Mockito.when(hostingService.getHostingEnvironments(uuid)).thenReturn(Collections.emptyList());
Expand All @@ -61,7 +61,7 @@ public void setUp() {
}

@Test
public void testParticipantValid() {
void testParticipantValid() {
EngagementUser participant = EngagementUser.builder().email("[email protected]").firstName("Kevin").lastName("RH").role("monkey").build();
Engagement engagement = Engagement.builder().uuid("uuid").type("Res").lastUpdate(lastUpdate).engagementUsers(Set.of(participant)).build();
engagementService.update(engagement);
Expand All @@ -70,7 +70,7 @@ public void testParticipantValid() {

@Test
@SuppressWarnings("unchecked")
public void testParticipantInValid() {
void testParticipantInValid() {
EngagementUser participant = EngagementUser.builder().email("[email protected]").firstName("Kevin").lastName("RH").role("Chef").build();
Engagement engagement = Engagement.builder().uuid("uuid").type("Res").lastUpdate(lastUpdate).engagementUsers(Set.of(participant)).build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ void setup() {

users = Collections.singleton(EngagementUser.builder().build());
Engagement engagement = Engagement.builder().uuid("1").region("na").engagementUsers(users).build();
Mockito.when(engagementService.getByUuid(Mockito.eq("1"))).thenReturn(engagement);
Mockito.when(engagementService.getByUuid("1")).thenReturn(engagement);

Mockito.when(participantClient.updateParticipants("1", "na", "b", "c", users)).thenReturn(Response.ok().build());
Mockito.when(participantClient.updateParticipants("1", "na", "x", "c", users)).thenThrow(new WebApplicationException());
Expand Down

0 comments on commit e394fbe

Please sign in to comment.