Search code examples
gogo-modulesvariable-initialization

In Go, how to track down which import is causing an error which occurs upon variable initialization?


I am trying to run the main() function for a repository but am running into an intractable panic which occurs upon variable initialization:

> go run main.go
go: finding github.com/myorg/some-repo/emulator latest
go: finding github.com/myorg/some-repo latest
panic: duplicate metrics collector registration attempted

goroutine 1 [running]:
github.com/prometheus/client_golang/prometheus.(*Registry).MustRegister(0xc0002a09b0, 0xc00033a1d0, 0x1, 0x1)
    /Users/kurt/go/pkg/mod/github.com/prometheus/[email protected]/prometheus/registry.go:400 +0xad
github.com/prometheus/client_golang/prometheus/promauto.Factory.NewGaugeVec(0x1acee40, 0xc0002a09b0, 0x0, 0x0, 0x0, 0x0, 0x19ade0e, 0x21, 0x19c60fa, 0x56, ...)
    /Users/kurt/go/pkg/mod/github.com/prometheus/[email protected]/prometheus/promauto/auto.go:306 +0x118
github.com/prometheus/client_golang/prometheus/promauto.NewGaugeVec(0x0, 0x0, 0x0, 0x0, 0x19ade0e, 0x21, 0x19c60fa, 0x56, 0x0, 0xc000370160, ...)
    /Users/kurt/go/pkg/mod/github.com/prometheus/[email protected]/prometheus/promauto/auto.go:197 +0xa9
github.com/myorg/some-library/pubsub.init.ializers()
    /Users/kurt/go/pkg/mod/github.com/myorg/[email protected]/pubsub/gcp.go:30 +0xcd
exit status 2

The error boils down to this line of code:

var inFlightMetric     = promauto.NewGauge(prometheus.GaugeOpts{Name: "gcp_pubsub_handlers_running_count"})

What I believe the problem is, is that that same library also has a pubsub/v2/gcp.go which the same line, so programs trying to import both github.com/myorg/some-library/pubsub and github.com/myorg/some-library/pubsub/v2 run into a panic caused by a 'name collision' in the Prometheus metrics collectors.

What I would like to do find which dependency is importing github.com/myorg/some-library/pubsub and replace it with pubsub/v2 to avoid this name collision. I'm having trouble figuring out how to determine that from this stack trace, however. Any ideas on how to achieve this?


Solution

  • I ended up working around this problem by making a branch avoid-registering-duplicate-metrics-collector in the library module and importing it from that branch:

    go get github.com/myorg/some-lib@avoid-registering-duplicate-metrics-collector
    

    In that branch, I attached a _v1 suffix to all the metrics registered in the pubsub package to avoid name collisions with the pusub/v2 ones. This is a bit of a hack though and requires regular merging of the master branch into that branch to keep it up-to-date. A way to find out which file in the imports was actually trying to import the pubsub package would still be useful.