Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
334 changes: 334 additions & 0 deletions test/metrics_otel_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,334 @@
//go:build e2e

// Copyright 2026 The Tekton Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package test

import (
"context"
"fmt"
"strings"
"testing"
"time"

"github.com/openshift-pipelines/pipelines-as-code/pkg/params/triggertype"
tgitea "github.com/openshift-pipelines/pipelines-as-code/test/pkg/gitea"

dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/expfmt"
"github.com/prometheus/common/model"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
Comment thread
khrm marked this conversation as resolved.

const (
pacNamespace = "pipelines-as-code"
pacMetricsPort = "9090"
pacControllerSelector = "app.kubernetes.io/name=controller,app.kubernetes.io/part-of=pipelines-as-code"
pacWatcherSelector = "app.kubernetes.io/name=watcher,app.kubernetes.io/part-of=pipelines-as-code"
)

// pacKubeClient builds a kubernetes client from the default kubeconfig.
func pacKubeClient(t *testing.T) kubernetes.Interface {
t.Helper()
rules := clientcmd.NewDefaultClientConfigLoadingRules()
cfg, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, &clientcmd.ConfigOverrides{}).ClientConfig()
if err != nil {
t.Fatalf("Failed to build kubeconfig: %v", err)
}
return kubernetes.NewForConfigOrDie(cfg)
}

// scrapePACPodMetrics scrapes /metrics from the first Running/Ready pod
// matching labelSelector via the Kubernetes API proxy. Returns an error
// so callers can retry on transient failures without aborting the test.
func scrapePACPodMetrics(ctx context.Context, kubeClient kubernetes.Interface, labelSelector string) (map[string]*dto.MetricFamily, error) {
pods, err := kubeClient.CoreV1().Pods(pacNamespace).List(ctx, metav1.ListOptions{
LabelSelector: labelSelector,
})
if err != nil {
return nil, err
}

var podName string
for _, pod := range pods.Items {
if pod.Status.Phase != corev1.PodRunning {
continue
}
podReady := len(pod.Status.ContainerStatuses) > 0
for _, cs := range pod.Status.ContainerStatuses {
if !cs.Ready {
podReady = false
break
}
}
if podReady {
podName = pod.Name
break
}
}
if podName == "" {
return nil, fmt.Errorf("no Running/Ready PAC pod found for selector %q in namespace %s", labelSelector, pacNamespace)
}

result := kubeClient.CoreV1().RESTClient().Get().
Resource("pods").
Name(podName + ":" + pacMetricsPort).
Namespace(pacNamespace).
SubResource("proxy").
Suffix("metrics").
Do(ctx)

body, err := result.Raw()
if err != nil {
return nil, err
}

parser := expfmt.NewTextParser(model.LegacyValidation)
families, err := parser.TextToMetricFamilies(strings.NewReader(string(body)))
if err != nil {
return nil, err
}
return families, nil
}

// waitForControllerMetrics polls the PAC controller pod until the named
// metric appears. Transient errors are logged and retried until timeout.
func waitForControllerMetrics(ctx context.Context, t *testing.T, kubeClient kubernetes.Interface, metricName string, timeout time.Duration) map[string]*dto.MetricFamily {
t.Helper()
return waitForPACPodMetric(ctx, t, kubeClient, pacControllerSelector, metricName, timeout)
}

// waitForWatcherMetrics polls the PAC watcher pod until the named metric
// appears. Transient errors are logged and retried until timeout.
func waitForWatcherMetrics(ctx context.Context, t *testing.T, kubeClient kubernetes.Interface, metricName string, timeout time.Duration) map[string]*dto.MetricFamily {
t.Helper()
return waitForPACPodMetric(ctx, t, kubeClient, pacWatcherSelector, metricName, timeout)
}

// waitForPACPodMetric is the shared polling implementation used by
// waitForControllerMetrics and waitForWatcherMetrics.
func waitForPACPodMetric(ctx context.Context, t *testing.T, kubeClient kubernetes.Interface, labelSelector, metricName string, timeout time.Duration) map[string]*dto.MetricFamily {
t.Helper()
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
for {
families, err := scrapePACPodMetrics(ctx, kubeClient, labelSelector)
if err == nil {
if _, ok := families[metricName]; ok {
return families
}
} else {
t.Logf("Retrying metrics scrape (%s): %v", labelSelector, err)
}
select {
case <-ctx.Done():
t.Fatalf("Timed out waiting for metric %q (selector=%s, waited %v): %v", metricName, labelSelector, timeout, ctx.Err())
return nil
case <-time.After(5 * time.Second):
}
}
}

// counterValue returns the sum of all counter values for the given metric name.
func counterValue(families map[string]*dto.MetricFamily, name string) float64 {
fam, ok := families[name]
if !ok {
return 0
}
var total float64
for _, m := range fam.GetMetric() {
if c := m.GetCounter(); c != nil {
total += c.GetValue()
}
}
return total
}

// TestOthersOTelMetricsController verifies that the PAC controller pod exposes the
// expected OTel metric families after the OC→OTel migration (PR #2567):
// - http_client_* and kn_k8s_client_* (knative k8s client OTel instrumentation)
// - go_* runtime metrics
// - PAC application metrics logged (appear only after first PipelineRun)
// - Old OpenCensus metric names absent
func TestOthersOTelMetricsController(t *testing.T) {
ctx := context.Background()
kubeClient := pacKubeClient(t)

t.Log("Waiting for PAC controller metrics (http_client_request_duration_seconds)")
families := waitForControllerMetrics(ctx, t, kubeClient, "http_client_request_duration_seconds", 2*time.Minute)
t.Logf("Scraped %d metric families from PAC controller", len(families))

tests := []struct {
name string
prefix string
errMsg string
}{
{
name: "http_client_prefix",
prefix: "http_client_",
errMsg: "Expected at least one http_client_* metric from knative k8s client instrumentation, found none",
},
{
name: "kn_k8s_client_prefix",
prefix: "kn_k8s_client_",
errMsg: "Expected at least one kn_k8s_client_* metric from knative k8s client instrumentation, found none",
},
{
name: "go_runtime_prefix",
prefix: "go_",
errMsg: "Expected standard go_* runtime metrics, found none",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for name := range families {
if strings.HasPrefix(name, tt.prefix) {
return
}
}
t.Error(tt.errMsg)
})
}

// Old OC metric names must be absent.
// TODO: Remove in a future release once no OC-based release is supported.
for name := range families {
for _, prefix := range []string{"pipelines_as_code/", "tekton_pipelines_as_code_"} {
if strings.HasPrefix(name, prefix) {
t.Errorf("Old OC metric %q still present; expected removal after OTel migration", name)
}
}
}
}

// TestOthersOTelMetricsWatcher verifies that the PAC watcher pod exposes the
// expected OTel metric families after the OC→OTel migration (PR #2567):
// - kn_workqueue_* (knative reconciler workqueue)
// - http_client_* and kn_k8s_client_* (knative k8s client OTel instrumentation)
// - go_* runtime metrics
func TestOthersOTelMetricsWatcher(t *testing.T) {
ctx := context.Background()
kubeClient := pacKubeClient(t)

t.Log("Waiting for PAC watcher metrics (go_goroutines)")
families := waitForWatcherMetrics(ctx, t, kubeClient, "go_goroutines", 2*time.Minute)
t.Logf("Scraped %d metric families from PAC watcher", len(families))

tests := []struct {
name string
prefix string
errMsg string
}{
{
name: "kn_workqueue_prefix",
prefix: "kn_workqueue_",
errMsg: "Expected at least one kn_workqueue_* metric on the PAC watcher, found none",
},
{
name: "http_client_prefix",
prefix: "http_client_",
errMsg: "Expected at least one http_client_* metric on the PAC watcher, found none",
},
{
name: "kn_k8s_client_prefix",
prefix: "kn_k8s_client_",
errMsg: "Expected at least one kn_k8s_client_* metric on the PAC watcher, found none",
},
{
name: "go_runtime_prefix",
prefix: "go_",
errMsg: "Expected standard go_* runtime metrics on PAC watcher, found none",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
for name := range families {
if strings.HasPrefix(name, tt.prefix) {
return
}
}
t.Error(tt.errMsg)
})
}
}

// TestOthersOTelMetricsAfterPACRun triggers a real PAC PipelineRun via Gitea
// and asserts that pipelines_as_code_pipelinerun_count increments by
// exactly 1. The test skips automatically if Gitea is not configured
// (TEST_GITEA_API_URL and related env vars are unset).
func TestOthersOTelMetricsAfterPACRun(t *testing.T) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This e2e test is failing in the CI === RUN TestOthersOTelMetricsAfterPACRun {"level":"info","ts":1782788949.960166,"caller":"gitea/gitea.go:290","msg":"gitea: initialized API client with provided credentials user=pac providerURL=http://localhost:3000"} {"level":"info","ts":1782788949.964509,"caller":"cctx/ctx.go:19","msg":"Found pipelines-as-code installation in namespace pipelines-as-code"} {"level":"info","ts":1782788949.9646285,"caller":"cctx/ctx.go:22","msg":"Pipelines as Code Controller: &{Name:default Configmap:pipelines-as-code Secret:pipelines-as-code-secret GlobalRepository:pipelines-as-code}"} {"level":"info","ts":1782788949.9674673,"caller":"repository/create.go:17","msg":"Namespace pac-e2e-test-2w5pv created"} {"level":"info","ts":1782788949.9676106,"caller":"gitea/scm.go:151","msg":"Creating gitea repository pac-e2e-test-2w5pv for user pac"} {"level":"info","ts":1782788950.389976,"caller":"gitea/scm.go:163","msg":"Creating webhook to smee url on gitea repository pac-e2e-test-2w5pv"} {"level":"info","ts":1782788950.909148,"caller":"repository/create.go:26","msg":"PipelinesAsCode Repository pac-e2e-test-2w5pv has been created in namespace pac-e2e-test-2w5pv"} {"level":"info","ts":1782788951.527173,"caller":"scm/scm.go:48","msg":"Pushed files to repo https://gitea.paac-127-0-0-1.nip.io/pac/pac-e2e-test-2w5pv branch pac-e2e-test-2w5pv"} {"level":"info","ts":1782788956.5320754,"caller":"gitea/test.go:254","msg":"Creating PullRequest"} {"level":"info","ts":1782788957.0262525,"caller":"gitea/test.go:269","msg":"PullRequest https://gitea.paac-127-0-0-1.nip.io/pac/pac-e2e-test-2w5pv/pulls/1 has been created"} {"level":"info","ts":1782788957.17538,"caller":"gitea/test.go:477","msg":"Number of gitea status on PR: 0/1"} {"level":"info","ts":1782788962.3255165,"caller":"gitea/test.go:474","msg":"Status on SHA: pac-e2e-test-2w5pv is success from Pipelines as Code CI / always-good-pipelinerun"} {"level":"info","ts":1782788962.325611,"caller":"gitea/test.go:477","msg":"Number of gitea status on PR: 1/1"} {"level":"info","ts":1782788962.3256638,"caller":"gitea/test.go:542","msg":"Looking for regexp \".*Pipelines as Code CI.*has.*successfully.*validated your commit.*\" in PR comments"} {"level":"info","ts":1782788962.4651678,"caller":"gitea/test.go:548","msg":"Found regexp in comment: Pipelines as Code CI/always-good-pipelinerun-z9rnx has successfully validated your commit.\n
    \n
  • Namespace: pac-e2e-test-2w5pv
  • \n
  • PipelineRun: always-good-pipelinerun-z9rnx
  • \n
\n
\n

Task Statuses:

\n\n\n \n\n\n\n
StatusDurationName
Succeeded3 seconds\n\n[The Task name is Task](http://dashboard.paac-127-0-0-1.nip.io/#/namespaces/pac-e2e-test-2w5pv/pipelineruns/always-good-pipelinerun-z9rnx?pipelineTask=task)\n\n
"} metrics_otel_test.go:314: Timed out waiting for metric "pipelines_as_code_pipelinerun_count_total" (selector=app.kubernetes.io/name=controller,app.kubernetes.io/part-of=pipelines-as-code, waited 2m0s): context deadline exceeded setup.go:87: Deleted gitea repo pac/pac-e2e-test-2w5pv --- FAIL: TestOthersOTelMetricsAfterPACRun (132.88s) FAIL FAIL github.com/openshift-pipelines/pipelines-as-code/test 1007.891s

ctx := context.Background()
kubeClient := pacKubeClient(t)

// Baseline before the PAC run to compute an exact delta.
baseline, err := scrapePACPodMetrics(ctx, kubeClient, pacControllerSelector)
if err != nil {
t.Skipf("PAC controller metrics not reachable, skipping: %v", err)
}
baseCount := counterValue(baseline, "pipelines_as_code_pipelinerun_count")

// TestPR sets up Gitea, creates a repo, pushes .tekton/pr.yaml, creates a
// PR, waits for PAC to process it. It calls t.Skip if Gitea is not
// configured via TEST_GITEA_API_URL / TEST_GITEA_PASSWORD env vars.
topts := &tgitea.TestOpts{
Regexp: successRegexp,
TargetEvent: triggertype.PullRequest.String(),
YAMLFiles: map[string]string{".tekton/pr.yaml": "testdata/always-good-pipelinerun.yaml"},
CheckForStatus: "success",
}
_, f := tgitea.TestPR(t, topts)
defer f()

// Assert exact delta == 1 (one PipelineRun processed by PAC).
after := waitForControllerMetrics(ctx, t, kubeClient, "pipelines_as_code_pipelinerun_count", 2*time.Minute)
delta := counterValue(after, "pipelines_as_code_pipelinerun_count") - baseCount
if delta != 1 {
t.Errorf("pipelinerun_count delta = %v, want exactly 1", delta)
}
t.Logf("pipelines_as_code_pipelinerun_count delta: %v", delta)

// Assert all PAC application metrics are present after a real run.
appTests := []struct {
name string
metricName string
errMsg string
}{
{
name: "pipelinerun_count",
metricName: "pipelines_as_code_pipelinerun_count",
errMsg: "pipelines_as_code_pipelinerun_count not found after PAC run",
},
{
name: "pipelinerun_duration_seconds_sum",
metricName: "pipelines_as_code_pipelinerun_duration_seconds_sum",
errMsg: "pipelines_as_code_pipelinerun_duration_seconds_sum not found after PAC run",
},
{
name: "git_provider_api_request_count",
metricName: "pipelines_as_code_git_provider_api_request_count",
errMsg: "pipelines_as_code_git_provider_api_request_count not found after PAC run",
},
}
for _, tt := range appTests {
t.Run(tt.name, func(t *testing.T) {
if _, ok := after[tt.metricName]; !ok {
t.Error(tt.errMsg)
}
})
}
}
Loading