Skip to content
This repository was archived by the owner on Oct 3, 2023. It is now read-only.

ability to share default registry #9

Merged
merged 3 commits into from
May 31, 2019
Merged
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
3 changes: 2 additions & 1 deletion example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"time"

"contrib.go.opencensus.io/exporter/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opencensus.io/stats"
"go.opencensus.io/stats/view"
)
Expand Down Expand Up @@ -78,6 +79,6 @@ func main() {

addr := ":9999"
log.Printf("Serving at %s", addr)
http.Handle("/metrics", exporter)
http.Handle("/metrics", promhttp.Handler())
log.Fatal(http.ListenAndServe(addr, nil))
}
20 changes: 15 additions & 5 deletions prometheus.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"sync"

"context"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opencensus.io/metric/metricdata"
Expand All @@ -44,6 +45,8 @@ type Exporter struct {
type Options struct {
Namespace string
Registry *prometheus.Registry
Registerer prometheus.Registerer
Gatherer prometheus.Gatherer
OnError func(err error)
ConstLabels prometheus.Labels // ConstLabels will be set as labels on all views.
}
Expand All @@ -53,12 +56,19 @@ func NewExporter(o Options) (*Exporter, error) {
if o.Registry == nil {
o.Registry = prometheus.NewRegistry()
}
collector := newCollector(o, o.Registry)
if o.Registerer == nil {
o.Registerer = o.Registry
}
if o.Gatherer == nil {
o.Gatherer = o.Registry
}

collector := newCollector(o, o.Registerer)
e := &Exporter{
opts: o,
g: o.Registry,
g: o.Gatherer,
c: collector,
handler: promhttp.HandlerFor(o.Registry, promhttp.HandlerOpts{}),
handler: promhttp.HandlerFor(o.Gatherer, promhttp.HandlerOpts{}),
}
collector.ensureRegisteredOnce()

Expand Down Expand Up @@ -112,7 +122,7 @@ type collector struct {
registerOnce sync.Once

// reg helps collector register views dynamically.
reg *prometheus.Registry
reg prometheus.Registerer

// reader reads metrics from all registered producers.
reader *metricexport.Reader
Expand All @@ -132,7 +142,7 @@ func (c *collector) Collect(ch chan<- prometheus.Metric) {
c.reader.ReadAndExport(me)
}

func newCollector(opts Options, registrar *prometheus.Registry) *collector {
func newCollector(opts Options, registrar prometheus.Registerer) *collector {
return &collector{
reg: registrar,
opts: opts,
Expand Down
101 changes: 90 additions & 11 deletions prometheus_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"go.opencensus.io/tag"

"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)

type mSlice []*stats.Int64Measure
Expand Down Expand Up @@ -73,8 +74,6 @@ func TestMetricsEndpointOutput(t *testing.T) {
}
defer view.Unregister(vc...)

view.SetReportingPeriod(time.Millisecond)

for _, m := range measures {
stats.Record(context.Background(), m.M(1))
}
Expand All @@ -86,8 +85,8 @@ func TestMetricsEndpointOutput(t *testing.T) {
var output string
for {
time.Sleep(10 * time.Millisecond)
if i == 1000 {
t.Fatal("no output at /metrics (10s wait)")
if i == 10 {
t.Fatal("no output at /metrics (100ms wait)")
}
i++

Expand Down Expand Up @@ -321,8 +320,6 @@ func TestConstLabelsIncluded(t *testing.T) {
}
defer view.Unregister(vc...)

view.SetReportingPeriod(time.Millisecond)

ctx, _ := tag.New(context.Background(), tag.Upsert(measureLabel, "issue961"))
for _, m := range measures {
stats.Record(ctx, m.M(1))
Expand All @@ -335,8 +332,8 @@ func TestConstLabelsIncluded(t *testing.T) {
var output string
for {
time.Sleep(10 * time.Millisecond)
if i == 1000 {
t.Fatal("no output at /metrics (10s wait)")
if i == 10 {
t.Fatal("no output at /metrics (100ms wait)")
}
i++

Expand Down Expand Up @@ -403,7 +400,6 @@ func TestViewMeasureWithoutTag(t *testing.T) {
t.Fatalf("failed to create views: %v", err)
}
defer view.Unregister(v)
view.SetReportingPeriod(time.Millisecond)
// Make a measure without some tags in the view.
ctx1, _ := tag.New(context.Background(), tag.Upsert(k4, "issue659"), tag.Upsert(randomKey, "value"), tag.Upsert(k2, "issue659"))
stats.Record(ctx1, m.M(1))
Expand All @@ -415,8 +411,8 @@ func TestViewMeasureWithoutTag(t *testing.T) {
var output string
for {
time.Sleep(10 * time.Millisecond)
if i == 1000 {
t.Fatal("no output at /metrics (10s wait)")
if i == 10 {
t.Fatal("no output at /metrics (100ms wait)")
}
i++
resp, err := http.Get(srv.URL)
Expand Down Expand Up @@ -448,3 +444,86 @@ tests_foo{key_1="issue659",key_2="",key_3="issue659",key_4="",key_5="issue659"}
t.Fatalf("output differed from expected output: %s want: %s", output, want)
}
}

func TestShareDefaultRegistry(t *testing.T) {
_, err := NewExporter(Options{
Registerer: prometheus.DefaultRegisterer,
Gatherer: prometheus.DefaultGatherer,
})
if err != nil {
t.Fatalf("failed to create prometheus exporter: %v", err)
}
m := stats.Int64("tests/foo", "foo", stats.UnitDimensionless)
v := &view.View{
Name: m.Name(),
Description: m.Description(),
Measure: m,
Aggregation: view.Count(),
}
if err := view.Register(v); err != nil {
t.Fatalf("failed to create views: %v", err)
}
defer view.Unregister(v)
stats.Record(context.Background(), m.M(1))

// counter, prometheus way
c := prometheus.NewCounter(prometheus.CounterOpts{Name: "prom_counter", Help: "Prometheus Counter"})
prometheus.MustRegister(c)

c.Add(1)

// Use prometheus handler
srv := httptest.NewServer(promhttp.Handler())
defer srv.Close()

var i int
var output string
for {
time.Sleep(10 * time.Millisecond)
if i == 10 {
t.Fatal("no output at /metrics (100ms wait)")
}
i++

resp, err := http.Get(srv.URL)
if err != nil {
t.Fatalf("failed to get /metrics: %v", err)
}

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatalf("failed to read body: %v", err)
}
resp.Body.Close()

output = string(body)
if output != "" {
break
}
}

if strings.Contains(output, "collected before with the same name and label values") {
t.Fatal("metric name and labels being duplicated but must be unique")
}

if strings.Contains(output, "error(s) occurred") {
t.Fatal("error reported by prometheus registry")
}

wantOc := `# HELP tests_foo foo
# TYPE tests_foo counter
tests_foo 1
`
if !strings.Contains(output, wantOc) {
t.Errorf("output does not contain opencensus counter. Output: %s want: %s", output, wantOc)
}

wantP := `# HELP prom_counter Prometheus Counter
# TYPE prom_counter counter
prom_counter 1
`
if !strings.Contains(output, wantP) {
t.Errorf("output does not contain opencensus counter. Output: %s want: %s", output, wantP)
}

}