Skip to content

Commit

Permalink
Skrev om NaisEnv fra enum til interface, endret navn til RuntimeEnvir…
Browse files Browse the repository at this point in the history
…onment
  • Loading branch information
nilsmsa committed Sep 20, 2024
1 parent 1cb29d5 commit 98dce98
Show file tree
Hide file tree
Showing 16 changed files with 124 additions and 84 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import no.nav.paw.bekreftelse.api.plugins.configureTracing
import no.nav.paw.bekreftelse.api.routes.bekreftelseRoutes
import no.nav.paw.bekreftelse.api.routes.metricsRoutes
import no.nav.paw.bekreftelse.api.routes.swaggerRoutes
import no.nav.paw.config.env.appNameOrDefaultForLocal
import no.nav.paw.config.env.currentRuntimeEnvironment
import no.nav.paw.config.hoplite.loadNaisOrLocalConfiguration
import no.nav.paw.health.route.healthRoutes
import org.slf4j.LoggerFactory
Expand All @@ -29,7 +31,7 @@ fun main() {
val applicationConfig = loadNaisOrLocalConfiguration<ApplicationConfig>(APPLICATION_CONFIG_FILE_NAME)
val serverConfig = loadNaisOrLocalConfiguration<ServerConfig>(SERVER_CONFIG_FILE_NAME)

logger.info("Starter: ${applicationConfig.appId}")
logger.info("Starter: ${currentRuntimeEnvironment.appNameOrDefaultForLocal()}")

val dependencies = createDependencies(applicationConfig)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import no.nav.poao_tilgang.client.PoaoTilgangHttpClient
import org.apache.kafka.streams.KafkaStreams

fun createDependencies(applicationConfig: ApplicationConfig): Dependencies {
val azureM2MTokenClient = azureAdM2MTokenClient(applicationConfig.naisEnv, applicationConfig.azureM2M)
val azureM2MTokenClient = azureAdM2MTokenClient(applicationConfig.runtimeEnvironment, applicationConfig.azureM2M)

val kafkaKeysClient = kafkaKeysClient(applicationConfig.kafkaKeysClient) {
azureM2MTokenClient.createMachineToMachineToken(applicationConfig.kafkaKeysClient.scope)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package no.nav.paw.bekreftelse.api.config

import no.nav.paw.config.env.NaisEnv
import no.nav.paw.config.env.currentAppId
import no.nav.paw.config.env.currentAppName
import no.nav.paw.config.env.currentNaisEnv
import no.nav.paw.config.env.RuntimeEnvironment
import no.nav.paw.config.env.currentRuntimeEnvironment
import no.nav.paw.config.kafka.KafkaConfig
import no.nav.paw.kafkakeygenerator.auth.AzureM2MConfig
import no.nav.paw.kafkakeygenerator.client.KafkaKeyConfig
Expand All @@ -20,9 +18,7 @@ data class ApplicationConfig(
val kafkaKeysClient: KafkaKeyConfig,
val kafkaClients: KafkaConfig,
// Env
val naisEnv: NaisEnv = currentNaisEnv,
val appId: String = currentAppId ?: "UNSPECIFIED",
val appName: String = currentAppName ?: "UNSPECIFIED",
val runtimeEnvironment: RuntimeEnvironment = currentRuntimeEnvironment,
val hostname: String = InetAddress.getLocalHost().hostName
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import no.nav.paw.bekreftelse.melding.v1.vo.Bruker
import no.nav.paw.bekreftelse.melding.v1.vo.BrukerType
import no.nav.paw.bekreftelse.melding.v1.vo.Metadata
import no.nav.paw.bekreftelse.melding.v1.vo.Svar
import no.nav.paw.config.env.currentAppName
import no.nav.paw.config.env.appImageOrDefaultForLocal
import no.nav.paw.config.env.currentRuntimeEnvironment
import no.nav.paw.config.env.namespaceOrDefaultForLocal
import java.time.Instant
import java.util.*

Expand All @@ -23,7 +25,7 @@ fun BekreftelseRequest.toHendelse(
brukerId: String,
brukerType: BrukerType
) = Bekreftelse.newBuilder()
.setNamespace("paw") // TODO Hente fra config?
.setNamespace(currentRuntimeEnvironment.namespaceOrDefaultForLocal())
.setId(bekreftelseId)
.setPeriodeId(periodeId)
.setSvar(
Expand All @@ -36,7 +38,7 @@ fun BekreftelseRequest.toHendelse(
.setType(brukerType)
.build()
)
.setKilde(currentAppName)
.setKilde(currentRuntimeEnvironment.appImageOrDefaultForLocal())
.setTidspunkt(Instant.now())
.build()
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.routing.IgnoreTrailingSlash
import no.nav.paw.bekreftelse.api.config.ApplicationConfig
import no.nav.paw.bekreftelse.api.config.AutorisasjonConfig
import no.nav.paw.config.env.NaisEnv
import no.nav.paw.config.env.Local
import no.nav.paw.config.env.Nais
import no.nav.paw.error.handler.handleException

fun Application.configureHTTP(applicationConfig: ApplicationConfig) {
Expand All @@ -23,16 +24,12 @@ fun Application.configureHTTP(applicationConfig: ApplicationConfig) {
install(CORS) {
val origins = applicationConfig.autorisasjon.getCorsAllowOrigins()

when (applicationConfig.naisEnv) {
NaisEnv.ProdGCP -> {
when (applicationConfig.runtimeEnvironment) {
is Nais -> {
origins.forEach { allowHost(it) }
}

NaisEnv.DevGCP -> {
origins.forEach { allowHost(it) }
}

NaisEnv.Local -> anyHost()
is Local -> anyHost()
}

allowMethod(HttpMethod.Options)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,49 @@ import com.fasterxml.jackson.module.kotlin.readValue
import io.confluent.kafka.streams.serdes.avro.SpecificAvroSerde
import no.nav.paw.bekreftelse.api.model.InternState
import no.nav.paw.bekreftelse.melding.v1.Bekreftelse
import no.nav.paw.config.env.NaisEnv
import no.nav.paw.config.env.currentNaisEnv
import no.nav.paw.config.env.ProdGcp
import no.nav.paw.config.env.RuntimeEnvironment
import no.nav.paw.config.env.currentRuntimeEnvironment
import org.apache.kafka.common.serialization.Deserializer
import org.apache.kafka.common.serialization.Serde
import org.apache.kafka.common.serialization.Serializer

inline fun <reified T> buildJsonSerializer(naisEnv: NaisEnv, objectMapper: ObjectMapper) = object : Serializer<T> {
inline fun <reified T> buildJsonSerializer(runtimeEnvironment: RuntimeEnvironment, objectMapper: ObjectMapper) = object : Serializer<T> {
override fun serialize(topic: String?, data: T): ByteArray {
if (data == null) return byteArrayOf()
try {
return objectMapper.writeValueAsBytes(data)
} catch (e: Exception) {
if (naisEnv == NaisEnv.ProdGCP && e is JsonProcessingException) e.clearLocation()
if (runtimeEnvironment is ProdGcp && e is JsonProcessingException) e.clearLocation()
throw e
}
}
}

inline fun <reified T> buildJsonDeserializer(naisEnv: NaisEnv, objectMapper: ObjectMapper) = object : Deserializer<T> {
inline fun <reified T> buildJsonDeserializer(runtimeEnvironment: RuntimeEnvironment, objectMapper: ObjectMapper) = object : Deserializer<T> {
override fun deserialize(topic: String?, data: ByteArray?): T? {
if (data == null) return null
try {
return objectMapper.readValue<T>(data)
} catch (e: Exception) {
if (naisEnv == NaisEnv.ProdGCP && e is JsonProcessingException) e.clearLocation()
if (runtimeEnvironment is ProdGcp && e is JsonProcessingException) e.clearLocation()
throw e
}
}
}

inline fun <reified T> buildJsonSerde(naisEnv: NaisEnv, objectMapper: ObjectMapper) = object : Serde<T> {
inline fun <reified T> buildJsonSerde(runtimeEnvironment: RuntimeEnvironment, objectMapper: ObjectMapper) = object : Serde<T> {
override fun serializer(): Serializer<T> {
return buildJsonSerializer(naisEnv, objectMapper)
return buildJsonSerializer(runtimeEnvironment, objectMapper)
}

override fun deserializer(): Deserializer<T> {
return buildJsonDeserializer(naisEnv, objectMapper)
return buildJsonDeserializer(runtimeEnvironment, objectMapper)
}
}

inline fun <reified T> buildJsonSerde(): Serde<T> {
return buildJsonSerde<T>(currentNaisEnv, buildObjectMapper)
return buildJsonSerde<T>(currentRuntimeEnvironment, buildObjectMapper)
}

fun buildInternStateSerde() = buildJsonSerde<InternState>()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ import io.ktor.client.HttpClient
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.jackson.jackson
import no.nav.common.token_client.client.AzureAdMachineToMachineTokenClient
import no.nav.paw.config.env.currentNaisEnv
import no.nav.paw.config.env.currentRuntimeEnvironment
import no.nav.paw.config.hoplite.loadNaisOrLocalConfiguration
import no.nav.paw.kafkakeygenerator.auth.AzureM2MConfig
import no.nav.paw.kafkakeygenerator.auth.azureAdM2MTokenClient
import no.nav.paw.kafkakeygenerator.client.KafkaKeysClient
import no.nav.paw.kafkakeygenerator.client.createKafkaKeyGeneratorClient

fun initClients(azureConfig: AzureM2MConfig): Pair<KafkaKeysClient, OppslagApiClient> {
val azureTokenClient = azureAdM2MTokenClient(currentNaisEnv, azureConfig)
val azureTokenClient = azureAdM2MTokenClient(currentRuntimeEnvironment, azureConfig)
val kafkaKeysClient = createKafkaKeyGeneratorClient(azureTokenClient)
val oppslagApiClient = oppslagsApiClient(azureTokenClient)
return kafkaKeysClient to oppslagApiClient
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ import no.nav.paw.arbeidssoekerregisteret.backup.api.brukerstoette.models.Feil
import no.nav.paw.arbeidssoekerregisteret.backup.brukerstoette.BrukerstoetteService
import no.nav.paw.arbeidssoekerregisteret.backup.health.configureHealthRoutes
import no.nav.paw.arbeidssoekerregisteret.backup.health.installMetrics
import no.nav.paw.config.env.NaisEnv
import no.nav.paw.config.env.currentNaisEnv
import no.nav.paw.config.env.ProdGcp
import no.nav.paw.config.env.currentRuntimeEnvironment
import no.nav.security.token.support.v2.IssuerConfig
import no.nav.security.token.support.v2.TokenSupportConfig
import no.nav.security.token.support.v2.TokenValidationContextPrincipal
Expand All @@ -50,7 +50,7 @@ fun initKtor(
routing {
swaggerUI(path = "docs/brukerstoette", swaggerFile = "openapi/Brukerstoette.yaml")
configureHealthRoutes(prometheusMeterRegistry)
if (currentNaisEnv == NaisEnv.ProdGCP) {
if (currentRuntimeEnvironment is ProdGcp) {
authenticate("azure") {
configureBrukerstoetteRoutes(brukerstoetteService)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import io.micrometer.prometheusmetrics.PrometheusMeterRegistry
import kotlinx.coroutines.runBlocking
import no.nav.paw.arbeidssokerregisteret.app.helse.Helse
import no.nav.paw.arbeidssokerregisteret.app.helse.initKtor
import no.nav.paw.config.env.NaisEnv
import no.nav.paw.config.env.currentNaisEnv
import no.nav.paw.config.env.ProdGcp
import no.nav.paw.config.env.RuntimeEnvironment
import no.nav.paw.config.env.currentRuntimeEnvironment
import no.nav.paw.config.hoplite.loadNaisOrLocalConfiguration
import no.nav.paw.config.kafka.KafkaConfig
import no.nav.paw.config.kafka.streams.KafkaStreamsFactory
Expand All @@ -31,8 +32,8 @@ val applicationConfiguration: ApplicationConfiguration get() =

typealias kafkaKeyFunction = (String) -> KafkaKeysResponse?

fun formidlingsGruppeTopic(env: NaisEnv) =
"teamarenanais.aapen-arena-formidlingsgruppeendret-v1-${if (env == NaisEnv.ProdGCP) "p" else "q"}"
fun formidlingsGruppeTopic(env: RuntimeEnvironment) =
"teamarenanais.aapen-arena-formidlingsgruppeendret-v1-${if (env is ProdGcp) "p" else "q"}"

fun main() {
val logger = LoggerFactory.getLogger("app")
Expand Down Expand Up @@ -64,7 +65,7 @@ fun main() {
"aktivePerioder",
idAndRecordKeyFunction,
periodeTopic,
formidlingsGruppeTopic(currentNaisEnv),
formidlingsGruppeTopic(currentRuntimeEnvironment),
appCfg.hendelseloggTopic
)
val kafkaStreams = KafkaStreams(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import no.nav.paw.arbeidssoekerregisteret.app.vo.ArenaFormidlingsruppe
import no.nav.paw.arbeidssoekerregisteret.app.vo.AvsluttetSerde
import no.nav.paw.arbeidssokerregisteret.api.v1.Periode
import no.nav.paw.arbeidssokerregisteret.intern.v1.Avsluttet
import no.nav.paw.config.env.NaisEnv
import no.nav.paw.config.env.Local
import no.nav.paw.kafkakeygenerator.client.KafkaKeysResponse
import no.nav.paw.kafkakeygenerator.client.inMemoryKafkaKeysMock
import org.apache.avro.specific.SpecificRecord
Expand Down Expand Up @@ -61,7 +61,7 @@ fun testScope(): TestScope {
stateStoreName = stateStoreName,
hendelseloggTopic = appCfg.hendelseloggTopic,
periodeTopic = periodeTopic,
formidlingsgrupperTopic = formidlingsGruppeTopic(NaisEnv.Local),
formidlingsgrupperTopic = formidlingsGruppeTopic(Local),
idAndRecordKeyFunction = idAndRecordKeyFunction,
prometheusRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
),
Expand All @@ -74,7 +74,7 @@ fun testScope(): TestScope {
periodeSerde.serializer()
)
val formidlingsgruppeInputTopic = testDriver.createInputTopic(
formidlingsGruppeTopic(NaisEnv.Local),
formidlingsGruppeTopic(Local),
Serdes.String().serializer(),
formidlingsgruppeSerde.serializer(),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import io.ktor.client.HttpClient
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.serialization.jackson.jackson
import kotlinx.coroutines.runBlocking
import no.nav.paw.config.env.currentNaisEnv
import no.nav.paw.config.env.currentRuntimeEnvironment
import no.nav.paw.config.hoplite.loadNaisOrLocalConfiguration
import no.nav.paw.kafkakeygenerator.auth.AzureM2MConfig
import no.nav.paw.kafkakeygenerator.auth.azureAdM2MTokenClient
Expand Down Expand Up @@ -65,7 +65,7 @@ fun interface PdlHentForenkletStatus {

private fun createPdlClient(): PdlClient {
val azureM2MConfig = loadNaisOrLocalConfiguration<AzureM2MConfig>("azure_m2m.toml")
val m2mTokenClient = azureAdM2MTokenClient(currentNaisEnv, azureM2MConfig)
val m2mTokenClient = azureAdM2MTokenClient(currentRuntimeEnvironment, azureM2MConfig)
val pdlConfig = loadNaisOrLocalConfiguration<PdlConfig>(PDL_CONFIG_FILE)

return PdlClient(pdlConfig.url, pdlConfig.tema, createHttpClient()) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package no.nav.paw.config.env

sealed interface RuntimeEnvironment

data object Local : RuntimeEnvironment

sealed interface Nais : RuntimeEnvironment {
val clusterName: String
val namespace: String
val appName: String
val appImage: String
}
sealed interface DevGcp : Nais

sealed interface ProdGcp : Nais


private class DevGCPImpl(
override val clusterName: String,
override val namespace: String,
override val appName: String,
override val appImage: String
) : DevGcp

private class ProdGCPImpl(
override val clusterName: String,
override val namespace: String,
override val appName: String,
override val appImage: String
) : ProdGcp

const val NAIS_PROD_CLUSER_NAME = "prod-gcp"
const val NAIS_DEV_CLUSER_NAME = "dev-gcp"

val currentRuntimeEnvironment: RuntimeEnvironment = currentRuntimeEnvironment()

private fun currentRuntimeEnvironment(): RuntimeEnvironment {
val namespace = { currentNamespace ?: error("NAIS_NAMESPACE is not set") }
val appName = { currentAppName ?: error("NAIS_APP_NAME is not set") }
val appImage = { currentAppImage ?: error("NAIS_APP_IMAGE is not set") }
return when (val clusterName = System.getenv("NAIS_CLUSTER_NAME")) {
NAIS_PROD_CLUSER_NAME -> ProdGCPImpl(clusterName, namespace(), appName(), appImage())
NAIS_DEV_CLUSER_NAME -> DevGCPImpl(clusterName, namespace(), appName(), appImage())
else -> Local
}
}

private val currentAppImage: String? get() = System.getenv("NAIS_APP_IMAGE") // F.eks. europe-north1-docker.pkg.dev/nais-management-233d/paw/paw-microfrontend-toggler:24.06.27.57-1

private val currentAppName: String? get() = System.getenv("NAIS_APP_NAME") // F.eks. paw-microfrontend-toggler

private val currentNamespace: String? get() = System.getenv("NAIS_NAMESPACE")
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package no.nav.paw.config.env

fun RuntimeEnvironment.namespaceOrDefaultForLocal(default: String = "local-namespace") = when (this) {
is Nais -> namespace
else -> default
}

fun RuntimeEnvironment.clusterNameOrDefaultForLocal(default: String = "local") = when (this) {
is Nais -> clusterName
else -> default
}

fun RuntimeEnvironment.appNameOrDefaultForLocal(default: String = "local-app") = when (this) {
is Nais -> appName
else -> default
}

fun RuntimeEnvironment.appImageOrDefaultForLocal(default: String = "local-image") = when (this) {
is Nais -> appImage
else -> default
}
Loading

0 comments on commit 98dce98

Please sign in to comment.