Skip to content

Commit

Permalink
feat: Include notification into polling (#15)
Browse files Browse the repository at this point in the history
* feat: include notification into polling

* refactor: Kiss (my ass) - No Events

* fix: adjust response handling according to agent

* fix: adjustments according review

---------

Co-authored-by: Benjamin Clauss <benjamin.clauss@novatec-gmbh.de>
  • Loading branch information
levinkerschberger and binarycoded authored Nov 26, 2024
1 parent b094099 commit d46ab4d
Show file tree
Hide file tree
Showing 16 changed files with 316 additions and 172 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
}

Expand Down
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) {
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
Expand Up @@ -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;
Expand All @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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,
Expand All @@ -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(),
Expand Down

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;
Expand All @@ -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) {
boolean isNewRegistration;
if (!isAgentConnected(agentId)) {
connectAgent(agentId, headers);
isNewRegistration = true;
} else {
updateConnectionLastFetch(agentId);
isNewRegistration = false;
}
return isNewRegistration;
}

/**
Expand Down Expand Up @@ -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();
}

/**
Expand All @@ -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();
}

/**
Expand All @@ -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.
*
Expand Down Expand Up @@ -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
Expand Up @@ -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);
}
}
Loading

0 comments on commit d46ab4d

Please sign in to comment.