code format

This commit is contained in:
Martin Ptáček
2023-07-26 15:17:43 +02:00
parent ea856001ae
commit a55be0b8a5
12 changed files with 80 additions and 86 deletions

View File

@ -115,7 +115,7 @@ data class PromConfiguration(
fun fromWorkData(data: Data): PromConfiguration { fun fromWorkData(data: Data): PromConfiguration {
val jsonString: String = data.getString("json") val jsonString: String = data.getString("json")
?: throw Exception("PromConfiguration serialization not working correctly!") ?: throw Exception("PromConfiguration serialization not working correctly!")
return Json.decodeFromString<PromConfiguration>(jsonString) return Json.decodeFromString(jsonString)
} }
fun loadFromConfigFile(context: Context): PromConfiguration { fun loadFromConfigFile(context: Context): PromConfiguration {

View File

@ -43,7 +43,7 @@ class MainActivity : ComponentActivity() {
navController: NavHostController = rememberNavController(), navController: NavHostController = rememberNavController(),
promViewModel: PromViewModel promViewModel: PromViewModel
) { ) {
val startDestination: String = "homepage" val startDestination = "homepage"
NavHost( NavHost(
navController = navController, navController = navController,
startDestination = startDestination, startDestination = startDestination,

View File

@ -7,13 +7,14 @@ import android.content.Intent
import android.content.IntentFilter import android.content.IntentFilter
import android.hardware.SensorManager import android.hardware.SensorManager
import android.os.BatteryManager import android.os.BatteryManager
import androidx.core.content.ContextCompat.getSystemService
class MetricsEngine(private val context: Context) { class MetricsEngine(private val context: Context) {
private lateinit var sensorManager: SensorManager; private lateinit var sensorManager: SensorManager;
init { init {
//sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager //sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
} }
public fun batteryChargeRatio(): Float { public fun batteryChargeRatio(): Float {
val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { intFilter -> val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { intFilter ->
context.registerReceiver(null, intFilter) context.registerReceiver(null, intFilter)
@ -39,7 +40,6 @@ class MetricsEngine(private val context: Context) {
} }
//TODO //TODO
///TYPE_ACCELEROMETER Yes Yes Yes Yes ///TYPE_ACCELEROMETER Yes Yes Yes Yes
//TYPE_AMBIENT_TEMPERATURE Yes n/a n/a n/a //TYPE_AMBIENT_TEMPERATURE Yes n/a n/a n/a

View File

@ -4,9 +4,7 @@ package com.birdthedeveloper.prometheus.android.exporter.worker
import android.app.NotificationManager import android.app.NotificationManager
import android.content.Context import android.content.Context
import android.os.Build
import android.util.Log import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat
import androidx.work.CoroutineWorker import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo import androidx.work.ForegroundInfo
@ -20,10 +18,8 @@ import io.prometheus.client.exporter.common.TextFormat
import kotlinx.coroutines.DelicateCoroutinesApi import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.io.StringWriter import java.io.StringWriter
@ -132,6 +128,7 @@ class PromWorker(
return Result.success() return Result.success()
} }
override suspend fun getForegroundInfo(): ForegroundInfo { override suspend fun getForegroundInfo(): ForegroundInfo {
return createForegroundInfo() return createForegroundInfo()
} }

View File

@ -27,7 +27,7 @@ data class PrometheusServerConfig(
) )
// Expose metrics on given port using Ktor http server // Expose metrics on given port using Ktor http server
class PrometheusServer() { class PrometheusServer {
companion object { companion object {
suspend fun start(config: PrometheusServerConfig) { suspend fun start(config: PrometheusServerConfig) {
Log.d(TAG, "Starting prometheus server") Log.d(TAG, "Starting prometheus server")

View File

@ -16,7 +16,6 @@ import io.prometheus.client.CollectorRegistry
import io.prometheus.client.Counter import io.prometheus.client.Counter
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
private const val TAG = "PUSHPROX_CLIENT" private const val TAG = "PUSHPROX_CLIENT"
@ -118,8 +117,8 @@ class PushProxClient(private val pushProxConfig: PushProxConfig) {
modifiedProxyURL = "http://$modifiedProxyURL" modifiedProxyURL = "http://$modifiedProxyURL"
} }
val pollURL: String = "$modifiedProxyURL/poll" val pollURL = "$modifiedProxyURL/poll"
val pushURL: String = "$modifiedProxyURL/push" val pushURL = "$modifiedProxyURL/push"
return PushProxContext( return PushProxContext(
client, client,

View File

@ -3,8 +3,6 @@
package com.birdthedeveloper.prometheus.android.exporter.worker package com.birdthedeveloper.prometheus.android.exporter.worker
import android.content.Context import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.util.Log import android.util.Log
import io.ktor.client.HttpClient import io.ktor.client.HttpClient
import io.ktor.client.request.header import io.ktor.client.request.header
@ -21,7 +19,6 @@ import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.lang.IndexOutOfBoundsException
private const val TAG: String = "REMOTE_WRITE_SENDER" private const val TAG: String = "REMOTE_WRITE_SENDER"
@ -112,7 +109,7 @@ class RemoteWriteSender(private val config: RemoteWriteConfiguration) {
} }
private suspend fun scraper(channel: Channel<Unit>) { private suspend fun scraper(channel: Channel<Unit>) {
val checkDelay : Long = 1000L val checkDelay = 1000L
insertInitialDummyScrape() insertInitialDummyScrape()
@ -163,7 +160,10 @@ class RemoteWriteSender(private val config: RemoteWriteConfiguration) {
ExponentialBackoff.runWithBackoff({ ExponentialBackoff.runWithBackoff({
sendRequestToRemoteWrite(body, config.maxSamplesPerExport) sendRequestToRemoteWrite(body, config.maxSamplesPerExport)
}, { }, {
Log.d(TAG, "exportToRemoteWriteEndpointException, ${it.message}, ${it}, ${it.stackTraceToString()}") Log.d(
TAG,
"exportToRemoteWriteEndpointException, ${it.message}, ${it}, ${it.stackTraceToString()}"
)
}, "Remote Write", false) }, "Remote Write", false)
Log.d(TAG, "Exponential backoff to export remote write finish") Log.d(TAG, "Exponential backoff to export remote write finish")
} }
@ -245,11 +245,13 @@ class RemoteWriteSender(private val config: RemoteWriteConfiguration) {
// this export was successful // this export was successful
storage.removeNumberOfScrapedSamples(numOfMetricScrapes) storage.removeNumberOfScrapedSamples(numOfMetricScrapes)
} }
HttpStatusCode.BadRequest -> { HttpStatusCode.BadRequest -> {
// probably some error or race condition has occured // probably some error or race condition has occured
// give up trying to send this data // give up trying to send this data
storage.removeNumberOfScrapedSamples(numOfMetricScrapes) storage.removeNumberOfScrapedSamples(numOfMetricScrapes)
} }
else -> { else -> {
throw TryExportMetricsAgainException("Status code: ${response.status.description}") throw TryExportMetricsAgainException("Status code: ${response.status.description}")
} }

View File

@ -10,7 +10,7 @@ import java.util.Queue
// HashMap<List of labels including name, List of TimeSeries samples to this TimeSeries> // HashMap<List of labels including name, List of TimeSeries samples to this TimeSeries>
private typealias ConverterHashMap = HashMap<List<TimeSeriesLabel>, MutableList<TimeSeriesSample>> private typealias ConverterHashMap = HashMap<List<TimeSeriesLabel>, MutableList<TimeSeriesSample>>
private const val TAG : String = "REMOTE_WRITE_SENDER_MEMORY_SIMPLE_STORAGE"; private const val TAG: String = "REMOTE_WRITE_SENDER_MEMORY_SIMPLE_STORAGE"
class RemoteWriteSenderSimpleMemoryStorage : RemoteWriteSenderStorage() { class RemoteWriteSenderSimpleMemoryStorage : RemoteWriteSenderStorage() {
private val data: Queue<MetricsScrape> = LinkedList() private val data: Queue<MetricsScrape> = LinkedList()
@ -18,7 +18,7 @@ class RemoteWriteSenderSimpleMemoryStorage : RemoteWriteSenderStorage() {
private fun filterExpiredMetrics(metrics: MutableList<MetricsScrape>) { private fun filterExpiredMetrics(metrics: MutableList<MetricsScrape>) {
val now: Long = System.currentTimeMillis() val now: Long = System.currentTimeMillis()
val oldestMetricTimeMs: Long = now - maxMetricsAge * 1000 val oldestMetricTimeMs: Long = now - maxMetricsAge * 1000
var howManyMetricsRemove : Int = 0 var howManyMetricsRemove = 0
// count how many metrics to remove // count how many metrics to remove
for (i in 0 until metrics.size) { for (i in 0 until metrics.size) {
@ -27,7 +27,7 @@ class RemoteWriteSenderSimpleMemoryStorage : RemoteWriteSenderStorage() {
if (scrape.timeSeriesList.first().sample.timeStampMs < oldestMetricTimeMs) { if (scrape.timeSeriesList.first().sample.timeStampMs < oldestMetricTimeMs) {
howManyMetricsRemove++ howManyMetricsRemove++
} else { } else {
break; // I suppose scrapes were performed one after another break // I suppose scrapes were performed one after another
} }
} }
} }
@ -56,7 +56,8 @@ class RemoteWriteSenderSimpleMemoryStorage : RemoteWriteSenderStorage() {
} }
private fun hashmapToProtobufWriteRequest(hashMap: ConverterHashMap): RemoteWrite.WriteRequest { private fun hashmapToProtobufWriteRequest(hashMap: ConverterHashMap): RemoteWrite.WriteRequest {
val writeRequestBuilder: RemoteWrite.WriteRequest.Builder = RemoteWrite.WriteRequest.newBuilder() val writeRequestBuilder: RemoteWrite.WriteRequest.Builder =
RemoteWrite.WriteRequest.newBuilder()
for (entry in hashMap) { for (entry in hashMap) {
val timeSeries = hashMapEntryToProtobufTimeSeries(entry.key, entry.value) val timeSeries = hashMapEntryToProtobufTimeSeries(entry.key, entry.value)
@ -84,9 +85,10 @@ class RemoteWriteSenderSimpleMemoryStorage : RemoteWriteSenderStorage() {
filterExpiredMetrics(scrapedMetrics) filterExpiredMetrics(scrapedMetrics)
val writeRequest: RemoteWrite.WriteRequest = metricsScrapeListToProtobuf(scrapedMetrics.toList()) val writeRequest: RemoteWrite.WriteRequest =
metricsScrapeListToProtobuf(scrapedMetrics.toList())
val bytes: ByteArray = writeRequest.toByteArray() val bytes: ByteArray = writeRequest.toByteArray()
return RemoteWriteSenderStorage.encodeWithSnappy(bytes) return encodeWithSnappy(bytes)
} }
private fun metricsScrapeListToProtobuf(input: List<MetricsScrape>): RemoteWrite.WriteRequest { private fun metricsScrapeListToProtobuf(input: List<MetricsScrape>): RemoteWrite.WriteRequest {
@ -102,9 +104,7 @@ class RemoteWriteSenderSimpleMemoryStorage : RemoteWriteSenderStorage() {
} }
} }
val result: RemoteWrite.WriteRequest = hashmapToProtobufWriteRequest(hashmap) return hashmapToProtobufWriteRequest(hashmap)
return result
} }
private fun processStorageTimeSeries(hashMap: ConverterHashMap, timeSeries: StorageTimeSeries) { private fun processStorageTimeSeries(hashMap: ConverterHashMap, timeSeries: StorageTimeSeries) {
@ -129,7 +129,7 @@ class RemoteWriteSenderSimpleMemoryStorage : RemoteWriteSenderStorage() {
if (number > 0) { if (number > 0) {
for (i in 1..number) { for (i in 1..number) {
if (data.isEmpty()) { if (data.isEmpty()) {
break; break
} else { } else {
data.remove() data.remove()
} }

View File

@ -2,17 +2,12 @@
package com.birdthedeveloper.prometheus.android.exporter.worker package com.birdthedeveloper.prometheus.android.exporter.worker
import android.util.Log
import io.prometheus.client.Collector.MetricFamilySamples import io.prometheus.client.Collector.MetricFamilySamples
import kotlinx.serialization.Serializable import kotlinx.serialization.Serializable
import org.iq80.snappy.Snappy import org.iq80.snappy.Snappy
import remote.write.RemoteWrite.Label import remote.write.RemoteWrite.Label
import remote.write.RemoteWrite.Sample import remote.write.RemoteWrite.Sample
import remote.write.RemoteWrite.TimeSeries
import remote.write.RemoteWrite.WriteRequest
import java.util.Enumeration import java.util.Enumeration
import java.util.LinkedList
import java.util.Queue
private const val TAG: String = "REMOTE_WRITE_SENDER_STORAGE" private const val TAG: String = "REMOTE_WRITE_SENDER_STORAGE"
@ -114,6 +109,7 @@ abstract class RemoteWriteSenderStorage {
name = "backfill", name = "backfill",
value = "true", value = "true",
) )
fun encodeWithSnappy(data: ByteArray): ByteArray { fun encodeWithSnappy(data: ByteArray): ByteArray {
return Snappy.compress(data) return Snappy.compress(data)
} }