diff --git a/src/main/scala/com/expedia/www/haystack/commons/util/MetricDefinitionKeyGenerator.scala b/src/main/scala/com/expedia/www/haystack/commons/util/MetricDefinitionKeyGenerator.scala new file mode 100644 index 0000000..e5ba4c0 --- /dev/null +++ b/src/main/scala/com/expedia/www/haystack/commons/util/MetricDefinitionKeyGenerator.scala @@ -0,0 +1,19 @@ +package com.expedia.www.haystack.commons.util + +import com.expedia.metrics.{MetricDefinition, TagCollection} + +import scala.collection.JavaConverters._ +import scala.collection.immutable.ListMap + +object MetricDefinitionKeyGenerator { + + def generateKey(metricDefinition: MetricDefinition): String = { + List(s"key=${metricDefinition.getKey}", getTagsAsString(metricDefinition.getTags), + getTagsAsString(metricDefinition.getMeta)).filter(!_.isEmpty).mkString(",") + } + + def getTagsAsString(tags: TagCollection): String = { + ListMap(tags.getKv.asScala.toSeq.sortBy(_._1): _*).map(tag => s"${tag._1}=${tag._2}").mkString(",") + } + +} diff --git a/src/test/scala/com/expedia/www/haystack/commons/util/MetricDefinitionKeyGeneratorSpec.scala b/src/test/scala/com/expedia/www/haystack/commons/util/MetricDefinitionKeyGeneratorSpec.scala new file mode 100644 index 0000000..b97ab1e --- /dev/null +++ b/src/test/scala/com/expedia/www/haystack/commons/util/MetricDefinitionKeyGeneratorSpec.scala @@ -0,0 +1,37 @@ +package com.expedia.www.haystack.commons.util + +import java.util + +import com.expedia.metrics.{MetricDefinition, TagCollection} +import com.expedia.www.haystack.commons.entities.TagKeys.PRODUCT_KEY +import com.expedia.www.haystack.commons.unit.UnitTestSpec + +class MetricDefinitionKeyGeneratorSpec extends UnitTestSpec { + "Metric Definition Key Generator" should { + "generate a unique key based on key and tags in MetricDefinition" in { + Given("a Metric Definition") + val metricDefinition = getMetricDefinition + + When("MetricDefinitionKeyGenerator is called") + val key = MetricDefinitionKeyGenerator.generateKey(metricDefinition) + + Then("a unique key is generated") + key should equal("key=duration,mtype=gauge,op=some-op,product=haystack,svc=some-svc,unit=short") + } + } + + private def getMetricDefinition: MetricDefinition = { + val metricTags = new util.LinkedHashMap[String, String] { + put("svc", "some-svc") + put("op", "some-op") + } + val tags = new util.LinkedHashMap[String, String] { + putAll(metricTags) + put(MetricDefinition.MTYPE, "gauge") + put(MetricDefinition.UNIT, "short") + put(PRODUCT_KEY, "haystack") + } + val tc = new TagCollection(tags) + new MetricDefinition("duration", tc, TagCollection.EMPTY) + } +}