Skip to content

Commit

Permalink
feat: Add workflow job collector
Browse files Browse the repository at this point in the history
  • Loading branch information
marcusramberg committed Oct 18, 2024
1 parent a90c4fc commit 71ec6dd
Show file tree
Hide file tree
Showing 11 changed files with 419 additions and 77 deletions.
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
.direnv
.envrc
.devenv
coverage.out

Expand Down
52 changes: 32 additions & 20 deletions pkg/action/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,19 @@ func handler(cfg *config.Config, db store.Store, logger *slog.Logger, client *gi
))
}

if cfg.Collector.WorkflowJobs {
logger.Debug("WorkflowJob collector registered")

registry.MustRegister(exporter.NewWorkflowJobCollector(
logger,
client,
db,
requestFailures,
requestDuration,
cfg.Target,
))
}

reg := promhttp.HandlerFor(
registry,
promhttp.HandlerOpts{
Expand All @@ -202,7 +215,7 @@ func handler(cfg *config.Config, db store.Store, logger *slog.Logger, client *gi
mux.Route("/", func(root chi.Router) {
root.Handle(cfg.Server.Path, reg)

if cfg.Collector.Workflows {
if cfg.Collector.Workflows || cfg.Collector.WorkflowJobs {
root.HandleFunc(cfg.Webhook.Path, func(w http.ResponseWriter, r *http.Request) {
secret, err := config.Value(cfg.Webhook.Secret)

Expand Down Expand Up @@ -283,31 +296,30 @@ func handler(cfg *config.Config, db store.Store, logger *slog.Logger, client *gi
io.WriteString(w, http.StatusText(http.StatusInternalServerError))
}
case *github.WorkflowJobEvent:
wf_job := event.WorkflowJob
level.Debug(logger).Log(
"msg", "received webhook request",
wf_job := event.GetWorkflowJob()

Check failure on line 299 in pkg/action/server.go

View workflow job for this annotation

GitHub Actions / testing

don't use underscores in Go names; var wf_job should be wfJob
logger.Debug("received webhook request",
"type", "workflow_job",
"owner", event.Repo.Owner.Login,
"repo", event.Repo.Name,
"id", wf_job.ID,
"name", wf_job.Name,
"attempt", wf_job.RunAttempt,
"status", wf_job.Status,
"conclusion", wf_job.Conclusion,
"created_at", wf_job.CreatedAt.Time.Unix(),
"started_at", wf_job.StartedAt.Time.Unix(),
"owner", event.GetRepo().GetOwner().GetLogin(),
"repo", event.GetRepo().GetName(),
"id", wf_job.GetID(),
"name", wf_job.GetName(),
"attempt", wf_job.GetRunAttempt(),
"status", wf_job.GetStatus(),
"conclusion", wf_job.GetConclusion(),
"created_at", wf_job.GetCreatedAt().Time.Unix(),
"started_at", wf_job.GetStartedAt().Time.Unix(),
"completed_at", wf_job.GetCompletedAt().Time.Unix(),
"labels", strings.Join(event.WorkflowJob.Labels, ", "),
"labels", strings.Join(wf_job.Labels, ", "),
)

if err := db.StoreWorkflowJobEvent(event); err != nil {
level.Error(logger).Log(
"msg", "failed to store github event",
logger.Error(
"failed to store github event",
"type", "workflow_job",
"owner", event.Repo.Owner.Login,
"repo", event.Repo.Name,
"name", wf_job.Name,
"id", wf_job.ID,
"owner", event.GetRepo().GetOwner().GetLogin(),
"repo", event.GetRepo().GetName(),
"name", wf_job.GetName(),
"id", wf_job.GetID(),
"error", err,
)

Expand Down
21 changes: 21 additions & 0 deletions pkg/command/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,27 @@ func RootFlags(cfg *config.Config) []cli.Flag {
EnvVars: []string{"GITHUB_EXPORTER_WORKFLOWS_LABELS"},
Destination: &cfg.Target.Workflows.Labels,
},
&cli.BoolFlag{
Name: "collector.workflow_jobs",
Value: false,
Usage: "Enable collector for workflow jobs",
EnvVars: []string{"GITHUB_EXPORTER_COLLECTOR_WORKFLOW_JOBS"},
Destination: &cfg.Collector.WorkflowJobs,
},
&cli.DurationFlag{
Name: "collector.workflow_jobs.window",
Value: 24 * time.Hour,
Usage: "History window for querying workflow jobs",
EnvVars: []string{"GITHUB_EXPORTER_WORKFLOW_JOBS_WINDOW"},
Destination: &cfg.Target.WorkflowJobs.Window,
},
&cli.StringSliceFlag{
Name: "collector.workflow_jobs.labels",
Value: config.JobLabels(),
Usage: "List of labels used for workflow jobs",
EnvVars: []string{"GITHUB_EXPORTER_WORKFLOWS_LABELS"},
Destination: &cfg.Target.WorkflowJobs.Labels,
},
&cli.BoolFlag{
Name: "collector.runners",
Value: false,
Expand Down
61 changes: 42 additions & 19 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,36 +37,44 @@ type Workflows struct {
Labels cli.StringSlice
}

// WorkflowJobs defines the workflow job specific configuration.
type WorkflowJobs struct {
Window time.Duration
Labels cli.StringSlice
}

// Runners defines the runner specific configuration.
type Runners struct {
Labels cli.StringSlice
}

// Target defines the target specific configuration.
type Target struct {
Token string
PrivateKey string
AppID int64
InstallID int64
BaseURL string
Insecure bool
Enterprises cli.StringSlice
Orgs cli.StringSlice
Repos cli.StringSlice
Timeout time.Duration
PerPage int
Workflows Workflows
Runners Runners
Token string
PrivateKey string
AppID int64
InstallID int64
BaseURL string
Insecure bool
Enterprises cli.StringSlice
Orgs cli.StringSlice
Repos cli.StringSlice
Timeout time.Duration
PerPage int
Workflows Workflows
WorkflowJobs WorkflowJobs
Runners Runners
}

// Collector defines the collector specific configuration.
type Collector struct {
Admin bool
Orgs bool
Repos bool
Billing bool
Workflows bool
Runners bool
Admin bool
Orgs bool
Repos bool
Billing bool
Workflows bool
WorkflowJobs bool
Runners bool
}

// Database defines the database specific configuration.
Expand Down Expand Up @@ -104,6 +112,21 @@ func Labels() *cli.StringSlice {
)
}

// Labels defines the default labels used by workflow_job collector.
func JobLabels() *cli.StringSlice {
return cli.NewStringSlice(
"owner",
"repo",
"name",
"title",
"branch",
"sha",
"run_id",
"run_attempt",
"labels",
)
}

// RunnerLabels defines the default labels used by runner collector.
func RunnerLabels() *cli.StringSlice {
return cli.NewStringSlice(
Expand Down
196 changes: 196 additions & 0 deletions pkg/exporter/workflow_job.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
package exporter

import (
"log/slog"
"time"

"github.com/google/go-github/v66/github"
"github.com/prometheus/client_golang/prometheus"
"github.com/promhippie/github_exporter/pkg/config"
"github.com/promhippie/github_exporter/pkg/store"
)

// WorkflowCollector collects metrics about the servers.
type WorkflowJobCollector struct {
client *github.Client
logger *slog.Logger
db store.Store
failures *prometheus.CounterVec
duration *prometheus.HistogramVec
config config.Target

Status *prometheus.Desc
Duration *prometheus.Desc
Creation *prometheus.Desc
Created *prometheus.Desc
Started *prometheus.Desc
}

// NewWorkflowCollector returns a new WorkflowCollector.
func NewWorkflowJobCollector(logger *slog.Logger, client *github.Client, db store.Store, failures *prometheus.CounterVec, duration *prometheus.HistogramVec, cfg config.Target) *WorkflowJobCollector {
if failures != nil {
failures.WithLabelValues("action").Add(0)
}

labels := cfg.Workflows.Labels.Value()
return &WorkflowJobCollector{
client: client,
logger: logger.With("collector", "workflow_job"),
db: db,
failures: failures,
duration: duration,
config: cfg,

Status: prometheus.NewDesc(
"github_workflow_job_status",
"Status of workflow jobs",
labels,
nil,
),
Duration: prometheus.NewDesc(
"github_workflow_job_duration_ms",
"Duration of workflow runs",
labels,
nil,
),
Creation: prometheus.NewDesc(
"github_workflow_job_duration_run_created_minutes",
"Duration since the workflow run creation time in minutes",
labels,
nil,
),
Created: prometheus.NewDesc(
"github_workflow_job_created_timestamp",
"Timestamp when the workflow job have been created",
labels,
nil,
),
Started: prometheus.NewDesc(
"github_workflow_job_started_timestamp",
"Timestamp when the workflow job have been started",
labels,
nil,
),
}
}

// Metrics simply returns the list metric descriptors for generating a documentation.
func (c *WorkflowJobCollector) Metrics() []*prometheus.Desc {
return []*prometheus.Desc{
c.Status,
c.Duration,
c.Creation,
c.Created,
c.Started,
}
}

// Describe sends the super-set of all possible descriptors of metrics collected by this Collector.
func (c *WorkflowJobCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- c.Status
ch <- c.Duration
ch <- c.Creation
ch <- c.Created
ch <- c.Started
}

// Collect is called by the Prometheus registry when collecting metrics.
func (c *WorkflowJobCollector) Collect(ch chan<- prometheus.Metric) {
if err := c.db.PruneWorkflowJobs(
c.config.WorkflowJobs.Window,
); err != nil {
c.logger.Error(
"Failed to prune workflow jobs",
"err", err,
)
}

now := time.Now()
records, err := c.db.GetWorkflowJobs()
c.duration.WithLabelValues("workflow_job").Observe(time.Since(now).Seconds())

if err != nil {
c.logger.Error(
"Failed to fetch workflows",
"err", err,
)

c.failures.WithLabelValues("workflow_job").Inc()
return
}

c.logger.Debug(
"Fetched workflow jobs",
"count", len(records),
"duration", time.Since(now),
)

for _, record := range records {
c.logger.Debug(
"Collecting workflow job",
"owner", record.Owner,
"repo", record.Repo,
"id", record.Identifier,
"run_id", record.RunID,
)

labels := []string{}

for _, label := range c.config.WorkflowJobs.Labels.Value() {
labels = append(
labels,
record.ByLabel(label),
)
}

ch <- prometheus.MustNewConstMetric(
c.Status,
prometheus.GaugeValue,
jobStatusToGauge(record.Status),
labels...,
)

ch <- prometheus.MustNewConstMetric(
c.Duration,
prometheus.GaugeValue,
float64((record.CompletedAt-record.StartedAt)*1000),
labels...,
)

ch <- prometheus.MustNewConstMetric(
c.Creation,
prometheus.GaugeValue,
time.Since(time.Unix(record.StartedAt, 0)).Minutes(),
labels...,
)

ch <- prometheus.MustNewConstMetric(
c.Created,
prometheus.GaugeValue,
float64(record.CreatedAt),
labels...,
)

ch <- prometheus.MustNewConstMetric(
c.Started,
prometheus.GaugeValue,
float64(record.StartedAt),
labels...,
)
}
}

func jobStatusToGauge(conclusion string) float64 {
switch conclusion {
case "queued":
return 1.0
case "waiting":
return 2.0
case "in_progress":
return 3.0
case "completed":
return 4.0
}

return 0.0
}
Loading

0 comments on commit 71ec6dd

Please sign in to comment.