From 9660774fd192cf28871cebd3b4fe622d04f1b3b7 Mon Sep 17 00:00:00 2001
From: Aliaksandr Valialkin <valyala@gmail.com>
Date: Mon, 7 Dec 2020 01:07:03 +0200
Subject: [PATCH] app/vmselect/graphite: remove duplicate `name` tag from
 `/tags/autoComplete/tags` handler

Updates https://github.com/VictoriaMetrics/VictoriaMetrics/issues/942
---
 app/vmselect/netstorage/netstorage.go | 20 ++++++++++++++++++--
 docs/CHANGELOG.md                     |  2 ++
 2 files changed, 20 insertions(+), 2 deletions(-)

diff --git a/app/vmselect/netstorage/netstorage.go b/app/vmselect/netstorage/netstorage.go
index b861f9dc80..5b9226e8be 100644
--- a/app/vmselect/netstorage/netstorage.go
+++ b/app/vmselect/netstorage/netstorage.go
@@ -586,11 +586,18 @@ func GetGraphiteTags(at *auth.Token, denyPartialResponse bool, filter string, li
 	}
 	// Substitute "__name__" with "name" for Graphite compatibility
 	for i := range labels {
-		if labels[i] == "__name__" {
+		if labels[i] != "__name__" {
+			continue
+		}
+		// Prevent from duplicate `name` tag.
+		// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/942
+		if hasString(labels, "name") {
+			labels = append(labels[:i], labels[i+1:]...)
+		} else {
 			labels[i] = "name"
 			sort.Strings(labels)
-			break
 		}
+		break
 	}
 	if len(filter) > 0 {
 		labels, err = applyGraphiteRegexpFilter(filter, labels)
@@ -604,6 +611,15 @@ func GetGraphiteTags(at *auth.Token, denyPartialResponse bool, filter string, li
 	return labels, isPartial, nil
 }
 
+func hasString(a []string, s string) bool {
+	for _, x := range a {
+		if x == s {
+			return true
+		}
+	}
+	return false
+}
+
 // GetLabels returns labels until the given deadline.
 func GetLabels(at *auth.Token, denyPartialResponse bool, deadline searchutils.Deadline) ([]string, bool, error) {
 	if deadline.Exceeded() {
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 4e0c99124e..6f7487c911 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,6 +6,8 @@
   Though [InfluxDB line protocol](https://docs.influxdata.com/influxdb/v1.8/write_protocols/line_protocol_tutorial/) denies multiple whitespace chars between these entities,
   some apps improperly put multiple whitespace chars. This workaround allows accepting data from such apps.
 
+* BUGFIX: prevent from duplicate `name` tag returned from `/tags/autoComplete/tags` handler. See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/942
+
 
 # [v1.49.0](https://github.com/VictoriaMetrics/VictoriaMetrics/releases/tag/v1.49.0)