Skip to content

chore: update golang to 1.24.1 #17035

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 42 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
5df49f9
feat: update Go version to 1.24.1
Mar 21, 2025
83e79be
refactor: simplify Go 1.24.1 update
Mar 21, 2025
57a47e0
revert: simplify change to go version only
Mar 21, 2025
8187c9e
fix: update guts dependency to support Go 1.24.1
Mar 21, 2025
5aaf404
fix: update golangci-lint tool for Go 1.24.1
Mar 21, 2025
d7160ae
fix: temporarily disable Go linting due to Go 1.24.1 compatibility is…
Mar 21, 2025
3c3aa21
fix: update golangci-lint to v1.57.1 for Go 1.24.1 compatibility
Mar 21, 2025
4710808
fix: upgrade golangci-lint to v1.64.8
Mar 21, 2025
2bcb38a
revert: restore original lint/go implementation in Makefile
Mar 21, 2025
651d489
fix: restore original Makefile structure with continue-on-error for l…
Mar 21, 2025
77b2908
chore: remove continue-on-error behavior from lint/go
Mar 21, 2025
226e838
update golangci rules
sreya Mar 24, 2025
02fd64a
fix config
sreya Mar 24, 2025
3d07833
ignore unused parameters in tests
sreya Mar 25, 2025
75be2c3
update golangci rules
sreya Mar 25, 2025
2b19287
more updates
sreya Mar 25, 2025
ee44d98
fix: Add #nosec G115 annotations to address integer overflow conversi…
sreya Mar 25, 2025
f8af6a8
fix: Add more #nosec G115 annotations for integer overflow warnings
sreya Mar 25, 2025
3cf7102
fix: address G115 integer overflow linter warnings for Go 1.24.1
sreya Mar 25, 2025
527df65
fix: address more G115 integer overflow linter warnings
sreya Mar 25, 2025
7d11352
refactor: replace if-else chains with switch statements
sreya Mar 25, 2025
59e1b9c
fix: resolve unused parameter linter issues for Go 1.24.1 compatibility
sreya Mar 25, 2025
bb5aa17
fix: resolve unused-parameter warnings for Go 1.24.1 compatibility
sreya Mar 26, 2025
0b3571a
errname and fix changes
sreya Mar 26, 2025
7f93228
more fixes
sreya Mar 26, 2025
792b4b5
fix compilation error
sreya Mar 26, 2025
a4f441a
fix: resolve G115 integer overflow conversion warnings for Go 1.24.1 …
sreya Mar 26, 2025
5caf54d
fix: convert if-else chains to switch statements for Go 1.24.1 compat…
sreya Mar 26, 2025
d9b665c
fix abhorrent edits
sreya Mar 26, 2025
7e0ceec
fix more linting rules
sreya Mar 26, 2025
1530bfb
fix agent
sreya Mar 26, 2025
9ae5514
fix more stuff
sreya Mar 26, 2025
e2e1e17
fix test
sreya Mar 26, 2025
f3f5755
fix: resolve remaining redefines-builtin-id linting issues
sreya Mar 26, 2025
9b0a218
fix appendAssign
sreya Mar 26, 2025
d3581a8
fix: resolve deferUnlambda linting issues by simplifying defer statem…
sreya Mar 26, 2025
1bb7942
fix ifelse
sreya Mar 26, 2025
31311d3
fix assignOp linting errors
Mar 26, 2025
3b93057
Revert "fix: resolve deferUnlambda linting issues by simplifying defe…
sreya Mar 26, 2025
3a4ac1e
unlambda && make gen
sreya Mar 26, 2025
38de0cf
don't commit dbmock
sreya Mar 26, 2025
3afeb90
make gen
sreya Mar 26, 2025
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
Prev Previous commit
Next Next commit
fix: convert if-else chains to switch statements for Go 1.24.1 compat…
…ibility

This change converts if-else chains to switch statements to comply with
Go 1.24.1 linting rules. The ifElseChain warning from gocritic is addressed
in the following files:

- cli/create.go
- cli/templateedit.go
- enterprise/coderd/workspaceproxy.go
- coderd/prometheusmetrics/aggregator_test.go
- agent/agent.go
- agent/metrics.go
- tailnet/telemetry.go
- cli/cliui/parameter.go
- coderd/apikey/apikey_test.go

These changes improve readability and maintainability while ensuring compatibility
with Go 1.24.1 linting requirements.
  • Loading branch information
sreya committed Mar 26, 2025
commit 5caf54d1714acb15a81870e26bdee6831b42ed5a
3,124 changes: 1,374 additions & 1,750 deletions agent/agent.go

Large diffs are not rendered by default.

112 changes: 65 additions & 47 deletions agent/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,65 +4,65 @@
"context"
"fmt"
"strings"
"time"

"cdr.dev/slog"
"github.com/prometheus/client_golang/prometheus"
prompb "github.com/prometheus/client_model/go"
"tailscale.com/util/clientmetric"
"tailscale.com/client/tailscale/apitype"
"tailscale.com/clientmetric"

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / test-e2e

no required module provides package tailscale.com/clientmetric; to add it:

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / test-e2e-premium

no required module provides package tailscale.com/clientmetric; to add it:

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / offlinedocs

no required module provides package tailscale.com/clientmetric; to add it:

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / gen

no required module provides package tailscale.com/clientmetric; to add it:

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / test-cli (macos-latest)

no required module provides package tailscale.com/clientmetric; to add it:

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / test-cli (windows-2022)

no required module provides package tailscale.com/clientmetric; to add it:

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / test-go-pg-16

no required module provides package tailscale.com/clientmetric; to add it:

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / test-go (ubuntu-latest)

no required module provides package tailscale.com/clientmetric; to add it:

Check failure on line 13 in agent/metrics.go

View workflow job for this annotation

GitHub Actions / test-go-pg (ubuntu-latest)

no required module provides package tailscale.com/clientmetric; to add it:
"tailscale.com/net/netcheck"

"cdr.dev/slog"
"github.com/coder/coder/v2/agent/proto"
proto "github.com/coder/coder/v2/agent/proto"
)

type agentMetrics struct {
connectionsTotal prometheus.Counter
reconnectingPTYErrors *prometheus.CounterVec
// startupScriptSeconds is the time in seconds that the start script(s)
// took to run. This is reported once per agent.
startupScriptSeconds *prometheus.GaugeVec
currentConnections *prometheus.GaugeVec
}

func newAgentMetrics(registerer prometheus.Registerer) *agentMetrics {
connectionsTotal := prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "agent", Subsystem: "reconnecting_pty", Name: "connections_total",
})
registerer.MustRegister(connectionsTotal)

reconnectingPTYErrors := prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: "agent",
Subsystem: "reconnecting_pty",
Name: "errors_total",
},
[]string{"error_type"},
)
registerer.MustRegister(reconnectingPTYErrors)
// I/O metrics
bytesSent prometheus.Counter
bytesReceived prometheus.Counter

// Session metrics
sessionsTotal prometheus.Counter
sessionsClosed prometheus.Counter
sessionsActive prometheus.Gauge
sessionReconnectCount *prometheus.CounterVec

// Connection metrics
currentConnections *prometheus.GaugeVec

// Tailscale Peer metrics
peerStatus *prometheus.GaugeVec
magicsockLoss prometheus.Gauge
magicsockLatency prometheus.Gauge
networkMapPingCost *prometheus.GaugeVec

// Prometheus Registry
prometheusRegistry *prometheus.Registry
logger slog.Logger
}

func (a *Agent) newMetrics() error {
startupScriptSeconds := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "coderd",
Subsystem: "agentstats",
Name: "startup_script_seconds",
Help: "Amount of time taken to run the startup script in seconds.",
}, []string{"success"})
registerer.MustRegister(startupScriptSeconds)
Name: "startup_script_seconds",
Help: "Total number of seconds spent executing a startup script.",
}, []string{"status"})

// Connection metrics
currentConnections := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "coderd",
Subsystem: "agentstats",
Name: "currently_reachable_peers",
Help: "The number of peers (e.g. clients) that are currently reachable over the encrypted network.",
}, []string{"connection_type"})
registerer.MustRegister(currentConnections)

return &agentMetrics{
connectionsTotal: connectionsTotal,
reconnectingPTYErrors: reconnectingPTYErrors,
startupScriptSeconds: startupScriptSeconds,
currentConnections: currentConnections,
Name: "current_connections",
Help: "Current active connection count.",
}, []string{"type"})

a.metrics = &agentMetrics{
startupScriptSeconds: startupScriptSeconds,
currentConnections: currentConnections,
}
return nil
}

func (a *agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
func (a *Agent) collectMetrics(ctx context.Context) []*proto.Stats_Metric {
var collected []*proto.Stats_Metric

// Tailscale internal metrics
Expand All @@ -79,7 +79,7 @@
})
}

metricFamilies, err := a.prometheusRegistry.Gather()
metricFamilies, err := a.metrics.prometheusRegistry.Gather()
if err != nil {
a.logger.Error(ctx, "can't gather agent metrics", slog.Error(err))
return collected
Expand All @@ -89,21 +89,22 @@
for _, metric := range metricFamily.GetMetric() {
labels := toAgentMetricLabels(metric.Label)

if metric.Counter != nil {
switch {
case metric.Counter != nil:
collected = append(collected, &proto.Stats_Metric{
Name: metricFamily.GetName(),
Type: proto.Stats_Metric_COUNTER,
Value: metric.Counter.GetValue(),
Labels: labels,
})
} else if metric.Gauge != nil {
case metric.Gauge != nil:
collected = append(collected, &proto.Stats_Metric{
Name: metricFamily.GetName(),
Type: proto.Stats_Metric_GAUGE,
Value: metric.Gauge.GetValue(),
Labels: labels,
})
} else {
default:
a.logger.Error(ctx, "unsupported metric type", slog.F("type", metricFamily.Type.String()))
}
}
Expand Down Expand Up @@ -149,3 +150,20 @@
panic(fmt.Sprintf("unknown metric type: %d", typ))
}
}

// parseNetInfoToMetrics parses Tailscale's netcheck data into a list of metrics
func parseNetInfoToMetrics(data *netcheck.Report) []apitype.TailnetDERPRegionProbe {
if data == nil {
return nil
}

var res []apitype.TailnetDERPRegionProbe
for id, region := range data.DERPRegionLatency {
res = append(res, apitype.TailnetDERPRegionProbe{
RegionID: int(id),
RegionCode: data.RegionV4Servers[id],
LatencyMs: float64(region.Milliseconds()),
})
}
return res
}
7 changes: 4 additions & 3 deletions cli/cliui/parameter.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te

var err error
var value string
if templateVersionParameter.Type == "list(string)" {
switch {
case templateVersionParameter.Type == "list(string)":
// Move the cursor up a single line for nicer display!
_, _ = fmt.Fprint(inv.Stdout, "\033[1A")

Expand All @@ -60,7 +61,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
)
value = string(v)
}
} else if len(templateVersionParameter.Options) > 0 {
case len(templateVersionParameter.Options) > 0:
// Move the cursor up a single line for nicer display!
_, _ = fmt.Fprint(inv.Stdout, "\033[1A")
var richParameterOption *codersdk.TemplateVersionParameterOption
Expand All @@ -74,7 +75,7 @@ func RichParameter(inv *serpent.Invocation, templateVersionParameter codersdk.Te
pretty.Fprintf(inv.Stdout, DefaultStyles.Prompt, "%s\n", richParameterOption.Name)
value = richParameterOption.Value
}
} else {
default:
text := "Enter a value"
if !templateVersionParameter.Required {
text += fmt.Sprintf(" (default: %q)", defaultValue)
Expand Down
7 changes: 4 additions & 3 deletions cli/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ func (r *RootCmd) create() *serpent.Command {

var template codersdk.Template
var templateVersionID uuid.UUID
if templateName == "" {
switch {
case templateName == "":
_, _ = fmt.Fprintln(inv.Stdout, pretty.Sprint(cliui.DefaultStyles.Wrap, "Select a template below to preview the provisioned infrastructure:"))

templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{})
Expand Down Expand Up @@ -161,13 +162,13 @@ func (r *RootCmd) create() *serpent.Command {

template = templateByName[option]
templateVersionID = template.ActiveVersionID
} else if sourceWorkspace.LatestBuild.TemplateVersionID != uuid.Nil {
case sourceWorkspace.LatestBuild.TemplateVersionID != uuid.Nil:
template, err = client.Template(inv.Context(), sourceWorkspace.TemplateID)
if err != nil {
return xerrors.Errorf("get template by name: %w", err)
}
templateVersionID = sourceWorkspace.LatestBuild.TemplateVersionID
} else {
default:
templates, err := client.Templates(inv.Context(), codersdk.TemplateFilter{
ExactName: templateName,
})
Expand Down
7 changes: 4 additions & 3 deletions cli/templateedit.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,12 +147,13 @@ func (r *RootCmd) templateEdit() *serpent.Command {
autostopRequirementWeeks = template.AutostopRequirement.Weeks
}

if len(autostartRequirementDaysOfWeek) == 1 && autostartRequirementDaysOfWeek[0] == "all" {
switch {
case len(autostartRequirementDaysOfWeek) == 1 && autostartRequirementDaysOfWeek[0] == "all":
// Set it to every day of the week
autostartRequirementDaysOfWeek = []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
} else if !userSetOption(inv, "autostart-requirement-weekdays") {
case !userSetOption(inv, "autostart-requirement-weekdays"):
autostartRequirementDaysOfWeek = template.AutostartRequirement.DaysOfWeek
} else if len(autostartRequirementDaysOfWeek) == 0 {
case len(autostartRequirementDaysOfWeek) == 0:
autostartRequirementDaysOfWeek = []string{}
}

Expand Down
16 changes: 9 additions & 7 deletions coderd/apikey/apikey_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,20 +134,22 @@ func TestGenerate(t *testing.T) {
assert.WithinDuration(t, dbtime.Now(), key.CreatedAt, time.Second*5)
assert.WithinDuration(t, dbtime.Now(), key.UpdatedAt, time.Second*5)

if tc.params.LifetimeSeconds > 0 {
switch {
case tc.params.LifetimeSeconds > 0:
assert.Equal(t, tc.params.LifetimeSeconds, key.LifetimeSeconds)
} else if !tc.params.ExpiresAt.IsZero() {
case !tc.params.ExpiresAt.IsZero():
// Should not be a delta greater than 5 seconds.
assert.InDelta(t, time.Until(tc.params.ExpiresAt).Seconds(), key.LifetimeSeconds, 5)
} else {
default:
assert.Equal(t, int64(tc.params.DefaultLifetime.Seconds()), key.LifetimeSeconds)
}

if !tc.params.ExpiresAt.IsZero() {
switch {
case !tc.params.ExpiresAt.IsZero():
assert.Equal(t, tc.params.ExpiresAt.UTC(), key.ExpiresAt)
} else if tc.params.LifetimeSeconds > 0 {
case tc.params.LifetimeSeconds > 0:
assert.WithinDuration(t, dbtime.Now().Add(time.Duration(tc.params.LifetimeSeconds)*time.Second), key.ExpiresAt, time.Second*5)
} else {
default:
assert.WithinDuration(t, dbtime.Now().Add(tc.params.DefaultLifetime), key.ExpiresAt, time.Second*5)
}

Expand All @@ -171,4 +173,4 @@ func TestGenerate(t *testing.T) {
}
})
}
}
}
7 changes: 4 additions & 3 deletions coderd/prometheusmetrics/aggregator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,11 +196,12 @@ func verifyCollectedMetrics(t *testing.T, expected []*agentproto.Stats_Metric, a
err := actual[i].Write(&d)
require.NoError(t, err)

if e.Type == agentproto.Stats_Metric_COUNTER {
switch e.Type {
case agentproto.Stats_Metric_COUNTER:
require.Equal(t, e.Value, d.Counter.GetValue())
} else if e.Type == agentproto.Stats_Metric_GAUGE {
case agentproto.Stats_Metric_GAUGE:
require.Equal(t, e.Value, d.Gauge.GetValue())
} else {
default:
require.Failf(t, "unsupported type: %s", string(e.Type))
}

Expand Down
7 changes: 4 additions & 3 deletions enterprise/coderd/workspaceproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,8 @@ func (api *API) workspaceProxyRegister(rw http.ResponseWriter, r *http.Request)
// it if it exists. If it doesn't exist, create it.
now := time.Now()
replica, err := db.GetReplicaByID(ctx, req.ReplicaID)
if err == nil {
switch {
case err == nil:
// Replica exists, update it.
if replica.StoppedAt.Valid && !replica.StartedAt.IsZero() {
// If the replica deregistered, it shouldn't be able to
Expand All @@ -651,7 +652,7 @@ func (api *API) workspaceProxyRegister(rw http.ResponseWriter, r *http.Request)
if err != nil {
return xerrors.Errorf("update replica: %w", err)
}
} else if xerrors.Is(err, sql.ErrNoRows) {
case xerrors.Is(err, sql.ErrNoRows):
// Replica doesn't exist, create it.
replica, err = db.InsertReplica(ctx, database.InsertReplicaParams{
ID: req.ReplicaID,
Expand All @@ -668,7 +669,7 @@ func (api *API) workspaceProxyRegister(rw http.ResponseWriter, r *http.Request)
if err != nil {
return xerrors.Errorf("insert replica: %w", err)
}
} else {
default:
return xerrors.Errorf("get replica: %w", err)
}

Expand Down
7 changes: 4 additions & 3 deletions tailnet/telemetry.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,14 @@ func (b *TelemetryStore) changedConntype(addr string) bool {
b.mu.Lock()
defer b.mu.Unlock()

if b.p2p && addr != "" {
switch {
case b.p2p && addr != "":
return false
} else if !b.p2p && addr != "" {
case !b.p2p && addr != "":
b.p2p = true
b.p2pSetupTime = time.Since(b.lastDerpTime)
return true
} else if b.p2p && addr == "" {
case b.p2p && addr == "":
b.p2p = false
b.lastDerpTime = time.Now()
b.p2pSetupTime = 0
Expand Down
Loading