From 4fc5b3b951370ea141ae9aea812c9bf4b7e93af5 Mon Sep 17 00:00:00 2001 From: Jack Wink <57678801+mothershipper@users.noreply.github.com> Date: Thu, 21 Oct 2021 12:47:47 -0700 Subject: [PATCH] fix(@opentelemetry/exporter-prometheus): unref prometheus server to prevent process running indefinitely Adds a test case as well, but, unfortunately, just that the server is unrefed. Not immediately clear how we could test based on open handles or reference counting to get at the behavior over the specific implementation. --- .../src/PrometheusExporter.ts | 3 ++- .../test/PrometheusExporter.test.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/experimental/packages/opentelemetry-exporter-prometheus/src/PrometheusExporter.ts b/experimental/packages/opentelemetry-exporter-prometheus/src/PrometheusExporter.ts index 35c1de5bd9e..3028f227239 100644 --- a/experimental/packages/opentelemetry-exporter-prometheus/src/PrometheusExporter.ts +++ b/experimental/packages/opentelemetry-exporter-prometheus/src/PrometheusExporter.ts @@ -68,7 +68,8 @@ export class PrometheusExporter implements MetricExporter { typeof config.appendTimestamp === 'boolean' ? config.appendTimestamp : PrometheusExporter.DEFAULT_OPTIONS.appendTimestamp; - this._server = createServer(this._requestHandler); + // unref to prevent prometheus exporter from holding the process open on exit + this._server = createServer(this._requestHandler).unref(); this._serializer = new PrometheusSerializer( this._prefix, this._appendTimestamp diff --git a/experimental/packages/opentelemetry-exporter-prometheus/test/PrometheusExporter.test.ts b/experimental/packages/opentelemetry-exporter-prometheus/test/PrometheusExporter.test.ts index 3b5f044be3c..9860d82eed9 100644 --- a/experimental/packages/opentelemetry-exporter-prometheus/test/PrometheusExporter.test.ts +++ b/experimental/packages/opentelemetry-exporter-prometheus/test/PrometheusExporter.test.ts @@ -36,6 +36,7 @@ describe('PrometheusExporter', () => { mockAggregator(HistogramAggregator); afterEach(() => { + sinon.restore(); delete process.env.OTEL_EXPORTER_PROMETHEUS_HOST; delete process.env.OTEL_EXPORTER_PROMETHEUS_PORT; }); @@ -116,6 +117,16 @@ describe('PrometheusExporter', () => { ); }); + it('should unref the server to allow graceful termination', () => { + const mockServer = sinon.createStubInstance(http.Server); + const createStub = sinon.stub(http, 'createServer'); + createStub.returns((mockServer as any) as http.Server); + const exporter = new PrometheusExporter({}, async () => { + await exporter.shutdown(); + }); + sinon.assert.calledOnce(mockServer.unref); + }); + it('should listen on environmentally set host and port', () => { process.env.OTEL_EXPORTER_PROMETHEUS_HOST = '127.0.0.1'; process.env.OTEL_EXPORTER_PROMETHEUS_PORT = '1234';