Skip to content

Commit

Permalink
Removed dependency on cloud-diagnostics-common (#338)
Browse files Browse the repository at this point in the history
PR-URL: #338
  • Loading branch information
kjin committed Jan 5, 2017
1 parent f5401db commit 8aed09d
Show file tree
Hide file tree
Showing 9 changed files with 138 additions and 86 deletions.
12 changes: 6 additions & 6 deletions config.js
Expand Up @@ -90,14 +90,14 @@ module.exports = {
// projects.
ignoreContextHeader: false,

// The contents of a key file. If this field is set, its contents will be
// used for authentication instead of your application default credentials.
credentials: null,

// A path to a key file relative to the current working directory. If this
// field is set, the contents of the pointed file will be used for
// authentication instead of your application default credentials.
keyFilename: null,

// The contents of a key file. If this field is set, its contents will be
// used for authentication instead of your application default credentials.
// If keyFilename is also set, the value of credentials will be ignored.
credentials: null
// If credentials is also set, the value of keyFilename will be ignored.
keyFilename: null
}
};
65 changes: 48 additions & 17 deletions index.js
Expand Up @@ -22,16 +22,18 @@ var filesLoadedBeforeTrace = Object.keys(require.cache);
// patched before any user-land modules get loaded.
require('continuation-local-storage');

var SpanData = require('./src/span-data.js');
var common = require('@google/cloud-diagnostics-common');
var semver = require('semver');
var common = require('@google-cloud/common');
var constants = require('./src/constants.js');
var util = require('./src/util.js');
var gcpMetadata = require('gcp-metadata');
var semver = require('semver');
var traceUtil = require('./src/util.js');
var SpanData = require('./src/span-data.js');
var util = require('util');

var modulesLoadedBeforeTrace = [];

for (var i = 0; i < filesLoadedBeforeTrace.length; i++) {
var moduleName = util.packageNameFromPath(filesLoadedBeforeTrace[i]);
var moduleName = traceUtil.packageNameFromPath(filesLoadedBeforeTrace[i]);
if (moduleName && moduleName !== '@google/cloud-trace' &&
modulesLoadedBeforeTrace.indexOf(moduleName) === -1) {
modulesLoadedBeforeTrace.push(moduleName);
Expand Down Expand Up @@ -69,12 +71,18 @@ var phantomTraceAgent = {
var agent = phantomTraceAgent;

var initConfig = function(projectConfig) {
var util = require('util');
var config = {};
util._extend(config, require('./config.js').trace);
util._extend(config, projectConfig);
if (process.env.hasOwnProperty('GCLOUD_TRACE_LOGLEVEL')) {
config.logLevel = process.env.GCLOUD_TRACE_LOGLEVEL;
var envLogLevel = parseInt(process.env.GCLOUD_TRACE_LOGLEVEL, 10);
if (!isNaN(envLogLevel)) {
config.logLevel = envLogLevel;
} else {
console.error('Warning: Ignoring env var GCLOUD_TRACE_LOGLEVEL as it ' +
'contains an non-integer log level: ' +
process.env.GCLOUD_TRACE_LOGLEVEL);
}
}
if (process.env.hasOwnProperty('GCLOUD_PROJECT')) {
config.projectId = process.env.GCLOUD_PROJECT;
Expand Down Expand Up @@ -122,10 +130,22 @@ var publicAgent = {
}

var config = initConfig(projectConfig);

if (!config.enabled) {
return this;
}
var logger = common.logger.create(config.logLevel, '@google/cloud-trace');

var logLevel = config.logLevel;
if (logLevel < 0) {
logLevel = 0;
} else if (logLevel >= common.logger.LEVELS.length) {
logLevel = common.logger.LEVELS.length - 1;
}
var logger = common.logger({
level: common.logger.LEVELS[logLevel],
tag: '@google/cloud-trace'
});

if (!semver.satisfies(process.versions.node, '>=0.12')) {
logger.error('Tracing is only supported on Node versions >=0.12');
return this;
Expand All @@ -151,25 +171,36 @@ var publicAgent = {
}

if (typeof config.projectId === 'undefined') {
// Queue the work to acquire the projectNumber (potentially from the
// Queue the work to acquire the projectId (potentially from the
// network.)
common.utils.getProjectNumber(headers, function(err, project) {
gcpMetadata.project({
property: 'project-id',
headers: headers
}, function(err, response, projectId) {
if (response && response.statusCode !== 200) {
if (response.statusCode === 503) {
err = new Error('Metadata service responded with a 503 status ' +
'code. This may be due to a temporary server error; please try ' +
'again later.');
} else {
err = new Error('Metadata service responded with the following ' +
'status code: ' + response.statusCode);
}
}
if (err) {
// Fatal error. Disable the agent.
logger.error('Unable to acquire the project number from metadata ' +
'service. Please provide a valid project number as an env. ' +
'variable, or through config.projectId passed to start().' +
err);
'variable, or through config.projectId passed to start(). ' +
'Disabling trace agent. ' + err);
publicAgent.stop();
return;
}
config.projectId = project;
config.projectId = projectId;
});
} else if (typeof config.projectId === 'number') {
config.projectId = config.projectId.toString();
} else if (typeof config.projectId !== 'string') {
logger.error('config.projectId, if provided, must be' +
' a string or number. Disabling trace agent.');
logger.error('config.projectId, if provided, must be a string. ' +
'Disabling trace agent.');
return this;
}

Expand Down
4 changes: 3 additions & 1 deletion package.json
Expand Up @@ -32,12 +32,14 @@
"nock": "^9.0.0",
"proxyquire": "^1.4.0",
"request": "^2.61.0",
"retry-request": "^1.3.2",
"timekeeper": "^1.0.0",
"tmp": "0.0.31"
},
"dependencies": {
"@google/cloud-diagnostics-common": "0.3.0",
"@google-cloud/common": "^0.11.0",
"continuation-local-storage": "^3.1.4",
"gcp-metadata": "^0.1.0",
"lodash.findindex": "^4.4.0",
"lodash.isequal": "^4.0.0",
"methods": "^1.1.1",
Expand Down
71 changes: 41 additions & 30 deletions src/trace-writer.js
Expand Up @@ -16,7 +16,8 @@

'use strict';

var utils = require('@google/cloud-diagnostics-common').utils;
var gcpMetadata = require('gcp-metadata');
var util = require('@google-cloud/common').util;
var traceLabels = require('./trace-labels.js');
var pjson = require('../package.json');
var constants = require('./constants.js');
Expand All @@ -42,7 +43,8 @@ function TraceWriter(logger, config) {
this.config_ = config;

/** @private {function} authenticated request function */
this.request_ = utils.authorizedRequestFactory(SCOPES, {
this.request_ = util.makeAuthenticatedRequestFactory({
scopes: SCOPES,
credentials: config.credentials,
keyFile: config.keyFilename
});
Expand All @@ -59,7 +61,7 @@ function TraceWriter(logger, config) {
// Schedule periodic flushing of the buffer, but only if we are able to get
// the project number (potentially from the network.)
var that = this;
that.getProjectNumber(function(err, project) {
that.getProjectId(function(err, project) {
if (err) { return; } // ignore as index.js takes care of this.
that.scheduleFlush_(project);
});
Expand Down Expand Up @@ -100,7 +102,10 @@ TraceWriter.prototype.stop = function() {

TraceWriter.prototype.getHostname = function(cb) {
var that = this;
utils.getHostname(headers, function(err, hostname) {
gcpMetadata.instance({
property: 'hostname',
headers: headers
}, function(err, response, hostname) {
if (err && err.code !== 'ENOTFOUND') {
// We are running on GCP.
that.logger_.warn('Unable to retrieve GCE hostname.', err);
Expand All @@ -111,7 +116,10 @@ TraceWriter.prototype.getHostname = function(cb) {

TraceWriter.prototype.getInstanceId = function(cb) {
var that = this;
utils.getInstanceId(headers, function(err, instanceId) {
gcpMetadata.instance({
property: 'id',
headers: headers
}, function(err, response, instanceId) {
if (err && err.code !== 'ENOTFOUND') {
// We are running on GCP.
that.logger_.warn('Unable to retrieve GCE instance id.', err);
Expand All @@ -120,6 +128,33 @@ TraceWriter.prototype.getInstanceId = function(cb) {
});
};

/**
* Returns the project ID if it has been cached and attempts to load
* it from the enviroment or network otherwise.
*
* @param {function(?, number):?} callback an (err, result) style callback
*/
TraceWriter.prototype.getProjectId = function(callback) {
var that = this;
if (that.config_.projectId) {
callback(null, that.config_.projectId);
return;
}

gcpMetadata.project({
property: 'project-id',
headers: headers
}, function(err, response, projectId) {
if (err) {
callback(err);
return;
}
that.logger_.info('Acquired ProjectId from metadata: ' + projectId);
that.config_.projectId = projectId;
callback(null, projectId);
});
};

/**
* Ensures that all sub spans of the provided spanData are
* closed and then queues the span data to be published.
Expand Down Expand Up @@ -151,7 +186,7 @@ TraceWriter.prototype.writeSpan = function(spanData) {
TraceWriter.prototype.queueTrace_ = function(trace) {
var that = this;

that.getProjectNumber(function(err, project) {
that.getProjectId(function(err, project) {
if (err) {
that.logger_.info('No project number, dropping trace.');
return; // ignore as index.js takes care of this.
Expand Down Expand Up @@ -228,30 +263,6 @@ TraceWriter.prototype.publish_ = function(projectId, json) {
});
};

/**
* Returns the project number if it has been cached and attempts to load
* it from the enviroment or network otherwise.
*
* @param {function(?, number):?} callback an (err, result) style callback
*/
TraceWriter.prototype.getProjectNumber = function(callback) {
var that = this;
if (that.config_.projectId) {
callback(null, that.config_.projectId);
return;
}

utils.getProjectNumber(headers, function(err, project) {
if (err) {
callback(err);
return;
}
that.logger_.info('Acquired ProjectId from metadata: ' + project);
that.config_.projectId = project;
callback(null, project);
});
};

/**
* Export TraceWriter.
* FIXME(ofrobots): TraceWriter should be a singleton. We should export
Expand Down
4 changes: 2 additions & 2 deletions test/hooks/test-hooks-index.js
Expand Up @@ -36,9 +36,9 @@ describe('findModuleVersion', function() {
});

it('should work with namespaces', function() {
var modulePath = findModulePath('@google/cloud-diagnostics-common', module);
var modulePath = findModulePath('@google-cloud/common', module);
var truePackage =
require('../../node_modules/@google/cloud-diagnostics-common/package.json');
require('../../node_modules/@google-cloud/common/package.json');
assert.equal(findModuleVersion(modulePath, Module._load), truePackage.version);
});
});

0 comments on commit 8aed09d

Please sign in to comment.