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

[java] Implements healthcheck endpoint for all weblogs #3218

Merged
merged 10 commits into from
Oct 11, 2024
Merged
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions utils/_context/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -698,7 +698,7 @@ def configure(self, replay):
)

# https://github.com/DataDog/system-tests/issues/2799
if self.library in ("cpp", "dotnet", "nodejs", "php", "python", "golang", "ruby"):
if self.library in ("cpp", "dotnet", "nodejs", "php", "python", "golang", "ruby", "java"):
self.healthcheck = {
"test": f"curl --fail --silent --show-error --max-time 2 localhost:{self.port}/healthcheck",
"retries": 60,
Expand Down Expand Up @@ -727,7 +727,7 @@ def post_start(self):

# new way of getting info from the weblog. Only working for nodejs and python right now
# https://github.com/DataDog/system-tests/issues/2799
if self.library in ("cpp", "dotnet", "nodejs", "python", "php", "golang", "ruby"):
if self.library in ("cpp", "dotnet", "nodejs", "python", "php", "golang", "ruby", "java"):
with open(self.healthcheck_log_file, mode="r", encoding="utf-8") as f:
data = json.load(f)
lib = data["library"]
Expand Down
5 changes: 5 additions & 0 deletions utils/build/docker/java/akka-http/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,11 @@
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>io.spray</groupId>
<artifactId>spray-json_2.13</artifactId>
<version>1.3.6</version>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.datadoghq.akka_http

import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import scala.io.Source
import spray.json._
import scala.util.{Failure, Success, Try}

object HealthcheckRoutes {

def route: Route = path("healthcheck") {
get {
val version: String = getVersion match {
case Success(v) => v
case Failure(_) => throw new RuntimeException("Can't get version")
}

val library = JsObject(
"language" -> JsString("java"),
"version" -> JsString(version)
)

val response = JsObject(
"status" -> JsString("ok"),
"library" -> library
)

complete(HttpEntity(ContentTypes.`application/json`, response.prettyPrint))
}
}

private def getVersion: Try[String] = {
Try {
val source = Source.fromResource("dd-java-agent.version")
val version = source.getLines().toList.headOption.getOrElse(throw new RuntimeException("File is empty"))
source.close()
version
}
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
package com.datadoghq.akka_http

import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route

import com.datadoghq.system_tests.iast.infra.{LdapServer, SqlServer}
import org.slf4j.LoggerFactory

import scala.concurrent.Future
import scala.io.Source
import scala.util.{Failure, Success, Try}

object Main extends App {

private val bindingFuture: Future[Http.ServerBinding] =
Http().newServerAt("0.0.0.0", 7777).bindFlow(AppSecRoutes.route ~ IastRoutes.route ~ RaspRoutes.route)
Http().newServerAt("0.0.0.0", 7777).bindFlow(AppSecRoutes.route ~ IastRoutes.route ~ RaspRoutes.route ~ HealthcheckRoutes.route)

LoggerFactory.getLogger(this.getClass).info("Server online at port 7777")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,13 @@
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import com.fasterxml.jackson.databind.ObjectMapper;

@SuppressWarnings("Convert2MethodRef")
Expand All @@ -42,6 +47,36 @@ public String hello() {
}
}

@GET
@Path("/healthcheck")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> healthcheck() {
String version;

try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
getClass().getClassLoader().getResourceAsStream("dd-java-agent.version"),
StandardCharsets.ISO_8859_1))) {
String line = reader.readLine();
if (line == null) {
throw new RuntimeException("Can't get version");
}
version = line;
} catch (Exception e) {
throw new RuntimeException("Can't get version", e);
}

Map<String, String> library = new HashMap<>();
library.put("language", "java");
library.put("version", version);

Map<String, Object> response = new HashMap<>();
response.put("status", "ok");
response.put("library", library);

return response;
}

@GET
@Path("/headers")
public Response headers() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ import java.util
import javax.inject.{Inject, Singleton}
import scala.concurrent.{ExecutionContext, Future, Promise}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
import scala.util.{Failure, Success, Try}

@Singleton
class AppSecController @Inject()(cc: MessagesControllerComponents, ws: WSClient, mat: Materializer)
Expand All @@ -28,6 +32,36 @@ class AppSecController @Inject()(cc: MessagesControllerComponents, ws: WSClient,
}
}

def healthcheck = Action {
val version: String = getVersion match {
case Success(v) => v
case Failure(_) => "0.0.0"
}

// Créer l'objet JSON pour la réponse
val response = Json.obj(
"status" -> "ok",
"library" -> Json.obj(
"language" -> "java",
"version" -> version
)
)

Ok(response)
}

// Méthode pour lire la version du fichier
private def getVersion: Try[String] = {
Try {
val source = Option(getClass.getClassLoader.getResourceAsStream("dd-java-agent.version"))
.getOrElse(throw new RuntimeException("File not found"))
val reader = new BufferedReader(new InputStreamReader(source, StandardCharsets.ISO_8859_1))
val version = reader.readLine()
reader.close()
version
}
}

def headers = Action {
Results.Ok("012345678901234567890123456789012345678901")
.as("text/plain; charset=utf-8")
Expand Down
1 change: 1 addition & 0 deletions utils/build/docker/java/play/conf/routes
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
GET / controllers.AppSecController.index
GET /healthcheck controllers.AppSecController.healthcheck
GET /headers controllers.AppSecController.headers
GET /tag_value/:value/:code controllers.AppSecController.tagValue(value: String, code: Int)
POST /tag_value/:value/:code controllers.AppSecController.tagValuePost(value: String, code: Int)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,19 @@
import ratpack.http.HttpMethod;
import ratpack.http.Response;
import ratpack.server.RatpackServer;
import ratpack.jackson.Jackson;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.InetAddress;
import java.util.logging.LogManager;
import java.util.Optional;

import java.util.HashMap;
import java.net.HttpURLConnection;
Expand Down Expand Up @@ -60,6 +65,16 @@ private static final Map<String, String> createMetadata() {
return h;
}

private static Optional<String> getVersion() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(Main.class.getClassLoader().getResourceAsStream("dd-java-agent.version"), StandardCharsets.ISO_8859_1))) {
String line = reader.readLine();
return Optional.ofNullable(line);
} catch (Exception e) {
return Optional.empty();
}
}

private static void setRootSpanTag(final String key, final String value) {
final Span span = GlobalTracer.get().activeSpan();
if (span instanceof MutableSpan) {
Expand Down Expand Up @@ -90,6 +105,18 @@ public static void main(String[] args) throws Exception {
span.finish();
}
})
.get("healthcheck", ctx -> {
String version = getVersion().orElse("0.0.0");

Map<String, Object> response = new HashMap<>();
Map<String, String> library = new HashMap<>();
library.put("language", "java");
library.put("version", version);
response.put("status", "ok");
response.put("library", library);

ctx.render(Jackson.json(response));
})
.get("headers", ctx -> {
Response response = ctx.getResponse();
response.getHeaders()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
import java.util.Map;
import java.util.List;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

import com.fasterxml.jackson.databind.ObjectMapper;

@Path("/")
Expand All @@ -42,6 +46,36 @@ public String hello() {
}
}

@GET
@Path("/healthcheck")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> healthcheck() {
String version;

try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
getClass().getClassLoader().getResourceAsStream("dd-java-agent.version"),
StandardCharsets.ISO_8859_1))) {
String line = reader.readLine();
if (line == null) {
throw new RuntimeException("Can't get version");
}
version = line;
} catch (Exception e) {
throw new RuntimeException("Can't get version", e);
}

Map<String, String> library = new HashMap<>();
library.put("language", "java");
library.put("version", version);

Map<String, Object> response = new HashMap<>();
response.put("status", "ok");
response.put("library", library);

return response;
}

@GET
@Path("/headers")
public Response headers() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashMap;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.List;
import java.util.concurrent.TimeUnit;
Expand All @@ -28,6 +32,36 @@ String home() {
return "Hello World!";
}

@RequestMapping("/healthcheck")
Map<String, Object> healtchcheck() {

String version;
ClassLoader cl = ClassLoader.getSystemClassLoader();

try (final BufferedReader reader =
new BufferedReader(
new InputStreamReader(
cl.getResourceAsStream("dd-java-agent.version"), StandardCharsets.ISO_8859_1))) {
String line = reader.readLine();
if (line == null) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Can't get version");
}
version = line;
} catch (Exception e) {
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Can't get version");
}

Map<String, String> library = new HashMap<>();
library.put("language", "java");
library.put("version", version);

Map<String, Object> response = new HashMap<>();
response.put("status", "ok");
response.put("library", library);

return response;
}

@GetMapping("/headers")
String headers(HttpServletResponse response) {
response.setHeader("content-language", "en-US");
Expand Down
Loading
Loading