Skip to content
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

fix(knex): connection attrs missing if connectionString used #1932

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
91 changes: 91 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
"knex": "0.95.9",
"mocha": "7.2.0",
"nyc": "15.1.0",
"pg": "8.11.3",
"rimraf": "5.0.5",
"sqlite3": "5.1.6",
"ts-mocha": "10.0.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,13 +131,19 @@
return function wrapQuery(original: () => any) {
return function wrapped_logging_method(this: any, query: any) {
const config = this.client.config;
const connection = utils.parseConnectionString(
config?.connection?.connectionString
);

const table = utils.extractTableName(this.builder);
// `method` actually refers to the knex API method - Not exactly "operation"
// in the spec sense, but matches most of the time.
const operation = query?.method;
const name =
config?.connection?.filename || config?.connection?.database;
connection?.database ||
config?.connection?.filename ||
config?.connection?.database;

Check warning on line 145 in plugins/node/opentelemetry-instrumentation-knex/src/instrumentation.ts

View check run for this annotation

Codecov / codecov/patch

plugins/node/opentelemetry-instrumentation-knex/src/instrumentation.ts#L145

Added line #L145 was not covered by tests

const maxLen = (
instrumentation._config as types.KnexInstrumentationConfig
).maxQueryLength!;
Expand All @@ -147,10 +153,13 @@
[SemanticAttributes.DB_SYSTEM]: utils.mapSystem(config.client),
[SemanticAttributes.DB_SQL_TABLE]: table,
[SemanticAttributes.DB_OPERATION]: operation,
[SemanticAttributes.DB_USER]: config?.connection?.user,
[SemanticAttributes.DB_USER]:
connection?.user || config?.connection?.user,
[SemanticAttributes.DB_NAME]: name,
[SemanticAttributes.NET_PEER_NAME]: config?.connection?.host,
[SemanticAttributes.NET_PEER_PORT]: config?.connection?.port,
[SemanticAttributes.NET_PEER_NAME]:
connection?.host || config?.connection?.host,
[SemanticAttributes.NET_PEER_PORT]:
connection?.port || config?.connection?.port,
[SemanticAttributes.NET_TRANSPORT]:
config?.connection?.filename === ':memory:' ? 'inproc' : undefined,
};
Expand Down
13 changes: 13 additions & 0 deletions plugins/node/opentelemetry-instrumentation-knex/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,16 @@ export const extractTableName = (builder: any): string => {
}
return table;
};

export const parseConnectionString = (connectionString: string | undefined) => {
if (!connectionString) {
return undefined;
}
const url = new URL(connectionString);
return {
host: url.hostname,
port: parseInt(url.port || '5432', 10),

Choose a reason for hiding this comment

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

I'm interested in this pull request getting merged, so I thought I'd add some notes.

It looks like connectionString is for both PostgreSQL and RedShift. It looks like the default port for RedShift is 5439.

I think you can check the URL protocol which should be postgres: or redshift: and set it to 5432/5439?

> (new URL("postgres://user:password@myhost/mydb")).protocol
'postgres:'

Copy link
Author

@edosrecki edosrecki Mar 27, 2024

Choose a reason for hiding this comment

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

Thanks for the comment. Yes I can do that. However we cannot then cover the case of CockroachDB which uses postgres protocol, but has a different default port of 26257.

I will see how knex handles redshift connection string when port is not provided and try to match that functionality. In the end that is the right thing to do.

user: url.username,
database: url.pathname.replace(/^\//, ''),
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,61 @@ describe('Knex instrumentation', () => {
);
});
});

describe('connectionString', () => {
const user = process.env.POSTGRES_USER || 'postgres';
const password = process.env.POSTGRES_PASSWORD || 'postgres';
const database = process.env.POSTGRES_DB || 'postgres';
const host = process.env.POSTGRES_HOST || 'localhost';
const port = process.env.POSTGRES_PORT
? parseInt(process.env.POSTGRES_PORT, 10)
: 54320;
let pgClient: any;

beforeEach(() => {
pgClient = knex({
client: 'pg',
connection: {
connectionString: `postgres://${user}:${password}@${host}:${port}/${database}`,
// connectionString takes precedence over other connection options in knex
host: 'ignored',
user: 'ignored',
port: 1111,
db: 'ignored',
},
});
});

afterEach(async () => {
await pgClient.destroy();
});

it('should extract connection attributes from connectionString when available', async () => {
const parentSpan = tracer.startSpan('parentSpan');
const statement = "select date('now')";

await context.with(
trace.setSpan(context.active(), parentSpan),
async () => {
await pgClient.raw(statement);
parentSpan.end();

const instrumentationSpans = memoryExporter.getFinishedSpans();

const span = instrumentationSpans[0];
assertMatch(span.name, new RegExp('raw'));
assertMatch(span.name, new RegExp(database));
assert.strictEqual(span.attributes['db.system'], 'postgresql');
assert.strictEqual(span.attributes['db.name'], database);
assert.strictEqual(span.attributes['db.user'], user);
assert.strictEqual(span.attributes['db.operation'], 'raw');
assert.strictEqual(span.attributes['db.statement'], statement);
assert.strictEqual(span.attributes['net.peer.name'], host);
assert.strictEqual(span.attributes['net.peer.port'], port);
}
);
});
});
});

describe('Disabling instrumentation', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import assert = require('assert');
import { parseConnectionString } from '../src/utils';

describe('utils', () => {
describe('parseConnectionString', () => {
it('should return undefined if connectionString is undefined', () => {
const connection = parseConnectionString(undefined);

assert.strictEqual(connection, undefined);
});

it('should return object with connection properties', () => {
const connection = parseConnectionString(
'postgres://user:password@localhost:5555/mydb'
);

assert.deepEqual(connection, {
host: 'localhost',
port: 5555,
user: 'user',
database: 'mydb',
});
});

it('should assume default port of 5432 if not provided', () => {
const connection = parseConnectionString(
'postgres://user@localhost/mydb'
);

assert.deepEqual(connection, {
host: 'localhost',
port: 5432,
user: 'user',
database: 'mydb',
});
});
});
});
Loading