|
| 1 | +package no.nav.familie.tilbake.leader |
| 2 | + |
| 3 | +import org.slf4j.LoggerFactory |
| 4 | +import java.net.InetAddress |
| 5 | +import java.net.URI |
| 6 | +import java.net.http.HttpClient |
| 7 | +import java.net.http.HttpRequest |
| 8 | +import java.net.http.HttpResponse |
| 9 | +import java.net.http.HttpResponse.BodyHandlers |
| 10 | + |
| 11 | +object LeaderClient { |
| 12 | + private val secureLogger = LoggerFactory.getLogger("secureLogger") |
| 13 | + |
| 14 | + /** |
| 15 | + * @return Om pod er leader eller ikke. null hvis leadersjekk ikke er implementert på pod |
| 16 | + */ |
| 17 | + @JvmStatic |
| 18 | + fun isLeader( |
| 19 | + antallGanger: Int = 3, |
| 20 | + forsinkelseIms: Long = 1000, |
| 21 | + ): Boolean? { |
| 22 | + val electorGetUrl = Environment.hentLeaderSystemEnv() ?: return null |
| 23 | + |
| 24 | + val client = HttpClient.newHttpClient() |
| 25 | + val request = |
| 26 | + HttpRequest |
| 27 | + .newBuilder() |
| 28 | + .uri(URI.create(electorGetUrl)) |
| 29 | + .GET() |
| 30 | + .build() |
| 31 | + |
| 32 | + val response: HttpResponse<String>? = |
| 33 | + retryFunksjon( |
| 34 | + antallGanger = antallGanger, |
| 35 | + forsinkelseIms = forsinkelseIms, |
| 36 | + ) { client.send(request, BodyHandlers.ofString()) } |
| 37 | + |
| 38 | + if (response?.body().isNullOrBlank()) return null |
| 39 | + |
| 40 | + val hostname: String = InetAddress.getLocalHost().hostName |
| 41 | + return response?.body()?.contains(hostname) |
| 42 | + } |
| 43 | + |
| 44 | + private fun <T> retryFunksjon( |
| 45 | + antallGanger: Int = 3, |
| 46 | + forsinkelseIms: Long = 1000, |
| 47 | + funksjon: () -> T, |
| 48 | + ): T? { |
| 49 | + var throwable: Exception? = null |
| 50 | + repeat(antallGanger) { |
| 51 | + try { |
| 52 | + return funksjon() |
| 53 | + } catch (e: Exception) { |
| 54 | + secureLogger.warn("Kunne ikke hente leader status") |
| 55 | + throwable = e |
| 56 | + } |
| 57 | + Thread.sleep(forsinkelseIms) |
| 58 | + } |
| 59 | + secureLogger.error("Kunne ikke hente leader status", throwable) |
| 60 | + return null |
| 61 | + } |
| 62 | +} |
0 commit comments