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

feat(opentelemetry-resources): add runtime version information #2727

Merged
merged 18 commits into from
Mar 4, 2022
Merged
Show file tree
Hide file tree
Changes from 13 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
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ class ProcessDetector implements Detector {
[SemanticResourceAttributes.PROCESS_COMMAND]: process.argv[1] || '',
[SemanticResourceAttributes.PROCESS_COMMAND_LINE]:
process.argv.join(' ') || '',
[SemanticResourceAttributes.PROCESS_RUNTIME_VERSION]: process.versions.node,
[SemanticResourceAttributes.PROCESS_RUNTIME_NAME]: 'nodejs',
[SemanticResourceAttributes.PROCESS_RUNTIME_DESCRIPTION]: 'Node.js',
};
return this._getResourceAttributes(processResource, config);
}
Expand All @@ -56,7 +59,8 @@ class ProcessDetector implements Detector {
processResource[SemanticResourceAttributes.PROCESS_EXECUTABLE_PATH] ===
'' ||
processResource[SemanticResourceAttributes.PROCESS_COMMAND] === '' ||
processResource[SemanticResourceAttributes.PROCESS_COMMAND_LINE] === ''
processResource[SemanticResourceAttributes.PROCESS_COMMAND_LINE] === '' ||
processResource[SemanticResourceAttributes.PROCESS_RUNTIME_VERSION] === ''
) {
diag.debug(
'ProcessDetector failed: Unable to find required process resources. '
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,4 @@
* limitations under the License.
*/

import { Resource } from '../../Resource';

/**
* Detects resources for the browser platform, which is currently only the
* telemetry SDK resource. More could be added in the future. This method
* is async to match the signature of corresponding method for node.
*/
export const detectResources = async (): Promise<Resource> => {
return Resource.empty();
};
export { detectResources } from '../utils';
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
Copy link
Member

Choose a reason for hiding this comment

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

The detectors were moved to the src/detectors folder so that we can have a consistent export on both Node.js and Web environments. And detector.detect will do nothing if the environment is not the expected one, like https://github.com/open-telemetry/opentelemetry-js/blob/main/packages/opentelemetry-resources/src/detectors/ProcessDetector.ts#L30.

Could you move the BrowserDetector to src/detectors too so that it can be exported unconditionally?

* 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 { diag } from '@opentelemetry/api';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
import { Detector, Resource, ResourceDetectionConfig } from '../../..';
import { ResourceAttributes } from '../../../types';

/**
* BrowserDetector will be used to detect the resources related to browser.
*/
class BrowserDetector implements Detector {
async detect(config?: ResourceDetectionConfig): Promise<Resource> {
const browserResource: ResourceAttributes = {
[SemanticResourceAttributes.PROCESS_RUNTIME_NAME]: 'browser',
legendecas marked this conversation as resolved.
Show resolved Hide resolved
[SemanticResourceAttributes.PROCESS_RUNTIME_DESCRIPTION]: 'Web Browser',
[SemanticResourceAttributes.PROCESS_RUNTIME_VERSION]: window.navigator.userAgent
legendecas marked this conversation as resolved.
Show resolved Hide resolved
};
return this._getResourceAttributes(browserResource, config);
}
/**
* Validates process resource attribute map from process variables
*
* @param browserResource The un-sanitized resource attributes from process as key/value pairs.
* @param config: Config
* @returns The sanitized resource attributes.
*/
private _getResourceAttributes(
browserResource: ResourceAttributes,
_config?: ResourceDetectionConfig
) {
if (
browserResource[SemanticResourceAttributes.PROCESS_RUNTIME_VERSION] === ''
) {
diag.debug(
'BrowserDetector failed: Unable to find required browser resources. '
);
return Resource.empty();
} else {
return new Resource({
...browserResource,
});
}
}
}


export const browserDetector = new BrowserDetector();
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
* 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.
*/

export * from './BrowserDetector';
Original file line number Diff line number Diff line change
Expand Up @@ -14,60 +14,4 @@
* limitations under the License.
*/

import { Resource } from '../../Resource';
import { ResourceDetectionConfig } from '../../config';
import { diag } from '@opentelemetry/api';
import * as util from 'util';

/**
* Runs all resource detectors and returns the results merged into a single
* Resource.
*
* @param config Configuration for resource detection
*/
export const detectResources = async (
config: ResourceDetectionConfig = {}
): Promise<Resource> => {
const internalConfig: ResourceDetectionConfig = Object.assign(config);

const resources: Array<Resource> = await Promise.all(
(internalConfig.detectors || []).map(async d => {
try {
const resource = await d.detect(internalConfig);
diag.debug(`${d.constructor.name} found resource.`, resource);
return resource;
} catch (e) {
diag.debug(`${d.constructor.name} failed: ${e.message}`);
return Resource.empty();
}
})
);

// Future check if verbose logging is enabled issue #1903
logResources(resources);

return resources.reduce(
(acc, resource) => acc.merge(resource),
Resource.empty()
);
};

/**
* Writes debug information about the detected resources to the logger defined in the resource detection config, if one is provided.
*
* @param resources The array of {@link Resource} that should be logged. Empty entried will be ignored.
*/
const logResources = (resources: Array<Resource>) => {
resources.forEach(resource => {
// Print only populated resources
if (Object.keys(resource.attributes).length > 0) {
const resourceDebugString = util.inspect(resource.attributes, {
depth: 2,
breakLength: Infinity,
sorted: true,
compact: false,
});
diag.verbose(resourceDebugString);
}
});
};
export { detectResources } from '../utils';
73 changes: 73 additions & 0 deletions packages/opentelemetry-resources/src/platform/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* 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 { Resource } from '../Resource';
import { ResourceDetectionConfig } from '../config';
import { diag } from '@opentelemetry/api';
import * as util from 'util';

/**
* Runs all resource detectors and returns the results merged into a single
* Resource.
*
* @param config Configuration for resource detection
*/
export const detectResources = async (
config: ResourceDetectionConfig = {}
): Promise<Resource> => {
const internalConfig: ResourceDetectionConfig = Object.assign(config);

const resources: Resource[] = await Promise.all(
(internalConfig.detectors || []).map(async d => {
try {
const resource = await d.detect(internalConfig);
diag.debug(`${d.constructor.name} found resource.`, resource);
return resource;
} catch (e) {
diag.debug(`${d.constructor.name} failed: ${e.message}`);
return Resource.empty();
}
})
);

// Future check if verbose logging is enabled issue #1903
logResources(resources);

return resources.reduce(
(acc, resource) => acc.merge(resource),
Resource.empty()
);
};

/**
* Writes debug information about the detected resources to the logger defined in the resource detection config, if one is provided.
*
* @param resources The array of {@link Resource} that should be logged. Empty entries will be ignored.
*/
const logResources = (resources: Array<Resource>) => {
resources.forEach(resource => {
// Print only populated resources
if (Object.keys(resource.attributes).length > 0) {
const resourceDebugString = util.inspect(resource.attributes, {
Copy link
Member

Choose a reason for hiding this comment

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

util.inspect is not available on the Web, that's why it is located in the src/platform/node so that it won't be bundled in the web applications. Moving this API out of src/platform/node makes it unusable on Web environments. I think this change could be separated into another PR to make detectResource Web compatible.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

i will file an issue for this and work on it in another pr. thanks!

depth: 2,
breakLength: Infinity,
sorted: true,
compact: false,
});
diag.verbose(resourceDebugString);
}
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* 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 * as sinon from 'sinon';
import { Resource } from '../../src';
import { browserDetector } from '../../src/platform/browser/detectors';
import {
assertResource,
assertEmptyResource,
} from '../util/resource-assertions';


describe('browserDetector()', () => {
beforeEach(() => {
(globalThis.window as {}) = {};
sinon.stub(globalThis, 'window').value({
navigator: {
userAgent: '',
}
});
});

afterEach(() => {
sinon.restore();
});

it('should return browser information', async () => {
sinon.stub(globalThis, 'window').value({
navigator: {
userAgent: 'dddd',
}
});

const resource: Resource = await browserDetector.detect();
assertResource(resource, {
version: 'dddd',
runtimeDescription: 'Web Browser',
runtimeName: 'browser',
});
});
it('should return empty resources if version is missing', async () => {
const resource: Resource = await browserDetector.detect();
assertEmptyResource(resource);
});
});

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
import * as sinon from 'sinon';
import { processDetector, Resource } from '../../../src';
import {
assertProcessResource,
assertResource,
assertEmptyResource,
} from '../../util/resource-assertions';
import { describeNode } from '../../util';
Expand All @@ -32,13 +32,19 @@ describeNode('processDetector() on Node.js', () => {
sinon
.stub(process, 'argv')
.value(['/tmp/node', '/home/ot/test.js', 'arg1', 'arg2']);
sinon
.stub(process, 'versions')
.value({'node': '1.4.1'});

const resource: Resource = await processDetector.detect();
assertProcessResource(resource, {
assertResource(resource, {
pid: 1234,
name: 'otProcess',
command: '/home/ot/test.js',
commandLine: '/tmp/node /home/ot/test.js arg1 arg2',
version: '1.4.1',
runtimeDescription: 'Node.js',
runtimeName: 'nodejs',
});
});
it('should return empty resources if title, command and commondLine is missing', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -258,18 +258,21 @@ export const assertServiceResource = (
};

/**
* Test utility method to validate a process resources
* Test utility method to validate a process / browser resources
*
* @param resource the Resource to validate
* @param validations validations for the resource attributes
*/
export const assertProcessResource = (
export const assertResource = (
resource: Resource,
validations: {
pid?: number;
name?: string;
command?: string;
commandLine?: string;
version?: string;
runtimeName?: string;
runtimeDescription?: string;
}
) => {
assert.strictEqual(
Expand All @@ -294,6 +297,24 @@ export const assertProcessResource = (
validations.commandLine
);
}
if (validations.version) {
assert.strictEqual(
resource.attributes[SemanticResourceAttributes.PROCESS_RUNTIME_VERSION],
validations.version
);
}
if (validations.runtimeName) {
assert.strictEqual(
resource.attributes[SemanticResourceAttributes.PROCESS_RUNTIME_NAME],
validations.runtimeName
);
}
if (validations.runtimeDescription) {
assert.strictEqual(
resource.attributes[SemanticResourceAttributes.PROCESS_RUNTIME_DESCRIPTION],
validations.runtimeDescription
);
}
};

export const assertWebEngineResource = (resource: Resource, validations: {
Expand Down