Skip to content
Open
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions .changeset/short-steps-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'grafana-github-datasource': minor
---

Saved **Workflow Runs** queries with a blank **Workflow** field previously failed. They now return all runs across the repository that match the query's filters. Use the new **Workflow Job Steps** query to analyze individual GitHub Actions job step durations.
7 changes: 7 additions & 0 deletions docs/sources/configure.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@ The following scopes are required for classic personal access tokens:
| `read:project` | Read project data. |
| `repo` | Full control of private repositories. Required only if you need to query private repositories. |

For fine-grained personal access tokens, grant the following repository permission to use the **Workflow Runs** and **Workflow Job Steps** query types:

| Permission | Access level |
| ----------- | ------------ |
| **Actions** | Read-only |

### GitHub App

GitHub App authentication provides better security and fine-grained access to resources compared to personal access tokens.
Expand Down Expand Up @@ -157,6 +163,7 @@ The following repository permissions are required:
| **Packages** | Read-only |
| **Repository security advisories** | Read-only |
| **Projects** | Read-only |
| **Actions** (for **Workflow Runs** and **Workflow Job Steps**) | Read-only |

### Code scanning permissions

Expand Down
17 changes: 13 additions & 4 deletions docs/sources/query-editor.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ Select a query type from the **Query Type** drop-down in the query editor:
- [**Vulnerabilities**](#vulnerabilities): Query security vulnerabilities detected in a repository.
- [**Webhook deliveries**](#webhook-deliveries): List deliveries of an organization or repository webhook, including the response status code.
- [**Workflows**](#workflows): List GitHub Actions workflows defined in a repository.
- [**Workflow runs**](#workflow-runs): List runs for a specific workflow, including status, conclusion, and timing information.
- [**Workflow runs**](#workflow-runs): List runs across a repository or filter by workflow, including status, conclusion, and timing information.
- [**Workflow job steps**](#workflow-job-steps): List individual job steps and their durations across workflow runs.
- [**Workflow usage**](#workflow-usage): Retrieve usage statistics for a workflow, such as run counts and durations.

### Code scanning
Expand Down Expand Up @@ -1045,20 +1046,22 @@ Show all workflows created within the `grafana/grafana` repository within the cu

### Workflow runs

List runs for a specific workflow, including status, conclusion, and timing information.
List runs across a repository or filter by a specific workflow. The Grafana time range selects runs by creation time. GitHub limits time-filtered results to 1,000 runs; use a narrower range for busy repositories.

#### Query options

| Name | Description | Required |
|------|-------------|----------|
| Owner | GitHub user or organization that owns the repository | Yes |
| Repository | Name of the repository | Yes |
| Workflow | The workflow ID or file name. Use `id` or the filename from `path` from [Workflows](#workflows) queries. | Yes |
| Workflow | Leave empty for all workflows, or enter a workflow ID or file name from [Workflows](#workflows). | No |
| Branch | The head branch to filter on | No |

##### Sample queries

Show all completed runs for the `Levitate` workflow in the `grafana/grafana` repository:
To compare run outcomes across a repository, set **Owner** and **Repository**, and leave **Workflow** and **Branch** empty. In the panel, use **Group by** on `conclusion` and **Count** on `id`. To compare workflows side by side, also group by `workflow_id`.

Show runs for the `Levitate` workflow in the `grafana/grafana` repository:

- Owner: `grafana`
- Repository: `grafana`
Expand Down Expand Up @@ -1090,6 +1093,12 @@ Show workflow runs for a specific branch (useful for monitoring release branch C
| workflow_id | Unique identifier for the workflow definition |
| run_number | The run number for this workflow run in the repository |

### Workflow job steps

List individual steps for the latest attempt of each matching workflow run. Use the same owner, repository, optional workflow and branch filters, and run creation time range as [Workflow runs](#workflow-runs). This detail query fetches jobs separately for each run, so it inspects at most the 50 most recent matching runs and reports a warning if the result is truncated. Use **Workflow Runs** for repository-wide run counts.

The table contains one row per step and includes workflow, run and attempt, job and link, step number and name, status, conclusion, start and completion times, and `duration_seconds`. Skipped steps and steps without valid start and completion times have no duration. For a bottleneck panel, group by `workflow_name`, `job_name`, and `step_name`, then calculate the mean or maximum duration.

### Workflow usage

Retrieve usage statistics for a workflow, such as run counts and durations.
Expand Down
111 changes: 88 additions & 23 deletions pkg/github/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"

"github.com/bradleyfalzon/ghinstallation/v2"
Expand All @@ -23,9 +25,11 @@ import (

// Client is a wrapper of GitHub clients that can access the GraphQL and rest API.
type Client struct {
restClient *googlegithub.Client
graphqlClient *githubv4.Client
authType models.AuthType
restClient *googlegithub.Client
graphqlClient *githubv4.Client
authType models.AuthType
workflowJobsMu sync.Mutex
workflowJobs map[workflowJobsKey]workflowJobsPage
}

const (
Expand Down Expand Up @@ -407,6 +411,61 @@ func (client *Client) getWorkflowUsage(ctx context.Context, owner, repo string,
return client.restClient.Actions.GetWorkflowUsageByFileName(ctx, owner, repo, workflow)
}

type workflowJobsKey struct {
owner, repo string
run, attempt int64
page, perPage int
}

type workflowJobsPage struct {
jobs []*googlegithub.WorkflowJob
next int
}

// ListWorkflowJobs returns a page for the observed run attempt. Only completed,
// explicitly identified attempts are cached, per authenticated data source client.
func (client *Client) ListWorkflowJobs(ctx context.Context, owner, repo string, run *googlegithub.WorkflowRun, opts googlegithub.ListOptions) ([]*googlegithub.WorkflowJob, int, error) {
id, attempt := run.GetID(), int64(run.GetRunAttempt())
key := workflowJobsKey{strings.ToLower(owner), strings.ToLower(repo), id, attempt, opts.Page, opts.PerPage}
cacheable := attempt > 0 && run.GetStatus() == runStatusCompleted
if cacheable {
client.workflowJobsMu.Lock()
cached, found := client.workflowJobs[key]
client.workflowJobsMu.Unlock()
if found {
return cached.jobs, cached.next, nil
}
}
var jobs *googlegithub.Jobs
var response *googlegithub.Response
var err error
if attempt > 0 {
jobs, response, err = client.restClient.Actions.ListWorkflowJobsAttempt(ctx, owner, repo, id, attempt, &opts)
} else {
jobs, response, err = client.restClient.Actions.ListWorkflowJobs(ctx, owner, repo, id, &googlegithub.ListWorkflowJobsOptions{Filter: "latest", ListOptions: opts})
}
if err != nil {
return nil, 0, addErrorSourceToError(err, response)
}
if cacheable {
client.workflowJobsMu.Lock()
if client.workflowJobs == nil {
client.workflowJobs = make(map[workflowJobsKey]workflowJobsPage)
}
// Keep memory bounded even when many dashboards query disjoint ranges.
const maxCachedJobPages = 512
if _, exists := client.workflowJobs[key]; !exists && len(client.workflowJobs) >= maxCachedJobPages {
for old := range client.workflowJobs {
delete(client.workflowJobs, old)
break
}
}
client.workflowJobs[key] = workflowJobsPage{jobs.Jobs, response.NextPage}
client.workflowJobsMu.Unlock()
}
return jobs.Jobs, response.NextPage, nil
}

func (client *Client) GetWorkflowRuns(ctx context.Context, owner, repo, workflow string, branch string, timeRange backend.TimeRange) ([]*googlegithub.WorkflowRun, error) {
workflowRuns := []*googlegithub.WorkflowRun{}

Expand All @@ -426,9 +485,17 @@ func (client *Client) GetWorkflowRuns(ctx context.Context, owner, repo, workflow
}

func (client *Client) getWorkflowRuns(ctx context.Context, owner, repo, workflow string, branch string, timeRange backend.TimeRange, page int) ([]*googlegithub.WorkflowRun, int, error) {
workflowID, _ := strconv.ParseInt(workflow, 10, 64)
runs, response, err := client.ListWorkflowRunsPage(ctx, owner, repo, workflow, branch, timeRange, googlegithub.ListOptions{Page: page, PerPage: 100})
if err != nil {
return nil, 0, err
}
return runs.WorkflowRuns, response.NextPage, nil
}

workflowRuns := []*googlegithub.WorkflowRun{}
// ListWorkflowRunsPage fetches just the requested page, preserving the API's total and next page.
func (client *Client) ListWorkflowRunsPage(ctx context.Context, owner, repo, workflow, branch string, timeRange backend.TimeRange, page googlegithub.ListOptions) (*googlegithub.WorkflowRuns, *googlegithub.Response, error) {
workflow = strings.TrimSpace(workflow)
workflowID, _ := strconv.ParseInt(workflow, 10, 64)

format := time.RFC3339
created := fmt.Sprintf("%s..%s", timeRange.From.Format(format), timeRange.To.Format(format))
Expand All @@ -439,29 +506,27 @@ func (client *Client) getWorkflowRuns(ctx context.Context, owner, repo, workflow
err error
)

if workflowID > 0 {
runs, response, err = client.restClient.Actions.ListWorkflowRunsByID(ctx, owner, repo, workflowID, &googlegithub.ListWorkflowRunsOptions{
Created: created,
ListOptions: googlegithub.ListOptions{Page: page, PerPage: 100},
Branch: branch,
})
} else {
runs, response, err = client.restClient.Actions.ListWorkflowRunsByFileName(ctx, owner, repo, workflow, &googlegithub.ListWorkflowRunsOptions{
Created: created,
ListOptions: googlegithub.ListOptions{Page: page, PerPage: 100},
Branch: branch,
})
opts := &googlegithub.ListWorkflowRunsOptions{
Created: created,
ListOptions: page,
Branch: branch,
}
switch {
case workflow == "":
runs, response, err = client.restClient.Actions.ListRepositoryWorkflowRuns(ctx, owner, repo, opts)
case workflowID > 0:
runs, response, err = client.restClient.Actions.ListWorkflowRunsByID(ctx, owner, repo, workflowID, opts)
default:
runs, response, err = client.restClient.Actions.ListWorkflowRunsByFileName(ctx, owner, repo, workflow, opts)
}

if err != nil {
// If the workflow is not found, return a specific error.
if response != nil && response.StatusCode == http.StatusNotFound {
return nil, 0, backend.DownstreamError(errWorkflowNotFound)
if workflow != "" && response != nil && response.StatusCode == http.StatusNotFound {
return nil, response, backend.DownstreamError(errWorkflowNotFound)
}
return nil, 0, addErrorSourceToError(fmt.Errorf("fetching workflow runs: %w", err), response)
return nil, response, addErrorSourceToError(err, response)
}

workflowRuns = append(workflowRuns, runs.WorkflowRuns...)

return workflowRuns, response.NextPage, nil
return runs, response, nil
}
115 changes: 115 additions & 0 deletions pkg/github/client/workflow_runs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package githubclient

import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"

googlegithub "github.com/google/go-github/v84/github"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestListWorkflowJobsCachesCompletedAttempts(t *testing.T) {
calls := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
assert.Equal(t, "100", r.URL.Query().Get("per_page"))
switch r.URL.Path {
case "/api/v3/repos/acme/widget/actions/runs/11/attempts/1/jobs":
w.Header().Set("Link", fmt.Sprintf("<http://%s%s?page=2>; rel=\"next\"", r.Host, r.URL.Path))
fmt.Fprint(w, `{"jobs":[{"id":20,"run_attempt":1}]}`)
case "/api/v3/repos/acme/widget/actions/runs/11/attempts/2/jobs":
fmt.Fprint(w, `{"jobs":[{"id":21,"run_attempt":2}]}`)
case "/api/v3/repos/acme/widget/actions/runs/11/jobs":
assert.Equal(t, "latest", r.URL.Query().Get("filter"))
fmt.Fprint(w, `{"jobs":[{"id":21,"run_attempt":2}]}`)
default:
t.Errorf("unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
}))
defer server.Close()
rest, err := googlegithub.NewClient(server.Client()).WithEnterpriseURLs(server.URL, server.URL)
require.NoError(t, err)
client := &Client{restClient: rest}
opts := googlegithub.ListOptions{Page: 1, PerPage: 100}
run := &googlegithub.WorkflowRun{ID: googlegithub.Ptr(int64(11)), RunAttempt: googlegithub.Ptr(1), Status: googlegithub.Ptr("completed")}
for range 2 {
jobs, next, err := client.ListWorkflowJobs(t.Context(), "acme", "widget", run, opts)
require.NoError(t, err)
require.Equal(t, 2, next)
require.Len(t, jobs, 1)
require.Equal(t, int64(20), jobs[0].GetID())
}
require.Equal(t, 1, calls, "completed attempt should be served from cache on refresh")

run.RunAttempt = googlegithub.Ptr(2)
run.Status = googlegithub.Ptr("in_progress")
for range 2 {
jobs, next, err := client.ListWorkflowJobs(t.Context(), "acme", "widget", run, opts)
require.NoError(t, err)
require.Zero(t, next)
require.Len(t, jobs, 1)
require.Equal(t, int64(21), jobs[0].GetID())
}
require.Equal(t, 3, calls, "new and in-progress attempts must bypass old cached results")

run.RunAttempt = nil
run.Status = googlegithub.Ptr("completed")
for range 2 {
_, _, err := client.ListWorkflowJobs(t.Context(), "acme", "widget", run, opts)
require.NoError(t, err)
}
require.Equal(t, 5, calls, "the mutable latest endpoint must not be cached")
}

func TestGetWorkflowRunsEndpoints(t *testing.T) {
const base = "/api/v3/repos/acme/widget/actions/"
for _, tc := range []struct {
name, workflow, path string
}{
{"all workflows", "", base + "runs"},
{"blank workflow", " ", base + "runs"},
{"by id", "42", base + "workflows/42/runs"},
{"by filename", "ci.yml", base + "workflows/ci.yml/runs"},
} {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != tc.path {
t.Errorf("request path = %q, want %q", r.URL.Path, tc.path)
w.WriteHeader(http.StatusNotFound)
return
}
params := r.URL.Query()
assert.Equal(t, "main", params.Get("branch"))
assert.Equal(t, "100", params.Get("per_page"))
assert.Equal(t, "2026-11-16T00:00:00Z..2026-11-17T00:00:00Z", params.Get("created"))
w.Header().Set("Content-Type", "application/json")
switch params.Get("page") {
case "1":
w.Header().Set("Link", fmt.Sprintf("<http://%s%s?page=2>; rel=\"next\"", r.Host, r.URL.Path))
fmt.Fprint(w, `{"total_count":2,"workflow_runs":[{"id":11,"workflow_id":42}]}`)
case "2":
fmt.Fprint(w, `{"total_count":2,"workflow_runs":[{"id":12,"workflow_id":43}]}`)
default:
t.Errorf("unexpected page %q", params.Get("page"))
w.WriteHeader(http.StatusBadRequest)
}
}))
defer server.Close()
rest, err := googlegithub.NewClient(server.Client()).WithEnterpriseURLs(server.URL, server.URL)
require.NoError(t, err)
client := &Client{restClient: rest}
from := time.Date(2026, 11, 16, 0, 0, 0, 0, time.UTC)
runs, err := client.GetWorkflowRuns(t.Context(), "acme", "widget", tc.workflow, "main", backend.TimeRange{From: from, To: from.Add(24 * time.Hour)})
require.NoError(t, err)
require.Len(t, runs, 2)
assert.Equal(t, int64(11), runs[0].GetID())
assert.Equal(t, int64(43), runs[1].GetWorkflowID())
})
}
}
1 change: 1 addition & 0 deletions pkg/github/codescanning_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type mockAlertPage struct {
}

type mockClient struct {
models.Client
mockAlerts []*googlegithub.Alert
mockResponse *googlegithub.Response
// pages, when set, makes successive ListAlertsFor* calls return successive
Expand Down
1 change: 1 addition & 0 deletions pkg/github/commit_files_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type prFilePage struct {

// commitFilesMockClient satisfies models.Client for commit file tests
type commitFilesMockClient struct {
models.Client
commitFiles []*googlegithub.CommitFile
prFilePages []prFilePage
prPageIdx int
Expand Down
1 change: 1 addition & 0 deletions pkg/github/commits_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
// Query populates QueryListCommitsInRange with a fixed set of commits; GetCommitFiles
// returns files keyed by commit SHA. All other methods panic if called unexpectedly.
type commitsWithFilesMockClient struct {
models.Client
commits []Commit
filesBySHA map[string][]*googlegithub.CommitFile
}
Expand Down
7 changes: 7 additions & 0 deletions pkg/github/datasource.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,13 @@ func (d *Datasource) HandleWorkflowRunsQuery(ctx context.Context, query *models.
return GetWorkflowRuns(ctx, d.client, opt, req.TimeRange)
}

// HandleWorkflowJobStepsQuery lists job steps and their durations for a repository.
func (d *Datasource) HandleWorkflowJobStepsQuery(ctx context.Context, query *models.WorkflowRunsQuery, req backend.DataQuery) (dfutil.Framer, error) {
return GetWorkflowJobSteps(ctx, d.client, models.WorkflowRunsOptions{
Owner: query.Owner, Repository: query.Repository, Workflow: query.Options.Workflow, Branch: query.Options.Branch,
}, req.TimeRange)
}

// HandleDeploymentsQuery is the query handler for listing GitHub Deployments
func (d *Datasource) HandleDeploymentsQuery(ctx context.Context, query *models.DeploymentsQuery, req backend.DataQuery) (dfutil.Framer, error) {
opt := models.ListDeploymentsOptions{
Expand Down
1 change: 1 addition & 0 deletions pkg/github/deployments_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
)

type mockDeploymentsClient struct {
models.Client
mockDeployments []*googlegithub.Deployment
mockResponse *googlegithub.Response
expectedOwner string
Expand Down
1 change: 1 addition & 0 deletions pkg/github/query_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ func GetQueryHandlers(s *QueryHandler) *datasource.QueryTypeMux {
register(models.QueryTypeWorkflows, s.HandleWorkflows)
register(models.QueryTypeWorkflowUsage, s.HandleWorkflowUsage)
register(models.QueryTypeWorkflowRuns, s.HandleWorkflowRuns)
register(models.QueryTypeWorkflowJobSteps, s.HandleWorkflowJobSteps)
register(models.QueryTypeCodeScanning, s.HandleCodeScanning)
register(models.QueryTypeDeployments, s.HandleDeployments)
register(models.QueryTypeOrganizations, s.HandleOrganizations)
Expand Down
Loading