Skip to content

chore: add prometheus monitoring of workspace traffic generation #7583

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
May 26, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
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
Next Next commit
add prometheus metrics endpoint to workspacetraffic command
  • Loading branch information
johnstcn committed May 17, 2023
commit f62cf1663c70043ece072d026bc51d69070eb46c
53 changes: 38 additions & 15 deletions cli/scaletest.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@ import (
"time"

"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
"go.opentelemetry.io/otel/trace"
"golang.org/x/xerrors"

"cdr.dev/slog"
"cdr.dev/slog/sloggers/sloghuman"

"github.com/coder/coder/cli/clibase"
"github.com/coder/coder/cli/cliui"
"github.com/coder/coder/coderd/httpapi"
Expand Down Expand Up @@ -896,13 +900,14 @@ func (r *RootCmd) scaletestCreateWorkspaces() *clibase.Cmd {

func (r *RootCmd) scaletestWorkspaceTraffic() *clibase.Cmd {
var (
tickInterval time.Duration
bytesPerTick int64
client = &codersdk.Client{}
tracingFlags = &scaletestTracingFlags{}
strategy = &scaletestStrategyFlags{}
cleanupStrategy = &scaletestStrategyFlags{cleanup: true}
output = &scaletestOutputFlags{}
tickInterval time.Duration
bytesPerTick int64
prometheusAddress string
client = &codersdk.Client{}
tracingFlags = &scaletestTracingFlags{}
strategy = &scaletestStrategyFlags{}
cleanupStrategy = &scaletestStrategyFlags{cleanup: true}
output = &scaletestOutputFlags{}
)

cmd := &clibase.Cmd{
Expand All @@ -913,6 +918,12 @@ func (r *RootCmd) scaletestWorkspaceTraffic() *clibase.Cmd {
),
Handler: func(inv *clibase.Invocation) error {
ctx := inv.Context()
reg := prometheus.NewRegistry()
metrics := workspacetraffic.NewMetrics(reg)

logger := slog.Make(sloghuman.Sink(io.Discard))
prometheusSrvClose := ServeHandler(ctx, logger, prometheusMetricsHandler(), prometheusAddress, "prometheus")
defer prometheusSrvClose()
Copy link
Member

Choose a reason for hiding this comment

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

I'm wondering if we need to add some graceful period before closing to make sure that all relevant metrics are scraped before the tool goes down.

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah, this would be heavily dependent on the prometheus scrape interval. Simplest is probably to expose it as a parameter to be set by the test operatorl.


// Bypass rate limiting
client.HTTPClient = &http.Client{
Expand Down Expand Up @@ -955,16 +966,18 @@ func (r *RootCmd) scaletestWorkspaceTraffic() *clibase.Cmd {
th := harness.NewTestHarness(strategy.toStrategy(), cleanupStrategy.toStrategy())
for idx, ws := range workspaces {
var (
agentID uuid.UUID
name = "workspace-traffic"
id = strconv.Itoa(idx)
agentID uuid.UUID
agentName string
Copy link
Member

Choose a reason for hiding this comment

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

I didn't go through the whole PR, but why is it required to specify the agent name? isn't it always "main"?

Copy link
Member Author

Choose a reason for hiding this comment

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

My understanding is that the agent name maps directly to what's specified in the workspace Terraform, is this not the case?

name = "workspace-traffic"
id = strconv.Itoa(idx)
)

for _, res := range ws.LatestBuild.Resources {
if len(res.Agents) == 0 {
continue
}
agentID = res.Agents[0].ID
agentName = res.Agents[0].Name
}

if agentID == uuid.Nil {
Expand All @@ -974,16 +987,19 @@ func (r *RootCmd) scaletestWorkspaceTraffic() *clibase.Cmd {

// Setup our workspace agent connection.
config := workspacetraffic.Config{
AgentID: agentID,
BytesPerTick: bytesPerTick,
Duration: strategy.timeout,
TickInterval: tickInterval,
AgentID: agentID,
AgentName: agentName,
BytesPerTick: bytesPerTick,
Duration: strategy.timeout,
TickInterval: tickInterval,
WorkspaceName: ws.Name,
WorkspaceOwner: ws.OwnerName,
}

if err := config.Validate(); err != nil {
return xerrors.Errorf("validate config: %w", err)
}
var runner harness.Runnable = workspacetraffic.NewRunner(client, config)
var runner harness.Runnable = workspacetraffic.NewRunner(client, config, metrics)
if tracingEnabled {
runner = &runnableTraceWrapper{
tracer: tracer,
Expand Down Expand Up @@ -1034,6 +1050,13 @@ func (r *RootCmd) scaletestWorkspaceTraffic() *clibase.Cmd {
Description: "How often to send traffic.",
Value: clibase.DurationOf(&tickInterval),
},
{
Flag: "prometheus-address",
Env: "CODER_SCALETEST_PROMETHEUS_ADDRESS",
Default: "0.0.0.0:2112",
Description: "Address on which to expose prometheus metrics.",
Value: clibase.StringOf(&prometheusAddress),
},
}

tracingFlags.attach(&cmd.Options)
Expand Down
3 changes: 3 additions & 0 deletions cli/testdata/coder_scaletest_workspace-traffic_--help.golden
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ Generate traffic to scaletest workspaces through coderd
Output format specs in the format "<format>[:<path>]". Not specifying
a path will default to stdout. Available formats: text, json.

--prometheus-address string, $CODER_SCALETEST_PROMETHEUS_ADDRESS (default: 0.0.0.0:2112)
Address on which to expose prometheus metrics.

--tick-interval duration, $CODER_SCALETEST_WORKSPACE_TRAFFIC_TICK_INTERVAL (default: 100ms)
How often to send traffic.

Expand Down
2 changes: 1 addition & 1 deletion scaletest/terraform/coder.tf
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ resource "null_resource" "coder-monitoring-manifest_apply" {
provisioner "local-exec" {
working_dir = "${abspath(path.module)}/.coderv2"
command = <<EOF
KUBECONFIG=${var.name}-cluster.kubeconfig gcloud container clusters get-credentials ${var.name}-cluster --project=${var.project_id} --zone=${var.zone} && \
KUBECONFIG=${var.name}-cluster.kubeconfig gcloud container clusters get-credentials ${google_container_cluster.primary.name} --project=${var.project_id} --zone=${var.zone} && \
KUBECONFIG=${var.name}-cluster.kubeconfig kubectl apply -f ${abspath(local_file.coder-monitoring-manifest.filename)}
EOF
}
Expand Down
13 changes: 13 additions & 0 deletions scaletest/workspacetraffic/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,23 @@ import (
"time"

"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
"golang.org/x/xerrors"
)

type Config struct {
// AgentID is the workspace agent ID to which to connect.
AgentID uuid.UUID `json:"agent_id"`

// AgentName is the name of the agent. Used for metrics.
AgentName string `json:"agent_name"`

// WorkspaceName is the name of the workspace. Used for metrics.
WorkspaceName string `json:"workspace_name"`

// WorkspaceOwner is the owner of the workspace. Used for metrics.
WorkspaceOwner string `json:"workspace_owner"`

// BytesPerTick is the number of bytes to send to the agent per tick.
BytesPerTick int64 `json:"bytes_per_tick"`

Expand All @@ -20,6 +30,9 @@ type Config struct {
// TickInterval specifies the interval between ticks (that is, attempts to
// send data to workspace agents).
TickInterval time.Duration `json:"tick_interval"`

// Registry is a prometheus.Registerer for logging metrics
Registry prometheus.Registerer
}

func (c Config) Validate() error {
Expand Down
48 changes: 48 additions & 0 deletions scaletest/workspacetraffic/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package workspacetraffic

import "github.com/prometheus/client_golang/prometheus"

type Metrics struct {
BytesRead prometheus.CounterVec
BytesWritten prometheus.CounterVec
Errors prometheus.CounterVec
ReadLatencyMS prometheus.HistogramVec
WriteLatencyMS prometheus.HistogramVec
}

func NewMetrics(reg prometheus.Registerer) *Metrics {
m := &Metrics{
BytesRead: *prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "coderd",
Subsystem: "scaletest",
Name: "bytes_read",
}, []string{"username", "workspace_name", "agent_name"}),
BytesWritten: *prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "coderd",
Subsystem: "scaletest",
Name: "bytes_written",
}, []string{"username", "workspace_name", "agent_name"}),
Errors: *prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "coderd",
Subsystem: "scaletest",
Name: "errors",
}, []string{"username", "workspace_name", "agent_name"}),
ReadLatencyMS: *prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "coderd",
Subsystem: "scaletest",
Name: "read_latency_seconds",
}, []string{"username", "workspace_name", "agent_name"}),
WriteLatencyMS: *prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "coderd",
Subsystem: "scaletest",
Name: "write_latency_seconds",
}, []string{"username", "workspace_name", "agent_name"}),
}

reg.MustRegister(m.BytesRead)
reg.MustRegister(m.BytesWritten)
reg.MustRegister(m.Errors)
reg.MustRegister(m.ReadLatencyMS)
reg.MustRegister(m.WriteLatencyMS)
return m
}
24 changes: 17 additions & 7 deletions scaletest/workspacetraffic/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,21 @@ import (
)

type Runner struct {
client *codersdk.Client
cfg Config
client *codersdk.Client
cfg Config
metrics *Metrics
}

var (
_ harness.Runnable = &Runner{}
_ harness.Cleanable = &Runner{}
)

func NewRunner(client *codersdk.Client, cfg Config) *Runner {
func NewRunner(client *codersdk.Client, cfg Config, metrics *Metrics) *Runner {
return &Runner{
client: client,
cfg: cfg,
client: client,
cfg: cfg,
metrics: metrics,
}
}

Expand Down Expand Up @@ -186,20 +188,28 @@ type countReadWriter struct {
io.ReadWriter
bytesRead atomic.Int64
bytesWritten atomic.Int64
metrics Metrics
labels []string
}

func (w *countReadWriter) Read(p []byte) (int, error) {
start := time.Now()
n, err := w.ReadWriter.Read(p)
if err == nil {
w.metrics.ReadLatencyMS.WithLabelValues(w.labels...).Observe(time.Since(start).Seconds())
if n > 0 {
w.bytesRead.Add(int64(n))
w.metrics.BytesRead.WithLabelValues(w.labels...).Add(float64(n))
}
return n, err
}

func (w *countReadWriter) Write(p []byte) (int, error) {
start := time.Now()
n, err := w.ReadWriter.Write(p)
if err == nil {
w.metrics.WriteLatencyMS.WithLabelValues(w.labels...).Observe(time.Since(start).Seconds())
if n > 0 {
w.bytesWritten.Add(int64(n))
w.metrics.BytesWritten.WithLabelValues(w.labels...).Add(float64(n))
}
return n, err
}
Expand Down