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
Show file tree
Hide file tree
Changes from 3 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
Expand Up @@ -3,8 +3,10 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
binarycoded marked this conversation as resolved.
Show resolved Hide resolved
public class Application {

public static void main(String[] args) {
Expand Down
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,28 @@
/* (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;

@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
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,33 @@
@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";

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.
*/
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;
}

/**
Expand Down Expand Up @@ -66,7 +79,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 +92,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 +110,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 +203,48 @@ 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-"))
binarycoded marked this conversation as resolved.
Show resolved Hide resolved
.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
Loading