From 292308b42fc68721a98a97002f6a139be264ef59 Mon Sep 17 00:00:00 2001 From: Ace Nassri Date: Tue, 25 Sep 2018 11:45:44 -0700 Subject: [PATCH] GCF: Add Stackdriver trigger sample (#740) * Add stackdriver BigQuery trigger sample * Make sample product-agnostic --- functions/log/.gcloudignore | 16 ++++++++++++++++ functions/log/index.js | 12 ++++++++++++ functions/log/test/index.test.js | 28 ++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 functions/log/.gcloudignore diff --git a/functions/log/.gcloudignore b/functions/log/.gcloudignore new file mode 100644 index 0000000000..ccc4eb240e --- /dev/null +++ b/functions/log/.gcloudignore @@ -0,0 +1,16 @@ +# This file specifies files that are *not* uploaded to Google Cloud Platform +# using gcloud. It follows the same syntax as .gitignore, with the addition of +# "#!include" directives (which insert the entries of the given .gitignore-style +# file at that point). +# +# For more information, run: +# $ gcloud topic gcloudignore +# +.gcloudignore +# If you would like to upload your .git directory, .gitignore file or files +# from your .gitignore file, remove the corresponding line +# below: +.git +.gitignore + +node_modules diff --git a/functions/log/index.js b/functions/log/index.js index 809de6d0b0..8f1f8ad61f 100644 --- a/functions/log/index.js +++ b/functions/log/index.js @@ -94,5 +94,17 @@ function getMetrics (callback) { // [END functions_log_get_metrics] } +// [START functions_log_stackdriver] +exports.processLogEntry = (data, callback) => { + const dataBuffer = Buffer.from(data.data.data, 'base64'); + const logEntry = JSON.parse(dataBuffer.toString('ascii')).protoPayload; + + console.log(`Method: ${logEntry.methodName}`); + console.log(`Resource: ${logEntry.resourceName}`); + console.log(`Initiator: ${logEntry.authenticationInfo.principalEmail}`); + callback(); +}; +// [END functions_log_stackdriver] + exports.getLogEntries = getLogEntries; exports.getMetrics = getMetrics; diff --git a/functions/log/test/index.test.js b/functions/log/test/index.test.js index fc9ff46c7b..ba39148d38 100644 --- a/functions/log/test/index.test.js +++ b/functions/log/test/index.test.js @@ -85,3 +85,31 @@ test.serial(`getMetrics: should retrieve metrics`, (t) => { t.is(callback.callCount, 1); }); + +test(`processLogEntry: should process log entry`, (t) => { + const sample = getSample(); + const callback = sinon.stub(); + + const json = JSON.stringify({ + protoPayload: { + methodName: 'method', + resourceName: 'resource', + authenticationInfo: { + principalEmail: 'me@example.com' + } + } + }); + + const data = { + data: { + data: Buffer.from(json, 'ascii') + } + }; + + sample.program.processLogEntry(data, callback); + + t.true(console.log.calledWith(`Method: method`)); + t.true(console.log.calledWith(`Resource: resource`)); + t.true(console.log.calledWith(`Initiator: me@example.com`)); + t.is(callback.callCount, 1); +});