Repository: knative/pkg
Pull request #1495 (2020-07-15 03:02:00)

Update Stackdriver custom exporter to support RecordBatch where some records are special and others are not.
/assign @jjzeng-seattle 

This addresses the usage at https://github.com/knative/serving/blob/master/pkg/reconciler/autoscaling/kpa/kpa.go#L220 where `requested_pod_count` is promoted to a "native" Stackdriver type, but `not_ready_pod_count` and `terminating_pod_count` are not.

I *really hope* that this is the last customization we need in `pkg` that corresponds to a Stackdriver backend change somewhere in Google's source control systems (and once we move to OpenCensus exporting, this translation can be done in an OpenCensus collector-compatible binary shipped by the Google Cloud Run team).

knative-prow-robot: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/knative/pkg/pull/1495#" title="Author self-approved">evankanderson</a>*

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=knative%2Fpkg).

The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process)

<details >
Needs approval from an approver in each of these files:

- ~~[metrics/OWNERS](https://github.com/knative/pkg/blob/master/metrics/OWNERS)~~ [evankanderson]

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":[]} -->
evankanderson: /assign @yanweiguo 

Sorry that the diff in `stackdriver_exporter.go` is so wonky; GitHub's diff computer seems to have made some bad choices when I indented the block and renamed a few variables.
knative-metrics-robot: The following is the coverage report on the affected files.
Say `/test pull-knative-pkg-go-coverage` to re-run this coverage report

File | Old Coverage | New Coverage | Delta
---- |:------------:|:------------:|:-----:
[metrics/stackdriver_exporter.go](https://storage.cloud.google.com/knative-prow/pr-logs/pull/knative_pkg/1495/pull-knative-pkg-go-coverage/1283235462734942208/artifacts/line-cov.html#file1) | 87.0% | 86.7% | -0.3

knative-prow-robot: @evankanderson: The following test **failed**, say `/retest` to rerun all failed tests:

Test name | Commit | Details | Rerun command
--- | --- | --- | ---
pull-knative-pkg-unit-tests | cce4e5f43894f27645fd9f2756b4a32e0537b5e5 | [link](https://prow.knative.dev/view/gcs/knative-prow/pr-logs/pull/knative_pkg/1495/pull-knative-pkg-unit-tests/1283235462734942209) | `/test pull-knative-pkg-unit-tests`

[Full PR test history](https://gubernator.knative.dev/pr/knative_pkg/1495). [Your PR dashboard](https://gubernator.knative.dev/pr/evankanderson).

<details>

Instructions for interacting with me using PR comments are available [here](https://git.k8s.io/community/contributors/guide/pull-requests.md).  If you have questions or suggestions related to my behavior, please file an issue against the [kubernetes/test-infra](https://github.com/kubernetes/test-infra/issues/new?title=Prow%20issue:) repository. I understand the commands that are listed [here](https://go.k8s.io/bot-commands).
</details>
<!-- test report -->
evankanderson: /retest

Patch:
diff --git a/controller/controller.go b/controller/controller.go
index 6024ec253..03f67b6ec 100644
--- a/controller/controller.go
+++ b/controller/controller.go
@@ -452,7 +452,7 @@ func (c *Impl) processNextWorkItem() bool {
 		if err != nil {
 			status = falseString
 		}
-		c.statsReporter.ReportReconcile(time.Since(startTime), keyStr, status)
+		c.statsReporter.ReportReconcile(time.Since(startTime), status)
 	}()
 
 	// Embed the key into the logger and attach that to the context we pass
diff --git a/controller/stats_reporter.go b/controller/stats_reporter.go
index c3445ed3d..6efaeca0f 100644
--- a/controller/stats_reporter.go
+++ b/controller/stats_reporter.go
@@ -46,7 +46,6 @@ var (
 	// - length between 1 and 255 inclusive
 	// - characters are printable US-ASCII
 	reconcilerTagKey = tag.MustNewKey("reconciler")
-	keyTagKey        = tag.MustNewKey("key")
 	successTagKey    = tag.MustNewKey("success")
 )
 
@@ -167,12 +166,12 @@ func init() {
 		Description: "Number of reconcile operations",
 		Measure:     reconcileCountStat,
 		Aggregation: view.Count(),
-		TagKeys:     []tag.Key{reconcilerTagKey, keyTagKey, successTagKey},
+		TagKeys:     []tag.Key{reconcilerTagKey, successTagKey},
 	}, {
 		Description: "Latency of reconcile operations",
 		Measure:     reconcileLatencyStat,
 		Aggregation: reconcileDistribution,
-		TagKeys:     []tag.Key{reconcilerTagKey, keyTagKey, successTagKey},
+		TagKeys:     []tag.Key{reconcilerTagKey, successTagKey},
 	}}
 	views = append(views, wp.DefaultViews()...)
 	views = append(views, rp.DefaultViews()...)
@@ -192,7 +191,7 @@ type StatsReporter interface {
 	ReportQueueDepth(v int64) error
 
 	// ReportReconcile reports the count and latency metrics for a reconcile operation
-	ReportReconcile(duration time.Duration, key, success string) error
+	ReportReconcile(duration time.Duration, success string) error
 }
 
 // Reporter holds cached metric objects to report metrics
@@ -234,11 +233,10 @@ func (r *reporter) ReportQueueDepth(v int64) error {
 }
 
 // ReportReconcile reports the count and latency metrics for a reconcile operation
-func (r *reporter) ReportReconcile(duration time.Duration, key, success string) error {
+func (r *reporter) ReportReconcile(duration time.Duration, success string) error {
 	ctx, err := tag.New(
 		context.Background(),
 		tag.Insert(reconcilerTagKey, r.reconciler),
-		tag.Insert(keyTagKey, key),
 		tag.Insert(successTagKey, success))
 	if err != nil {
 		return err
diff --git a/metrics/stackdriver_exporter.go b/metrics/stackdriver_exporter.go
index 1e1a85ae2..96d72dd24 100644
--- a/metrics/stackdriver_exporter.go
+++ b/metrics/stackdriver_exporter.go
@@ -206,76 +206,71 @@ func sdCustomMetricsRecorder(mc metricsConfig, allowCustomMetrics bool) func(con
 		metricskey.LabelClusterName: gm.cluster,
 	}
 	return func(ctx context.Context, mss []stats.Measurement, ros ...stats.Options) error {
-		i := 0
-		var templ *resourceTemplate
-		templateFound := false
+		// Some metrics may be promoted to known Stackdriver schemas, so we may
+		// end up multiple Resources recorded for a single `RecordBatch` call.
+		metricsByResource := map[*resourceTemplate][]stats.Measurement{}
 
-		// This loop serves two purpose, filtering out custom metrics when allowCustomMetrics set to false,
-		// and find the template for the system metrics.
 		for _, m := range mss {
 			metricType := path.Join(mc.stackdriverMetricTypePrefix, m.Measure().Name())
 			t, ok := metricToResourceLabels[metricType]
 			if ok || allowCustomMetrics {
-				mss[i] = m
-				i++
-				if templateFound && templ != t {
-					return fmt.Errorf("mixed resource type measurements in one report: %v", mss)
+				if metricsByResource[t] == nil {
+					metricsByResource[t] = make([]stats.Measurement, 0, len(mss))
 				}
-				templ = t
-				templateFound = true
+				metricsByResource[t] = append(metricsByResource[t], m)
 			}
 		}
-		// Trim the array
-		mss = mss[:i]
-		if i == 0 {
-			return nil
-		}
 
+		baseLabels := map[string]string{}
 		baseResource := metricskey.GetResource(ctx)
-		// Extract resource, if possible
-		if templ != nil {
-			tagMap := tag.FromContext(ctx)
-			r := resource.Resource{
-				Type:   templ.Type,
-				Labels: map[string]string{},
-			}
-			tagMutations := make([]tag.Mutator, 0, len(templ.LabelKeys))
-			if baseResource == nil {
-				baseResource = &resource.Resource{}
-			}
-			for k := range templ.LabelKeys {
-				if v, ok := baseResource.Labels[k]; ok {
-					r.Labels[k] = v
-					continue
+		if baseResource != nil {
+			baseLabels = baseResource.Labels
+		}
+		tagMap := tag.FromContext(ctx)
+		for templ, ms := range metricsByResource {
+			sdResource := baseResource
+			sdCtx := ctx
+			if templ != nil {
+				sdResource = &resource.Resource{
+					Type:   templ.Type,
+					Labels: map[string]string{},
 				}
-				tagKey := tag.MustNewKey(k)
-				if v, ok := tagMap.Value(tagKey); ok {
-					r.Labels[k] = v
-					tagMutations = append(tagMutations, tag.Delete(tagKey))
-					continue
+				tagMutations := make([]tag.Mutator, 0, len(templ.LabelKeys))
+				for k := range templ.LabelKeys {
+					if v, ok := baseLabels[k]; ok {
+						sdResource.Labels[k] = v
+						continue
+					}
+					tagKey := tag.MustNewKey(k)
+					if v, ok := tagMap.Value(tagKey); ok {
+						sdResource.Labels[k] = v
+						tagMutations = append(tagMutations, tag.Delete(tagKey))
+						continue
+					}
+					if v, ok := metadataMap[k]; ok {
+						sdResource.Labels[k] = v
+						continue
+					}
+					sdResource.Labels[k] = metricskey.ValueUnknown
 				}
-				if v, ok := metadataMap[k]; ok {
-					r.Labels[k] = v
-					continue
+				var err error
+				sdCtx, err = tag.New(metricskey.WithResource(ctx, *sdResource), tagMutations...)
+				if err != nil {
+					return err
 				}
-				r.Labels[k] = metricskey.ValueUnknown
 			}
-			var err error
-			ctx, err = tag.New(metricskey.WithResource(ctx, r), tagMutations...)
-			if err != nil {
-				return err
+			if sdResource != nil {
+				opt, err := optionForResource(sdResource)
+				if err != nil {
+					return err
+				}
+				ros = append(ros, opt)
 			}
-			baseResource = &r
-		}
-		if baseResource != nil {
-			opt, err := optionForResource(baseResource)
-			if err != nil {
+			if err := stats.RecordWithOptions(sdCtx, append(ros, stats.WithMeasurements(ms...))...); err != nil {
 				return err
 			}
-			ros = append(ros, opt)
 		}
-
-		return stats.RecordWithOptions(ctx, append(ros, stats.WithMeasurements(mss...))...)
+		return nil
 	}
 }
 


Test patch:
diff --git a/controller/stats_reporter_test.go b/controller/stats_reporter_test.go
index d82e7fe35..ff56d99a3 100644
--- a/controller/stats_reporter_test.go
+++ b/controller/stats_reporter_test.go
@@ -68,7 +68,6 @@ func TestReportReconcile(t *testing.T) {
 	r, _ := NewStatsReporter("testreconciler")
 	wantTags := map[string]string{
 		"reconciler": "testreconciler",
-		"key":        "test/key",
 		"success":    "true",
 	}
 
@@ -81,11 +80,11 @@ func TestReportReconcile(t *testing.T) {
 		initialReconcileLatency = d[0].Data.(*view.DistributionData).Sum()
 	}
 
-	expectSuccess(t, func() error { return r.ReportReconcile(10*time.Millisecond, "test/key", "true") })
+	expectSuccess(t, func() error { return r.ReportReconcile(10*time.Millisecond, "true") })
 	metricstest.CheckCountData(t, "reconcile_count", wantTags, initialReconcileCount+1)
 	metricstest.CheckDistributionData(t, "reconcile_latency", wantTags, 1, initialReconcileLatency+10, initialReconcileLatency+10)
 
-	expectSuccess(t, func() error { return r.ReportReconcile(15*time.Millisecond, "test/key", "true") })
+	expectSuccess(t, func() error { return r.ReportReconcile(15*time.Millisecond, "true") })
 	metricstest.CheckCountData(t, "reconcile_count", wantTags, initialReconcileCount+2)
 	metricstest.CheckDistributionData(t, "reconcile_latency", wantTags, 2, initialReconcileLatency+10, initialReconcileLatency+15)
 }
diff --git a/controller/testing/fake_stats_reporter.go b/controller/testing/fake_stats_reporter.go
index 506754dc1..528a854b3 100644
--- a/controller/testing/fake_stats_reporter.go
+++ b/controller/testing/fake_stats_reporter.go
@@ -30,8 +30,8 @@ type FakeStatsReporter struct {
 
 // FakeReconcileStatData is used to record the calls to ReportReconcile
 type FakeReconcileStatData struct {
-	Duration     time.Duration
-	Key, Success string
+	Duration time.Duration
+	Success  string
 }
 
 // ReportQueueDepth records the call and returns success.
@@ -43,10 +43,10 @@ func (r *FakeStatsReporter) ReportQueueDepth(v int64) error {
 }
 
 // ReportReconcile records the call and returns success.
-func (r *FakeStatsReporter) ReportReconcile(duration time.Duration, key, success string) error {
+func (r *FakeStatsReporter) ReportReconcile(duration time.Duration, success string) error {
 	r.Lock.Lock()
 	defer r.Lock.Unlock()
-	r.reconcileData = append(r.reconcileData, FakeReconcileStatData{duration, key, success})
+	r.reconcileData = append(r.reconcileData, FakeReconcileStatData{duration, success})
 	return nil
 }
 
diff --git a/controller/testing/fake_stats_reporter_test.go b/controller/testing/fake_stats_reporter_test.go
index dc2f894df..8fde1c7e4 100644
--- a/controller/testing/fake_stats_reporter_test.go
+++ b/controller/testing/fake_stats_reporter_test.go
@@ -38,8 +38,8 @@ func TestReportQueueDepth(t *testing.T) {
 
 func TestReportReconcile(t *testing.T) {
 	r := &FakeStatsReporter{}
-	r.ReportReconcile(time.Duration(123), "testkey", "False")
-	if got, want := r.GetReconcileData(), []FakeReconcileStatData{{time.Duration(123), "testkey", "False"}}; !reflect.DeepEqual(want, got) {
+	r.ReportReconcile(time.Duration(123), "False")
+	if got, want := r.GetReconcileData(), []FakeReconcileStatData{{time.Duration(123), "False"}}; !reflect.DeepEqual(want, got) {
 		t.Errorf("reconcile data len: want: %v, got: %v", want, got)
 	}
 }
diff --git a/metrics/resource_view_test.go b/metrics/resource_view_test.go
index e8c5262a1..76b9e23c7 100644
--- a/metrics/resource_view_test.go
+++ b/metrics/resource_view_test.go
@@ -25,6 +25,7 @@ import (
 	"net/http"
 	"os"
 	"sort"
+	"strings"
 	"sync"
 	"testing"
 	"time"
@@ -450,8 +451,11 @@ func TestStackDriverExports(t *testing.T) {
 		"revision_name":      "revision2",
 		"service_name":       "service2",
 	}
-	label3 := map[string]string{
-		"key": "value",
+	batchLabels := map[string]string{
+		"namespace_name":     "ns2",
+		"configuration_name": "config2",
+		"revision_name":      "revision2",
+		"service_name":       "service2",
 	}
 	harness := []struct {
 		name               string
@@ -472,8 +476,8 @@ func TestStackDriverExports(t *testing.T) {
 				2,
 			},
 			{
-				"custom.googleapis.com/knative.dev/autoscaler/testing/value",
-				label3,
+				"custom.googleapis.com/knative.dev/autoscaler/not_ready_pods",
+				batchLabels,
 				3,
 			},
 		},
@@ -516,14 +520,13 @@ func TestStackDriverExports(t *testing.T) {
 				Measure:     desiredPodCountM,
 				Aggregation: view.LastValue(),
 			}
-			customMeasurement := stats.Int64(
-				"testing/value",
-				"Stored value",
+			notReadyPodCountM := stats.Int64(
+				"not_ready_pods",
+				"Number of pods that are not ready",
 				stats.UnitDimensionless)
 			customView := &view.View{
-				Name:        "testing/value",
-				Description: "Test value",
-				Measure:     customMeasurement,
+				Description: "non-knative-revision metric per KnativeRevisionMetrics",
+				Measure:     notReadyPodCountM,
 				Aggregation: view.LastValue(),
 			}
 
@@ -551,23 +554,13 @@ func TestStackDriverExports(t *testing.T) {
 			Record(ctx, actualPodCountM.M(int64(1)))
 
 			r := resource.Resource{
-				Type: "knative_revision",
-				Labels: map[string]string{
-					metricskey.LabelNamespaceName:     "ns2",
-					metricskey.LabelServiceName:       "service2",
-					metricskey.LabelConfigurationName: "config2",
-					metricskey.LabelRevisionName:      "revision2",
-				},
+				Type:   "testing",
+				Labels: batchLabels,
 			}
-			Record(metricskey.WithResource(context.Background(), r), desiredPodCountM.M(int64(2)))
-
-			r = resource.Resource{
-				Type: "custom_resource",
-				Labels: map[string]string{
-					"key": "value",
-				},
-			}
-			Record(metricskey.WithResource(context.Background(), r), customMeasurement.M(int64(3)))
+			RecordBatch(
+				metricskey.WithResource(context.Background(), r),
+				desiredPodCountM.M(int64(2)),
+				notReadyPodCountM.M(int64(3)))
 
 			records := []metricExtract{}
 			for record := range sdFake.published {
@@ -577,6 +570,11 @@ func TestStackDriverExports(t *testing.T) {
 						Labels: ts.Resource.Labels,
 						Value:  ts.Points[0].Value.GetInt64Value(),
 					})
+					if strings.HasPrefix(ts.Metric.Type, "knative.dev/") {
+						if diff := cmp.Diff(ts.Resource.Type, metricskey.ResourceTypeKnativeRevision); diff != "" {
+							t.Errorf("Incorrect resource type for %q: (-want +got): %s", ts.Metric.Type, diff)
+						}
+					}
 				}
 				if len(records) >= 2 {
 					// There's no way to synchronize on the internal timer used