Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Include notification into polling #15

Merged
merged 4 commits into from
Nov 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -3,11 +3,14 @@

import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import java.util.Map;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import rocks.inspectit.gepard.agentmanager.configuration.service.ConfigurationService;
import rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService;
import rocks.inspectit.gepard.config.model.InspectitConfiguration;

@RestController
@@ -16,17 +19,27 @@
public class ConfigurationController {

private final ConfigurationService configurationService;
private final ConnectionService connectionService;

@GetMapping
@Operation(summary = "Get the agent configuration.")
public ResponseEntity<InspectitConfiguration> getAgentConfiguration() {
@GetMapping("/{agentId}")
@Operation(
summary =
"Get the agent configuration and register the agent with the given id and agent info in the configuration server.")
public ResponseEntity<InspectitConfiguration> getAgentConfiguration(
@PathVariable String agentId, @RequestHeader Map<String, String> headers) {

boolean isFirstRequest = connectionService.handleConfigurationRequest(agentId, headers);
InspectitConfiguration configuration = configurationService.getConfiguration();

// No config available
if (Objects.isNull(configuration)) {
return ResponseEntity.noContent().build();
}

if (isFirstRequest) {
return ResponseEntity.status(HttpStatus.CREATED).body(configuration);
}

return ResponseEntity.ok().body(configuration);
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/* (C) 2024 */
package rocks.inspectit.gepard.agentmanager.configuration.validation;

import static rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService.*;

import java.util.Map;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import rocks.inspectit.gepard.agentmanager.exception.MissingHeaderException;

/** Validation class that helps checking that all mandatory headers are set. */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ConfigurationRequestHeaderValidator {
public static void validateConfigurationRequestHeaders(Map<String, String> headers) {
binarycoded marked this conversation as resolved.
Show resolved Hide resolved
binarycoded marked this conversation as resolved.
Show resolved Hide resolved
validateHeader(headers, X_GEPARD_SERVICE_NAME);
validateHeader(headers, X_GEPARD_VM_ID);
validateHeader(headers, X_GEPARD_GEPARD_VERSION);
validateHeader(headers, X_GEPARD_OTEL_VERSION);
validateHeader(headers, X_GEPARD_JAVA_VERSION);
validateHeader(headers, X_GEPARD_START_TIME);
}

private static void validateHeader(Map<String, String> headers, String headerName) {
String value = headers.get(headerName);
if (value == null) {
throw new MissingHeaderException(headerName + " header is required");
}
}
}
Original file line number Diff line number Diff line change
@@ -12,10 +12,7 @@
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.ConnectionDto;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.QueryConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.UpdateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService;
@@ -32,15 +29,6 @@ public class ConnectionController {

private final ConnectionService connectionService;

@PostMapping("/{id}")
@Operation(summary = "Connect an agent to the agent manager.")
public ResponseEntity<Void> connect(
@PathVariable String id, @Valid @RequestBody CreateConnectionRequest connectRequest) {
Connection connection = connectionService.handleConnectRequest(id, connectRequest);
return ResponseEntity.created(ServletUriComponentsBuilder.fromCurrentRequest().build().toUri())
.build();
}

@PatchMapping("/{id}")
@Operation(summary = "Update the agent connection.")
public ResponseEntity<ConnectionDto> update(
Original file line number Diff line number Diff line change
@@ -19,6 +19,9 @@ public class Connection {
/** The registration time. * */
private Instant registrationTime;

/** The time of the last communication. */
private Instant lastFetch;

/** The status of the connection. */
private ConnectionStatus connectionStatus;

Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@
package rocks.inspectit.gepard.agentmanager.connection.model.dto;

import jakarta.validation.constraints.NotNull;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;
@@ -12,6 +13,7 @@ public record ConnectionDto(
@NotNull(message = "Connection ID missing.") String connectionId,
@NotNull(message = "Registration Time missing.") Instant registrationTime,
@NotNull(message = "Connection status is missing") ConnectionStatus connectionStatus,
@NotNull(message = "Time since last fetch is missing.") Duration timeSinceLastFetch,
@NotNull(message = "Service Name missing.") String serviceName,
@NotNull(message = "Gepard Version missing.") String gepardVersion,
@NotNull(message = "OpenTelemetry Version missing.") String otelVersion,
@@ -25,6 +27,7 @@ public static ConnectionDto fromConnection(String id, Connection connection) {
id,
connection.getRegistrationTime(),
connection.getConnectionStatus(),
Duration.between(connection.getLastFetch(), Instant.now()),
connection.getAgent().getServiceName(),
connection.getAgent().getGepardVersion(),
connection.getAgent().getOtelVersion(),

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
/* (C) 2024 */
package rocks.inspectit.gepard.agentmanager.connection.service;

import static rocks.inspectit.gepard.agentmanager.configuration.validation.ConfigurationRequestHeaderValidator.validateConfigurationRequestHeaders;

import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;
import rocks.inspectit.gepard.agentmanager.connection.model.ConnectionStatus;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.ConnectionDto;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.QueryConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.UpdateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.validation.RegexQueryService;
@@ -21,23 +24,35 @@
@RequiredArgsConstructor
public class ConnectionService {

private final ConcurrentHashMap<String, Connection> connectionCache;
public static final String X_GEPARD_SERVICE_NAME = "x-gepard-service-name";
public static final String X_GEPARD_VM_ID = "x-gepard-vm-id";
public static final String X_GEPARD_GEPARD_VERSION = "x-gepard-gepard-version";
public static final String X_GEPARD_OTEL_VERSION = "x-gepard-otel-version";
public static final String X_GEPARD_JAVA_VERSION = "x-gepard-java-version";
public static final String X_GEPARD_START_TIME = "x-gepard-start-time";
public static final String X_GEPARD_ATTRIBUTE = "x-gepard-attribute-";

private final ConcurrentHashMap<String, Connection> connectionCache;
private final RegexQueryService regexQueryService;

/**
* Handles a connection request from an agent.
* Handles a ConfigurationRequest. If the agent is not connected, it will be connected. If it is
* already connected, the last fetch time of the agent will be updated.
*
* @param connectionId The id for the created connection.
* @param connectRequest The request for the new connection to be created.
* @return Connection The response containing all saved information.
* @param agentId The id of the agent to be connected.
* @param headers The request headers, which should contain the agent information.
* @return true if it is a new the connection, false if it is a reconnect
*/
public Connection handleConnectRequest(
String connectionId, CreateConnectionRequest connectRequest) {
Connection connection = CreateConnectionRequest.toConnection(connectRequest);
connectionCache.put(connectionId, connection);

return connection;
public boolean handleConfigurationRequest(String agentId, Map<String, String> headers) {
binarycoded marked this conversation as resolved.
Show resolved Hide resolved
boolean isNewRegistration;
if (!isAgentConnected(agentId)) {
connectAgent(agentId, headers);
isNewRegistration = true;
} else {
updateConnectionLastFetch(agentId);
isNewRegistration = false;
}
return isNewRegistration;
}

/**
@@ -66,7 +81,7 @@ public ConnectionDto handleUpdateRequest(
public List<ConnectionDto> getConnections() {
return connectionCache.entrySet().stream()
.map(entry -> ConnectionDto.fromConnection(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
.toList();
}

/**
@@ -79,7 +94,7 @@ public List<ConnectionDto> queryConnections(QueryConnectionRequest query) {
return connectionCache.entrySet().stream()
.filter(entry -> matchesConnection(entry.getValue(), query))
.map(entry -> ConnectionDto.fromConnection(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
.toList();
}

/**
@@ -97,6 +112,29 @@ public ConnectionDto getConnection(String id) {
return ConnectionDto.fromConnection(id, connection);
}

/**
* Determines if an agent is connected.
*
* @param agentId The id of the agent to be searched for.
* @return true if the agent was found in the cache, false otherwise.
*/
public boolean isAgentConnected(String agentId) {
return connectionCache.get(agentId) != null;
}

/**
* Updates the last fetch time of an agent connection.
*
* @param agentId The id of the agent to be updated.
*/
private void updateConnectionLastFetch(String agentId) {
Connection connection = connectionCache.get(agentId);
if (connection != null) connection.setLastFetch(Instant.now());
else
throw new NoSuchElementException(
"No connection for agent id " + agentId + " found in cache.");
}

/**
* Checks if a connection matches the given query.
*
@@ -167,4 +205,46 @@ private boolean matchesAttributes(
&& regexQueryService.matches(actualValue, queryEntry.getValue());
});
}

/**
* Handles a connection request from an agent.
*
* @param connectionId The id for the created connection.
* @param headers The request headers, which should contain the agent information.
*/
private void connectAgent(String connectionId, Map<String, String> headers) {

validateConfigurationRequestHeaders(headers);

String serviceName = headers.get(X_GEPARD_SERVICE_NAME);
String vmId = headers.get(X_GEPARD_VM_ID);
String gepardVersion = headers.get(X_GEPARD_GEPARD_VERSION);
String otelVersion = headers.get(X_GEPARD_OTEL_VERSION);
String javaVersion = headers.get(X_GEPARD_JAVA_VERSION);
String startTime = headers.get(X_GEPARD_START_TIME);

Map<String, String> attributes =
headers.entrySet().stream()
.filter(entry -> entry.getKey().startsWith(X_GEPARD_ATTRIBUTE))
.collect(
Collectors.toMap(
entry ->
entry.getKey().substring(X_GEPARD_ATTRIBUTE.length()), // remove the prefix
Map.Entry::getValue));

Agent agent =
new Agent(
serviceName,
vmId,
gepardVersion,
otelVersion,
Instant.parse(startTime),
javaVersion,
attributes);

Connection connection =
new Connection(Instant.now(), Instant.now(), ConnectionStatus.CONNECTED, agent);

connectionCache.put(connectionId, connection);
}
}
Original file line number Diff line number Diff line change
@@ -157,4 +157,17 @@ public ResponseEntity<ApiError> handleInvalidPatternSyntax(

return new ResponseEntity<>(apiError, HttpStatus.BAD_REQUEST);
}

@ExceptionHandler(MissingHeaderException.class)
public ResponseEntity<ApiError> handleMissingHeaderException(
MissingHeaderException ex, HttpServletRequest request) {
ApiError apiError =
new ApiError(
request.getRequestURI(),
List.of(ex.getMessage()),
HttpStatus.BAD_REQUEST.value(),
LocalDateTime.now());

return new ResponseEntity<>(apiError, HttpStatus.BAD_REQUEST);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/* (C) 2024 */
package rocks.inspectit.gepard.agentmanager.exception;

public class MissingHeaderException extends RuntimeException {
public MissingHeaderException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
/* (C) 2024 */
package rocks.inspectit.gepard.agentmanager.configuration.controller;

import static org.mockito.Mockito.when;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static rocks.inspectit.gepard.agentmanager.testutils.ConfigurationRequestTestUtils.getGepardHeaders;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import rocks.inspectit.gepard.agentmanager.configuration.service.ConfigurationService;
import rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService;
import rocks.inspectit.gepard.agentmanager.testutils.InspectitConfigurationTestUtil;
import rocks.inspectit.gepard.config.model.InspectitConfiguration;

@@ -27,20 +29,29 @@ class ConfigurationControllerTest {

@MockBean private ConfigurationService configurationService;

@MockBean private ConnectionService connectionService;

private static final String AGENT_ID = "12345";

@Test
void getConfiguration_whenNoConfigAvailable_shouldReturnNoContent() throws Exception {

when(configurationService.getConfiguration()).thenReturn(null);

mockMvc.perform(get("/api/v1/agent-configuration")).andExpect(status().isNoContent());
mockMvc
.perform(get("/api/v1/agent-configuration/" + AGENT_ID))
.andExpect(status().isNoContent());
}

@Test
void getConfiguration_whenConfigAvailable_shouldReturnOk() throws Exception {

HttpHeaders headers = getGepardHeaders();

when(configurationService.getConfiguration()).thenReturn(new InspectitConfiguration());

mockMvc
.perform(get("/api/v1/agent-configuration"))
.perform(get("/api/v1/agent-configuration/" + AGENT_ID).headers(headers))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().json(objectMapper.writeValueAsString(new InspectitConfiguration())));
Original file line number Diff line number Diff line change
@@ -21,7 +21,6 @@
class ConfigurationServiceTest {

@InjectMocks private ConfigurationService configurationService;

@Mock private GitService gitService;

@Spy private ObjectMapper objectMapper;
@@ -100,4 +99,36 @@ void testUpdateConfiguration_NotSuccessfulSerialization() throws JsonProcessingE
verify(gitService, times(0)).commit();
assertEquals("Failed to serialize InspectitConfiguration to JSON", exception.getMessage());
}

@Test
void testHandleConfigurationRequest() throws JsonProcessingException {
String fileContent =
"""
{
"instrumentation": {
"scopes": {
"s_controller": {
"fqn": "io.opentelemetry.smoketest.springboot.controller.WebController"
}
},
"rules": {
"r_controller": {
"scopes": {
"s_controller": true
},
"tracing": {
"startSpan": true
}
}
}
}
}
""";

when(gitService.getFileContent()).thenReturn(fileContent);
when(objectMapper.readValue(fileContent, InspectitConfiguration.class))
.thenReturn(configuration);
InspectitConfiguration result = configurationService.getConfiguration();
assertEquals(configuration, result);
}
}
Original file line number Diff line number Diff line change
@@ -6,6 +6,7 @@
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
@@ -16,10 +17,8 @@
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;
import rocks.inspectit.gepard.agentmanager.connection.model.ConnectionStatus;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.ConnectionDto;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.QueryConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.UpdateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService;
@@ -33,54 +32,6 @@ class ConnectionControllerTest {

@MockBean private ConnectionService connectionService;

@Test
void connect_whenFieldIsMissing_shouldReturnBadRequest() throws Exception {
String id = "7e4686b7998c88427b14700f1c2aa69304a1c2fdb899067efe8ba9542fc02029";
String requestBody =
"""
{
"serviceName": "customer-service-e",
"gepardVersion: "0.0.1",
"otelVersion": "1.26.8"
}
""";

mockMvc
.perform(
post("/api/v1/connections/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isBadRequest());
}

@Test
void connect_whenEverythingIsValid_shouldReturnOk() throws Exception {
String id = "7e4686b7998c88427b14700f1c2aa69304a1c2fdb899067efe8ba9542fc02029";
CreateConnectionRequest createConnectionRequest =
new CreateConnectionRequest(
"customer-service-e",
"0.0.1",
"1.26.8",
"67887@localhost",
Instant.now(),
"22",
Map.of());

Connection connection = CreateConnectionRequest.toConnection(createConnectionRequest);
when(connectionService.handleConnectRequest(id, createConnectionRequest))
.thenReturn(connection);

mockMvc
.perform(
post("/api/v1/connections/{id}", id)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(createConnectionRequest)))
.andExpect(status().isCreated())
.andExpect(header().exists("Location"))
.andExpect(header().string("Location", "http://localhost/api/v1/connections/" + id));
}

@Test
void get_connections_whenEverythingIsValid_shouldReturnOk() throws Exception {
mockMvc
@@ -97,6 +48,7 @@ void get_connection_whenEverythingIsValid_shouldReturnOk() throws Exception {
"id",
Instant.now(),
ConnectionStatus.CONNECTED,
Duration.ofSeconds(3),
"service name",
"5",
"7",
@@ -122,6 +74,7 @@ void update_connection_whenEverythingIsValid_shouldReturnOk() throws Exception {
"id",
Instant.now(),
ConnectionStatus.CONNECTED,
Duration.ofSeconds(3),
"service name",
"5",
"7",
@@ -174,6 +127,7 @@ void queryConnections_whenMultipleParametersAreDefined_shouldReturnOk() throws E
"id",
Instant.now(),
ConnectionStatus.CONNECTED,
Duration.ofSeconds(2),
"service-name",
"0.0.1",
"1.26.8",
@@ -233,6 +187,7 @@ void queryConnections_whenRegexInParameters_shouldReturnOk() throws Exception {
"id",
Instant.parse("2023-04-15T12:34:56Z"),
ConnectionStatus.CONNECTED,
Duration.ofSeconds(2),
"service-name",
"0.0.1",
"1.26.8",
Original file line number Diff line number Diff line change
@@ -2,13 +2,16 @@
package rocks.inspectit.gepard.agentmanager.connection.service;

import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.*;
import static rocks.inspectit.gepard.agentmanager.testutils.ConfigurationRequestTestUtils.getGepardHeadersAsMap;

import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@@ -19,7 +22,6 @@
import rocks.inspectit.gepard.agentmanager.connection.model.Connection;
import rocks.inspectit.gepard.agentmanager.connection.model.ConnectionStatus;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.ConnectionDto;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.CreateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.QueryConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.model.dto.UpdateConnectionRequest;
import rocks.inspectit.gepard.agentmanager.connection.validation.RegexQueryService;
@@ -60,17 +62,8 @@ void testGetConnectionNotFound() {
@Test
void testGetConnections() {
String id = "7e4686b7998c88427b14700f1c2aa69304a1c2fdb899067efe8ba9542fc02029";
CreateConnectionRequest createConnectionRequest =
new CreateConnectionRequest(
"customer-service-e",
"0.0.1",
"1.26.8",
"67887@localhost",
Instant.now(),
"22",
Map.of());
connectionService.handleConnectRequest(id, createConnectionRequest);
connectionService.handleConnectRequest(id, createConnectionRequest);

connectionCache.put(id, createTestConnection());

List<ConnectionDto> response = connectionService.getConnections();

@@ -80,52 +73,52 @@ void testGetConnections() {
@Test
void testGetConnection() {
String id = "7e4686b7998c88427b14700f1c2aa69304a1c2fdb899067efe8ba9542fc02029";
CreateConnectionRequest createConnectionRequest =
new CreateConnectionRequest(
"customer-service-e",
"0.0.1",
"1.26.8",
"67887@localhost",
Instant.now(),
"22",
Map.of());
Connection connection = connectionService.handleConnectRequest(id, createConnectionRequest);

Connection connection = createTestConnection();
connectionCache.put(id, connection);

ConnectionDto connectionDto = connectionService.getConnection(id);

assertEquals(createConnectionRequest.startTime(), connectionDto.startTime());
assertEquals(createConnectionRequest.javaVersion(), connectionDto.javaVersion());
assertEquals(createConnectionRequest.otelVersion(), connectionDto.otelVersion());
assertEquals(createConnectionRequest.gepardVersion(), connectionDto.gepardVersion());
assertEquals(createConnectionRequest.vmId(), connectionDto.vmId());
assertEquals(createConnectionRequest.serviceName(), connectionDto.serviceName());
assertEquals(connection.getAgent().getStartTime(), connectionDto.startTime());
assertEquals(connection.getAgent().getJavaVersion(), connectionDto.javaVersion());
assertEquals(connection.getAgent().getOtelVersion(), connectionDto.otelVersion());
assertEquals(connection.getAgent().getGepardVersion(), connectionDto.gepardVersion());
assertEquals(connection.getAgent().getVmId(), connectionDto.vmId());
assertEquals(connection.getAgent().getServiceName(), connectionDto.serviceName());
}
}

@Nested
class HandleConnectRequest {
class HandleConfigurationRequest {
@Test
void testHandleConfigurationRequestUpdatesLastFetchOnExistingEntity()
throws InterruptedException {
String id = "7e4686b7998c88427b14700f1c2aa69304a1c2fdb899067efe8ba9542fc02029";

boolean isFirstRequest;
isFirstRequest = connectionService.handleConfigurationRequest(id, getGepardHeadersAsMap());
ConnectionDto connectionDto = connectionService.getConnection(id);
assertTrue(isFirstRequest);
isFirstRequest = connectionService.handleConfigurationRequest(id, getGepardHeadersAsMap());
ConnectionDto connectionDto2 = connectionService.getConnection(id);

await().atMost(1, TimeUnit.SECONDS);
assertFalse(isFirstRequest);
ConnectionDto connectionDto3 = connectionService.getConnection(id);

assertTrue(
connectionDto2.timeSinceLastFetch().compareTo(connectionDto3.timeSinceLastFetch()) < 0);
}

@Test
void testHandleConnectRequest() {
void testHandleConfigurationRequestCreatesNewEntity() {
String id = "7e4686b7998c88427b14700f1c2aa69304a1c2fdb899067efe8ba9542fc02029";
CreateConnectionRequest createConnectionRequest =
new CreateConnectionRequest(
"customer-service-e",
"0.0.1",
"1.26.8",
"67887@localhost",
Instant.now(),
"22",
Map.of());

Connection response = connectionService.handleConnectRequest(id, createConnectionRequest);

assertEquals(createConnectionRequest.startTime(), response.getAgent().getStartTime());
assertEquals(createConnectionRequest.javaVersion(), response.getAgent().getJavaVersion());
assertEquals(createConnectionRequest.otelVersion(), response.getAgent().getOtelVersion());
assertEquals(createConnectionRequest.gepardVersion(), response.getAgent().getGepardVersion());
assertEquals(createConnectionRequest.vmId(), response.getAgent().getVmId());
assertEquals(createConnectionRequest.serviceName(), response.getAgent().getServiceName());

boolean isFirstRequest =
connectionService.handleConfigurationRequest(id, getGepardHeadersAsMap());
ConnectionDto connectionDto = connectionService.getConnection(id);
assertTrue(isFirstRequest);
assertNotNull(connectionDto);
}
}

@@ -449,6 +442,7 @@ private Connection createTestConnection(String serviceName) {
private Connection createTestConnection(Instant registrationTime, String serviceName) {
return new Connection(
registrationTime,
Instant.now(),
ConnectionStatus.CONNECTED,
new Agent(serviceName, "1234@localhost", "1.0", "1.0", Instant.now(), "17", Map.of()));
}
@@ -461,6 +455,7 @@ private Connection createTestConnectionWithAttributes(
Instant registrationTime, Map<String, String> attributes) {
return new Connection(
registrationTime,
Instant.now(),
ConnectionStatus.CONNECTED,
new Agent("testService", "1234@localhost", "1.0", "1.0", Instant.now(), "17", attributes));
}
Original file line number Diff line number Diff line change
@@ -195,4 +195,19 @@ void handleInvalidPatternSyntax() {
assertEquals("requestURI", response.getBody().path());
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
}

@Test
void handleMissingHeaderException() {
MissingHeaderException exception = Mockito.mock(MissingHeaderException.class);
HttpServletRequest httpServletRequest = Mockito.mock(HttpServletRequest.class);
Mockito.when(httpServletRequest.getRequestURI()).thenReturn("requestURI");
Mockito.when(exception.getMessage()).thenReturn("exception message");

ResponseEntity<ApiError> response =
globalExceptionHandler.handleMissingHeaderException(exception, httpServletRequest);

assertEquals(List.of("exception message"), Objects.requireNonNull(response.getBody()).errors());
assertEquals("requestURI", response.getBody().path());
assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/* (C) 2024 */
package rocks.inspectit.gepard.agentmanager.testutils;

import static rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService.*;
import static rocks.inspectit.gepard.agentmanager.connection.service.ConnectionService.X_GEPARD_START_TIME;

import java.time.Instant;
import java.util.Map;
import org.springframework.http.HttpHeaders;

public class ConfigurationRequestTestUtils {

/**
* Creates a map with headers for a Gepard request.
*
* @return the headers
*/
public static Map<String, String> getGepardHeadersAsMap() {
HttpHeaders headers = getGepardHeaders();
return headers.toSingleValueMap();
}

/**
* Creates a HttpHeaders object with headers for a Gepard request.
*
* @return the headers
*/
public static HttpHeaders getGepardHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add(X_GEPARD_SERVICE_NAME, "test-service");
headers.add(X_GEPARD_VM_ID, "test-vm-id");
headers.add(X_GEPARD_GEPARD_VERSION, "test-gepard-version");
headers.add(X_GEPARD_OTEL_VERSION, "test-otel-version");
headers.add(X_GEPARD_JAVA_VERSION, "test-java-version");
headers.add(X_GEPARD_START_TIME, Instant.now().toString());
headers.add(X_GEPARD_ATTRIBUTE + "test-attribute", "test-attribute-value");
return headers;
}
}
3 changes: 0 additions & 3 deletions frontend/build.gradle
Original file line number Diff line number Diff line change
@@ -35,9 +35,6 @@ tasks.register('package_frontend', Jar) {
// Task to build the frontend
npm_run_build {

// First clean the dist and build directory
dependsOn clean

// Only execute this task if something in the frontend has changed.
inputs.files fileTree('src')
inputs.files fileTree('public')