11package fi.hsl.transitdata.dbmonitor
22
3- import com.fasterxml.jackson.core.JsonFactory
4- import com.fasterxml.jackson.databind.ObjectMapper
5- import com.fasterxml.jackson.module.kotlin.KotlinModule
63import com.typesafe.config.Config
74import kotlinx.coroutines.Dispatchers
85import kotlinx.coroutines.runBlocking
96import kotlinx.coroutines.withContext
7+ import mu.KotlinLogging
108import java.net.URL
119import java.sql.Connection
12- import java.sql.DriverManager
1310import java.sql.Statement
1411
15-
1612object MonitorService{
17-
18- private val f = JsonFactory ()
19- private val mapper: ObjectMapper = ObjectMapper (f).registerModule(KotlinModule ())
13+ private val log = KotlinLogging .logger {}
2014
2115 fun start (config : Config , connection : Connection )= runBlocking {
2216 try {
2317 connection.use {
2418 config.getConfigList(" databases" ).forEach {
25- endpointToCheck -> checkIfDbIfReachable(endpointToCheck.getString(" dblabel" ), endpointToCheck.getString(" dbname" ), it)
19+ endpointToCheck -> (
20+ try {
21+ checkIfDbIfReachable(endpointToCheck.getString(" dblabel" ), endpointToCheck.getString(" dbname" ), it)
22+ }
23+ catch (e : Exception ){
24+ log.error (" Failed to connect to db" , e)
25+ sendErrorMessageToSlack(e, config)
26+ })
2627 }
2728 }
2829 }
@@ -31,31 +32,29 @@ object MonitorService{
3132 }
3233 }
3334
34- private fun sendErrorMessageToSlack (e : Exception , config : Config ){
35+ private fun sendErrorMessageToSlack (e : Exception , config : Config , dblabel : String? = null ){
3536
3637 val url = URL (config.getString(" slackbridge" ))
3738 val headers : Map <String , String > = mapOf (
3839 Pair (" Content-type" ," application/json" )
3940 )
40-
4141 NetworkHelper .getResponse(url, headers, config.getString(" errormessage" ) + " " + e.message)
42- throw e
4342 }
4443
4544 /* *
4645 * Throws an exception if can't reach the db
4746 */
4847 private suspend fun checkIfDbIfReachable (dblabel : String , dbname : String , connection : Connection ){
49- withContext(Dispatchers .IO ) {
50- try {
51- val stmt: Statement = connection.createStatement()
52- stmt.execute(" use [$dbname ]" )
53- stmt.close()
54- assert (connection.isValid(5000 ))
55- } catch (e: Exception ) {
56- throw Exception (" Connection to DB $dblabel failed" )
57- }
58- }
48+ withContext(Dispatchers .IO ){
49+ try {
50+ val stmt: Statement = connection.createStatement()
51+ stmt.execute(" use [$dbname ]" )
52+ stmt.close()
53+ assert (connection.isValid(5000 ))
54+ } catch (e: Exception ) {
55+ throw Exception (" Connection to DB $dblabel failed" , e )
56+ }
57+ }
5958 }
6059}
6160
0 commit comments