|
| 1 | +package io.kuberhealthy.client; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.OutputStream; |
| 5 | +import java.net.HttpURLConnection; |
| 6 | +import java.net.URL; |
| 7 | +import java.nio.charset.StandardCharsets; |
| 8 | + |
| 9 | +/** |
| 10 | + * Minimal client for reporting check results to Kuberhealthy. |
| 11 | + */ |
| 12 | +public class KuberhealthyClient { |
| 13 | + private final String url; |
| 14 | + private final String uuid; |
| 15 | + |
| 16 | + public KuberhealthyClient(String url, String uuid) { |
| 17 | + this.url = url; |
| 18 | + this.uuid = uuid; |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * Reports the result of a check to Kuberhealthy. |
| 23 | + * |
| 24 | + * @param ok true if the check succeeded |
| 25 | + * @param errorMessage error description when ok is false |
| 26 | + * @throws IOException when the report cannot be delivered |
| 27 | + */ |
| 28 | + public void report(boolean ok, String errorMessage) throws IOException { |
| 29 | + String payload = "{\"ok\":true,\"errors\":[]}"; |
| 30 | + if (!ok) { |
| 31 | + payload = "{\"ok\":false,\"errors\":[\"" + escape(errorMessage) + "\"]}"; |
| 32 | + } |
| 33 | + |
| 34 | + HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); |
| 35 | + conn.setRequestMethod("POST"); |
| 36 | + conn.setRequestProperty("Content-Type", "application/json"); |
| 37 | + conn.setRequestProperty("kh-run-uuid", uuid); |
| 38 | + conn.setDoOutput(true); |
| 39 | + |
| 40 | + try (OutputStream os = conn.getOutputStream()) { |
| 41 | + os.write(payload.getBytes(StandardCharsets.UTF_8)); |
| 42 | + } |
| 43 | + |
| 44 | + int code = conn.getResponseCode(); |
| 45 | + if (code != 200) { |
| 46 | + throw new IOException("unexpected response code: " + code); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private static String escape(String s) { |
| 51 | + return s.replace("\\", "\\\\").replace("\"", "\\\""); |
| 52 | + } |
| 53 | +} |
0 commit comments