Skip to content

Commit f8393e9

Browse files
committed
Enable turning on/off debug output via config
1 parent 9d9540c commit f8393e9

File tree

7 files changed

+46
-35
lines changed

7 files changed

+46
-35
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ values can be defined using `|` separator for both Web interface and API (for in
2626
are inclusive, that is start and end of the intervals are included. The intervals unbound from one side are also
2727
supported, for example, `track-number=10|` or `track-number=|15`.
2828

29+
If you want extensive debug output (including all SQL requests), specify `debug: True` in the configuration file.
30+
2931
### Run installation of the EMS interfaces on a RedHat-based Operating System (AlmaLinux, CentOS, RedHat)
3032

3133
There are three possible ways to install the EMS API and Web UI.

src/commonMain/kotlin/ConfigFile.kt

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,10 @@ class ConfigFile(
2323
val keycloak_auth: KeyCloakAuthConfig?,
2424

2525
val title: String,
26-
val pages: List<PageConfig>
26+
val pages: List<PageConfig>,
27+
28+
// If true, API will log requests extensively
29+
val debug: Boolean? = false
2730
)
2831

2932
@Serializable

src/jvmMain/kotlin/Application.kt

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ import java.sql.DriverManager
2121

2222
lateinit var config: ConfigFile
2323

24+
fun debug(message: String) {
25+
if (config.debug == true) {
26+
println(message)
27+
}
28+
}
29+
2430
fun Application.main() {
2531

2632
install(DefaultHeaders)
@@ -38,14 +44,14 @@ fun Application.main() {
3844
basic("auth-keycloak-userpass") {
3945
// Obtain Token via KeyCloak
4046
validate { credentials ->
41-
println("auth-keycloak-userpass called for username ${credentials.name}")
47+
debug("auth-keycloak-userpass called for username ${credentials.name}")
4248
// Note: validate must return Principal in case of successful authentication or null otherwise
43-
getKCPrincipalOrNull(config, credentials.name, credentials.password) //.also { println(it) }
49+
getKCPrincipalOrNull(config, credentials.name, credentials.password) //.also { debug(it) }
4450
}
4551
}
4652
bearer("auth-keycloak-bearer") {
4753
authenticate { bearerTokenCredential: BearerTokenCredential ->
48-
println("auth-keycloak-bearer called with token = ${bearerTokenCredential.token}")
54+
debug("auth-keycloak-bearer called with token = ${bearerTokenCredential.token}")
4955
val groups = getKCgroups(config, bearerTokenCredential.token) ?: return@authenticate null
5056
TokenGroupsPrincipal(bearerTokenCredential.token, groups, rolesFromGroups(config, groups))
5157
}
@@ -69,7 +75,7 @@ fun Application.main() {
6975
DriverManager.getConnection(urlConditionDB, config.condition_db!!.user, config.condition_db!!.password)
7076
}
7177

72-
// println("Working Directory = ${System.getProperty("user.dir")}")
78+
// debug("Working Directory = ${System.getProperty("user.dir")}")
7379
routing {
7480

7581
// Allows all resources to be statically available (including generated nica-ems.js file)
@@ -112,7 +118,7 @@ fun Application.main() {
112118
}
113119
}
114120
} catch (err: Exception) {
115-
println("EMS database error: $err")
121+
debug("EMS database error: $err")
116122
call.respond(HttpStatusCode.NotFound, "EMS database error: $err")
117123
} finally {
118124
connEMD?.close()
@@ -173,7 +179,7 @@ fun Application.main() {
173179
// e.g. POST { "software_id": 100, "software_version": "22.1" }
174180
// Note: software_id is assigned automatically by the database, regardless of what is passed in JSON
175181
val roles = call.principal<WithRoles>()?.roles!!
176-
// println("Roles in post(SOFTWARE_URL): $roles")
182+
// debug("Roles in post(SOFTWARE_URL): $roles")
177183
if (!(roles.isWriter or roles.isAdmin)) {
178184
call.respond(HttpStatusCode.Unauthorized)
179185
return@post // not really needed here but important in other places
@@ -183,7 +189,7 @@ fun Application.main() {
183189
val sw = call.receive<SoftwareVersion>()
184190
connEMD = newEMDConnection(config, this.context)
185191
val query = """INSERT INTO software_ (software_version) VALUES ('${sw.software_version}')"""
186-
println(query)
192+
debug(query)
187193
connEMD!!.createStatement().executeUpdate(query)
188194
call.respond(HttpStatusCode.OK, "SW record was created")
189195
} catch (err: PSQLException) {
@@ -245,7 +251,7 @@ fun Application.main() {
245251
val storage = call.receive<Storage>()
246252
connEMD = newEMDConnection(config, this.context)
247253
val query = """INSERT INTO storage_ (storage_name) VALUES ('${storage.storage_name}')"""
248-
println(query)
254+
debug(query)
249255

250256
connEMD!!.createStatement().executeUpdate(query)
251257
call.response.status(HttpStatusCode.OK)
@@ -373,7 +379,7 @@ fun Application.main() {
373379
connEMD!!.autoCommit = false
374380
val softwareMap = getSoftwareMap(connEMD!!)
375381
val storageMap = getStorageMap(connEMD!!)
376-
println("Received ${events.size} events!")
382+
debug("Received ${events.size} events!")
377383
val fileData = mutableMapOf<Pair<Byte, String>, Int>()
378384
events.forEach { event ->
379385
val software_id = softwareMap.str_to_id[event.software_version]
@@ -403,7 +409,7 @@ fun Application.main() {
403409
} else { // create file record
404410
val fileQuery =
405411
"""INSERT INTO file_ (storage_id, file_path) VALUES ($storage_id, '$file_path')"""
406-
println(fileQuery)
412+
debug(fileQuery)
407413
connEMD!!.createStatement().executeUpdate(fileQuery)
408414
val res2 = connEMD!!.createStatement().executeQuery(
409415
"""SELECT file_guid FROM file_ WHERE storage_id = $storage_id AND file_path = '$file_path'"""
@@ -412,12 +418,12 @@ fun Application.main() {
412418
file_guid = res2.getInt("file_guid")
413419
}
414420
fileData[Pair(storage_id, file_path)] = file_guid
415-
println("File GUID for $file_path = $file_guid")
421+
debug("File GUID for $file_path = $file_guid")
416422
}
417423
}
418424
val stmt = connEMD!!.createStatement()
419425
events.forEach { event ->
420-
println("Creating event: $event")
426+
debug("Creating event: $event")
421427
val software_id = softwareMap.str_to_id[event.software_version]
422428
val storage_id = storageMap.str_to_id[event.reference.storage_name]
423429
val file_guid = fileData[Pair(storage_id, event.reference.file_path)]!!
@@ -435,12 +441,12 @@ fun Application.main() {
435441
VALUES ($file_guid, ${event.reference.event_number}, $software_id, ${event.period_number},
436442
${event.run_number}, $parameterValuesStr)
437443
""".trimIndent()
438-
println(query)
444+
debug(query)
439445
stmt.addBatch(query)
440446
}
441447
stmt.executeBatch()
442448
connEMD!!.commit()
443-
println("Success: ${events.size} event(s) were created")
449+
debug("Success: ${events.size} event(s) were created")
444450
call.respond(HttpStatusCode.OK, "Success: ${events.size} event(s) were created")
445451
} catch (err: PSQLException) {
446452
if (err.toString().contains("The connection attempt failed.")) {
@@ -470,7 +476,7 @@ fun Application.main() {
470476
connEMD!!.autoCommit = false
471477
val softwareMap = getSoftwareMap(connEMD!!)
472478
val storageMap = getStorageMap(connEMD!!)
473-
println("Received ${events.size} events!")
479+
debug("Received ${events.size} events!")
474480
val fileData = mutableMapOf<Pair<Byte, String>, Int>()
475481
events.forEach { event ->
476482
val software_id = softwareMap.str_to_id[event.software_version]
@@ -500,7 +506,7 @@ fun Application.main() {
500506
} else { // create file record
501507
val fileQuery =
502508
"""INSERT INTO file_ (storage_id, file_path) VALUES ($storage_id, '$file_path')"""
503-
println(fileQuery)
509+
debug(fileQuery)
504510
connEMD!!.createStatement().executeUpdate(fileQuery)
505511
val res2 = connEMD!!.createStatement().executeQuery(
506512
"""SELECT file_guid FROM file_ WHERE storage_id = $storage_id AND file_path = '$file_path'"""
@@ -509,12 +515,12 @@ fun Application.main() {
509515
file_guid = res2.getInt("file_guid")
510516
}
511517
fileData[Pair(storage_id, file_path)] = file_guid
512-
println("File GUID for $file_path = $file_guid")
518+
debug("File GUID for $file_path = $file_guid")
513519
}
514520
}
515521
val stmt = connEMD!!.createStatement()
516522
events.forEach { event ->
517-
println("Creating event: $event")
523+
debug("Creating event: $event")
518524
val software_id = softwareMap.str_to_id[event.software_version]
519525
val storage_id = storageMap.str_to_id[event.reference.storage_name]
520526
val file_guid = fileData[Pair(storage_id, event.reference.file_path)]!!
@@ -542,7 +548,7 @@ fun Application.main() {
542548
software_id=$software_id, period_number=${event.period_number}, run_number=${event.run_number},
543549
$parameterNamesEqValuesStr
544550
""".trimIndent()
545-
println(query)
551+
debug(query)
546552
stmt.addBatch(query)
547553
}
548554
stmt.executeBatch()
@@ -594,7 +600,7 @@ fun Application.main() {
594600
)
595601
if (res.next()) {
596602
val file_guid: Int = res.getInt("file_guid")
597-
println("File GUID ($storage_id, $file_path) = $file_guid")
603+
debug("File GUID ($storage_id, $file_path) = $file_guid")
598604
fileData[Pair(storage_id, file_path)] = file_guid
599605
} else { // no such file
600606
call.respond(
@@ -607,14 +613,14 @@ fun Application.main() {
607613
}
608614
val stmt = connEMD!!.createStatement()
609615
events.forEach { event ->
610-
println("Deleting event: $event")
616+
debug("Deleting event: $event")
611617
val storage_id = storageMap.str_to_id[event.reference.storage_name]
612618
val file_guid = fileData[Pair(storage_id, event.reference.file_path)]
613619
val query = """
614620
DELETE FROM ${page.db_table_name}
615621
WHERE (("file_guid" = $file_guid AND "event_number" = ${event.reference.event_number}));
616622
""".trimIndent()
617-
println(query)
623+
debug(query)
618624
stmt.addBatch(query)
619625
}
620626
val res = stmt.executeBatch()
@@ -647,7 +653,7 @@ fun Application.main() {
647653
// Synchronous - build a file with some ROOT macro and return it
648654
get("/eventFile") {
649655
// TODO Apply all filtering, build ROOT file
650-
println("Serving dummy eventFile...")
656+
debug("Serving dummy eventFile...")
651657
val f =
652658
Thread.currentThread().getContextClassLoader().getResource("static/downloadFile.bin")!!.file
653659
call.respondFile(File(f))

src/jvmMain/kotlin/ConditionDBUtils.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ fun getRunsBy(
2626
filteringConditions.add(it.generateSQLWhere())
2727
}
2828
sql += " WHERE " + filteringConditions.joinToString(" AND ")
29-
println("Condition db request: $sql")
29+
debug("Condition db request: $sql")
3030

3131
val res = conn.createStatement().executeQuery(sql)
3232
return ArrayList<Pair<Short, Int>>().apply {

src/jvmMain/kotlin/EventDBUtils.kt

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,14 +92,14 @@ fun queryEMD(
9292
+"""WARNING: Empty set of (period_number, run_number) returned in
9393
pre-selection, not using it"""
9494
}
95-
println("WARNING: Empty set of (period_number, run_number) returned in pre-selection, not using it")
95+
debug("WARNING: Empty set of (period_number, run_number) returned in pre-selection, not using it")
9696
return null
9797
} else {
9898
val periodsRunsJoined = periodsRuns
9999
.joinToString(", ", prefix = "( ", postfix = " )")
100100
{ "(${it.first}, ${it.second})" }
101101
body?.p { +"Preselection (period_number, run_number) returned: $periodsRunsJoined" }
102-
println("Preselection (period_number, run_number) returned: $periodsRunsJoined")
102+
debug("Preselection (period_number, run_number) returned: $periodsRunsJoined")
103103
filterCriteria.add(" (period_number, run_number) IN $periodsRunsJoined")
104104
}
105105
}
@@ -118,13 +118,13 @@ fun queryEMD(
118118
query += " OFFSET ${offset.stringValue}"
119119
}
120120

121-
println(query)
121+
debug(query)
122122

123123
try {
124124
val res = connEMD.createStatement().executeQuery(query)
125125
return res
126126
} catch (err: PSQLException) {
127-
println("Error querying the database: ${err}")
127+
debug("Error querying the database: ${err}")
128128
return null
129129
}
130130

src/jvmMain/kotlin/config.kt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ fun readConfig(): ConfigFile? {
1515
} catch (e: java.lang.Exception) {
1616
println(
1717
"Could not read config file from $CONFIG_PATH. \n" +
18-
"Make sure the file is there and has proper format (if in Docker, mount as volume)"
18+
"Make sure the file is there and has proper format (if in container, mount as volume)"
1919
)
2020
return null
2121
}

src/jvmMain/kotlin/keycloak.kt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,22 +48,22 @@ fun getKCtoken(config: ConfigFile, username: String, pass: String): String? {
4848
token = keycloak.tokenManager().grantToken()
4949
// println(token.token)
5050
} catch (e: NotAuthorizedException) {
51-
println("Authentication failed, no token obtained!")
51+
debug("Authentication failed, no token obtained!")
5252
return null
5353
}
54-
return token!!.token .also{ println("getKCtoken: token was obtained") } //.also { println(it) }
54+
return token!!.token .also{ debug("getKCtoken: token was obtained") } //.also { println(it) }
5555
}
5656

5757
suspend fun getKCgroups(config: ConfigFile, token: String): List<String> {
5858
val parser = JwtParser()
5959
val jsonToken = parser.parseToJsonObject(token)
60-
// println(jsonToken?.get("groups"))
60+
// debug(jsonToken?.get("groups"))
6161
val res = mutableListOf<String>()
6262
jsonToken?.get("groups")?.jsonArray?.forEach {
63-
// println(it)
63+
// debug(it)
6464
res.add((it.toString().replace("/", "").replace("\"", "")))
6565
}
66-
// println(res)
66+
// debug(res)
6767
return res
6868
}
6969

0 commit comments

Comments
 (0)