From 7a5bf127d52a95652d7599c68b1a0aa2db368c6a Mon Sep 17 00:00:00 2001 From: Luke Sneeringer Date: Tue, 24 Oct 2017 04:31:21 -0700 Subject: [PATCH] Excise dns, logging, and monitoring. (#2692) --- README.md | 8 +- packages/dns/README.md | 98 -- packages/dns/package.json | 77 - packages/dns/src/change.js | 183 --- packages/dns/src/index.js | 266 ---- packages/dns/src/record.js | 177 --- packages/dns/src/zone.js | 982 ------------ packages/dns/system-test/data/zonefile.zone | 2 - packages/dns/system-test/dns.js | 376 ----- packages/dns/test/change.js | 156 -- packages/dns/test/index.js | 391 ----- packages/dns/test/record.js | 355 ----- packages/dns/test/zone.js | 946 ----------- packages/logging/README.md | 123 -- packages/logging/package.json | 91 -- packages/logging/src/entry.js | 168 -- packages/logging/src/index.js | 802 ---------- packages/logging/src/log.js | 658 -------- packages/logging/src/metadata.js | 159 -- packages/logging/src/sink.js | 279 ---- .../src/v2/config_service_v2_client.js | 605 -------- .../v2/config_service_v2_client_config.json | 51 - .../src/v2/doc/doc_google_api_label.js | 38 - .../doc/doc_google_api_monitored_resource.js | 94 -- .../doc_google_logging_type_http_request.js | 87 -- .../src/v2/doc/doc_google_protobuf_any.js | 121 -- .../v2/doc/doc_google_protobuf_duration.js | 84 - .../v2/doc/doc_google_protobuf_timestamp.js | 88 -- packages/logging/src/v2/doc/doc_log_entry.js | 183 --- packages/logging/src/v2/doc/doc_logging.js | 314 ---- .../logging/src/v2/doc/doc_logging_config.js | 314 ---- .../logging/src/v2/doc/doc_logging_metrics.js | 208 --- packages/logging/src/v2/index.js | 39 - .../src/v2/logging_service_v2_client.js | 838 ---------- .../v2/logging_service_v2_client_config.json | 65 - .../src/v2/metrics_service_v2_client.js | 558 ------- .../v2/metrics_service_v2_client_config.json | 51 - packages/logging/system-test/logging.js | 556 ------- packages/logging/test/entry.js | 233 --- packages/logging/test/index.js | 1382 ----------------- packages/logging/test/log.js | 755 --------- packages/logging/test/metadata.js | 331 ---- packages/logging/test/sink.js | 285 ---- packages/monitoring/README.md | 75 - packages/monitoring/package.json | 43 - .../smoke-test/metric_service_smoke_test.js | 92 -- packages/monitoring/src/index.js | 111 -- packages/monitoring/src/v3/doc/doc_common.js | 415 ----- .../src/v3/doc/doc_google_api_distribution.js | 84 - .../src/v3/doc/doc_google_api_label.js | 38 - .../src/v3/doc/doc_google_api_metric.js | 159 -- .../doc/doc_google_api_monitored_resource.js | 94 -- .../v3/doc/doc_google_protobuf_duration.js | 84 - .../v3/doc/doc_google_protobuf_timestamp.js | 88 -- packages/monitoring/src/v3/doc/doc_group.js | 77 - packages/monitoring/src/v3/doc/doc_metric.js | 107 -- .../monitoring/src/v3/group_service_client.js | 799 ---------- .../src/v3/group_service_client_config.json | 56 - packages/monitoring/src/v3/index.js | 38 - .../src/v3/metric_service_client.js | 1097 ------------- .../src/v3/metric_service_client_config.json | 66 - packages/monitoring/test/gapic-v3.js | 766 --------- 62 files changed, 4 insertions(+), 17862 deletions(-) delete mode 100644 packages/dns/README.md delete mode 100644 packages/dns/package.json delete mode 100644 packages/dns/src/change.js delete mode 100644 packages/dns/src/index.js delete mode 100644 packages/dns/src/record.js delete mode 100644 packages/dns/src/zone.js delete mode 100644 packages/dns/system-test/data/zonefile.zone delete mode 100644 packages/dns/system-test/dns.js delete mode 100644 packages/dns/test/change.js delete mode 100644 packages/dns/test/index.js delete mode 100644 packages/dns/test/record.js delete mode 100644 packages/dns/test/zone.js delete mode 100644 packages/logging/README.md delete mode 100644 packages/logging/package.json delete mode 100644 packages/logging/src/entry.js delete mode 100644 packages/logging/src/index.js delete mode 100644 packages/logging/src/log.js delete mode 100644 packages/logging/src/metadata.js delete mode 100644 packages/logging/src/sink.js delete mode 100644 packages/logging/src/v2/config_service_v2_client.js delete mode 100644 packages/logging/src/v2/config_service_v2_client_config.json delete mode 100644 packages/logging/src/v2/doc/doc_google_api_label.js delete mode 100644 packages/logging/src/v2/doc/doc_google_api_monitored_resource.js delete mode 100644 packages/logging/src/v2/doc/doc_google_logging_type_http_request.js delete mode 100644 packages/logging/src/v2/doc/doc_google_protobuf_any.js delete mode 100644 packages/logging/src/v2/doc/doc_google_protobuf_duration.js delete mode 100644 packages/logging/src/v2/doc/doc_google_protobuf_timestamp.js delete mode 100644 packages/logging/src/v2/doc/doc_log_entry.js delete mode 100644 packages/logging/src/v2/doc/doc_logging.js delete mode 100644 packages/logging/src/v2/doc/doc_logging_config.js delete mode 100644 packages/logging/src/v2/doc/doc_logging_metrics.js delete mode 100644 packages/logging/src/v2/index.js delete mode 100644 packages/logging/src/v2/logging_service_v2_client.js delete mode 100644 packages/logging/src/v2/logging_service_v2_client_config.json delete mode 100644 packages/logging/src/v2/metrics_service_v2_client.js delete mode 100644 packages/logging/src/v2/metrics_service_v2_client_config.json delete mode 100644 packages/logging/system-test/logging.js delete mode 100644 packages/logging/test/entry.js delete mode 100644 packages/logging/test/index.js delete mode 100644 packages/logging/test/log.js delete mode 100644 packages/logging/test/metadata.js delete mode 100644 packages/logging/test/sink.js delete mode 100644 packages/monitoring/README.md delete mode 100644 packages/monitoring/package.json delete mode 100644 packages/monitoring/smoke-test/metric_service_smoke_test.js delete mode 100644 packages/monitoring/src/index.js delete mode 100644 packages/monitoring/src/v3/doc/doc_common.js delete mode 100644 packages/monitoring/src/v3/doc/doc_google_api_distribution.js delete mode 100644 packages/monitoring/src/v3/doc/doc_google_api_label.js delete mode 100644 packages/monitoring/src/v3/doc/doc_google_api_metric.js delete mode 100644 packages/monitoring/src/v3/doc/doc_google_api_monitored_resource.js delete mode 100644 packages/monitoring/src/v3/doc/doc_google_protobuf_duration.js delete mode 100644 packages/monitoring/src/v3/doc/doc_google_protobuf_timestamp.js delete mode 100644 packages/monitoring/src/v3/doc/doc_group.js delete mode 100644 packages/monitoring/src/v3/doc/doc_metric.js delete mode 100644 packages/monitoring/src/v3/group_service_client.js delete mode 100644 packages/monitoring/src/v3/group_service_client_config.json delete mode 100644 packages/monitoring/src/v3/index.js delete mode 100644 packages/monitoring/src/v3/metric_service_client.js delete mode 100644 packages/monitoring/src/v3/metric_service_client_config.json delete mode 100644 packages/monitoring/test/gapic-v3.js diff --git a/README.md b/README.md index 199b997ed78..d91bda7d6c9 100644 --- a/README.md +++ b/README.md @@ -15,21 +15,21 @@ This client supports the following Google Cloud Platform services at a [General * [Cloud Natural Language](http://github.com/googleapis/nodejs-language/) (GA) * [Cloud Storage](http://github.com/googleapis/nodejs-storage/) (GA) * [Cloud Translation API](#cloud-translation-api-ga) (GA) -* [Google Stackdriver Logging](#google-stackdriver-logging-ga) (GA) +* [Google Stackdriver Logging](https://github.com/googleapis/nodejs-logging/) (GA) This client supports the following Google Cloud Platform services at a [Beta](#versioning) quality level: -* [Cloud Firestore](http://github.com/googleapis/nodejs-firestore/) (Beta) +* [Cloud Firestore](https://github.com/googleapis/nodejs-firestore/) (Beta) * [Cloud Pub/Sub](#cloud-pubsub-beta) (Beta) * [Cloud Spanner](#cloud-spanner-beta) (Beta) * [Cloud Vision](#cloud-vision-beta) (Beta) * [Google BigQuery](#google-bigquery-beta) (Beta) -* [Google Stackdriver Monitoring](#google-stackdriver-monitoring-beta) (Beta) +* [Google Stackdriver Monitoring](https://github.com/googleapis/nodejs-monitoring) (Beta) This client supports the following Google Cloud Platform services at an [Alpha](#versioning) quality level: * [Cloud Bigtable](#cloud-bigtable-alpha) (Alpha) -* [Cloud DNS](#cloud-dns-alpha) (Alpha) +* [Cloud DNS](https://github.com/googleapis/nodejs-dns) (Alpha) * [Cloud Resource Manager](#cloud-resource-manager-alpha) (Alpha) * [Cloud Speech](#cloud-speech-alpha) (Alpha) * [Google Compute Engine](#google-compute-engine-alpha) (Alpha) diff --git a/packages/dns/README.md b/packages/dns/README.md deleted file mode 100644 index a18ba509762..00000000000 --- a/packages/dns/README.md +++ /dev/null @@ -1,98 +0,0 @@ -# @google-cloud/dns ([Alpha][versioning]) -> Cloud DNS Client Library for Node.js - -*Looking for more Google APIs than just DNS? You might want to check out [`google-cloud`][google-cloud].* - -- [API Documentation][gcloud-dns-docs] -- [Official Documentation][cloud-dns-docs] - - -```sh -$ npm install --save @google-cloud/dns -``` -```js -var dns = require('@google-cloud/dns')({ - projectId: 'grape-spaceship-123', - keyFilename: '/path/to/keyfile.json' -}); - -// Create a managed zone. -dns.createZone('my-new-zone', { - dnsName: 'my-domain.com.' -}, function(err, zone) {}); - -// Reference an existing zone. -var zone = dns.zone('my-existing-zone'); - -// Create an NS record. -var nsRecord = zone.record('ns', { - ttl: 86400, - name: 'my-domain.com.', - data: 'ns-cloud1.googledomains.com.' -}); - -zone.addRecords([nsRecord], function(err, change) {}); - -// Create a zonefile from the records in your zone. -zone.export('/zonefile.zone', function(err) {}); - -// Promises are also supported by omitting callbacks. -zone.addRecords([nsRecord]).then(function(data) { - var change = data[0]; -}); - -// It's also possible to integrate with third-party Promise libraries. -var dns = require('@google-cloud/dns')({ - promise: require('bluebird') -}); -``` - - -## Authentication - -It's incredibly easy to get authenticated and start using Google's APIs. You can set your credentials on a global basis as well as on a per-API basis. See each individual API section below to see how you can auth on a per-API-basis. This is useful if you want to use different accounts for different Cloud services. - -### On Google Cloud Platform - -If you are running this client on Google Cloud Platform, we handle authentication for you with no configuration. You just need to make sure that when you [set up the GCE instance][gce-how-to], you add the correct scopes for the APIs you want to access. - -``` js -var dns = require('@google-cloud/dns')(); -// ...you're good to go! -``` - -### Elsewhere - -If you are not running this client on Google Cloud Platform, you need a Google Developers service account. To create a service account: - -1. Visit the [Google Developers Console][dev-console]. -2. Create a new project or click on an existing project. -3. Navigate to **APIs & auth** > **APIs section** and turn on the following APIs (you may need to enable billing in order to use these services): - * Google Cloud DNS API -4. Navigate to **APIs & auth** > **Credentials** and then: - * If you want to use a new service account key, click on **Create credentials** and select **Service account key**. After the account key is created, you will be prompted to download the JSON key file that the library uses to authenticate your requests. - * If you want to generate a new service account key for an existing service account, click on **Generate new JSON key** and download the JSON key file. - -``` js -var projectId = process.env.GCLOUD_PROJECT; // E.g. 'grape-spaceship-123' - -var dns = require('@google-cloud/dns')({ - projectId: projectId, - - // The path to your key file: - keyFilename: '/path/to/keyfile.json' - - // Or the contents of the key file: - credentials: require('./path/to/keyfile.json') -}); - -// ...you're good to go! -``` - - -[versioning]: https://github.com/GoogleCloudPlatform/google-cloud-node#versioning -[google-cloud]: https://github.com/GoogleCloudPlatform/google-cloud-node -[gce-how-to]: https://cloud.google.com/compute/docs/authentication#using -[dev-console]: https://console.developers.google.com/project -[gcloud-dns-docs]: https://googlecloudplatform.github.io/google-cloud-node/#/docs/dns -[cloud-dns-docs]: https://cloud.google.com/dns/docs diff --git a/packages/dns/package.json b/packages/dns/package.json deleted file mode 100644 index efe913caa00..00000000000 --- a/packages/dns/package.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "name": "@google-cloud/dns", - "version": "0.6.2", - "author": "Google Inc.", - "description": "Cloud DNS Client Library for Node.js", - "contributors": [ - { - "name": "Burcu Dogan", - "email": "jbd@google.com" - }, - { - "name": "Johan Euphrosine", - "email": "proppy@google.com" - }, - { - "name": "Patrick Costello", - "email": "pcostell@google.com" - }, - { - "name": "Ryan Seys", - "email": "ryan@ryanseys.com" - }, - { - "name": "Silvano Luciani", - "email": "silvano@google.com" - }, - { - "name": "Stephen Sawchuk", - "email": "sawchuk@gmail.com" - } - ], - "main": "./src/index.js", - "files": [ - "src", - "AUTHORS", - "CONTRIBUTORS", - "LICENSE" - ], - "repository": "googlecloudplatform/google-cloud-node", - "keywords": [ - "google apis client", - "google api client", - "google apis", - "google api", - "google", - "google cloud platform", - "google cloud", - "cloud", - "google dns", - "dns" - ], - "dependencies": { - "@google-cloud/common": "^0.13.0", - "arrify": "^1.0.0", - "dns-zonefile": "0.1.18", - "extend": "^3.0.0", - "is": "^3.0.1", - "methmeth": "^1.0.0", - "string-format-obj": "^1.0.0" - }, - "devDependencies": { - "async": "^2.1.4", - "mocha": "^3.0.1", - "proxyquire": "^1.7.10", - "tmp": "^0.0.31", - "uuid": "^3.0.1" - }, - "scripts": { - "publish-module": "node ../../scripts/publish.js dns", - "test": "mocha test/*.js", - "system-test": "mocha system-test/*.js --no-timeouts --bail" - }, - "license": "Apache-2.0", - "engines": { - "node": ">=4.0.0" - } -} diff --git a/packages/dns/src/change.js b/packages/dns/src/change.js deleted file mode 100644 index 93c78051efd..00000000000 --- a/packages/dns/src/change.js +++ /dev/null @@ -1,183 +0,0 @@ -/*! - * Copyright 2014 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module dns/change - */ - -'use strict'; - -var common = require('@google-cloud/common'); -var util = require('util'); - -/** - * @constructor - * @alias module:dns/change - * - * @param {module:dns/zone} zone - The parent zone object. - * @param {string} id - ID of the change. - * - * @example - * var zone = dns.zone('zone-id'); - * var change = zone.change('change-id'); - */ -function Change(zone, id) { - var methods = { - /** - * Check if the change exists. - * - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this - * request. - * @param {boolean} callback.exists - Whether the change exists or not. - * - * @example - * change.exists(function(err, exists) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * change.exists().then(function(data) { - * var exists = data[0]; - * }); - */ - exists: true, - - /** - * Get a change if it exists. - * - * You may optionally use this to "get or create" an object by providing an - * object with `autoCreate` set to `true`. Any extra configuration that is - * normally required for the `create` method must be contained within this - * object as well. - * - * @param {options=} options - Configuration object. - * @param {boolean} options.autoCreate - Automatically create the object if - * it does not exist. Default: `false` - * - * @example - * change.get(function(err, change, apiResponse) { - * // `change.metadata` has been populated. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * change.get().then(function(data) { - * var change = data[0]; - * var apiResponse = data[1]; - * }); - */ - get: true, - - /** - * Get the metadata for the change in the zone. - * - * @resource [Changes: get API Documentation]{@link https://cloud.google.com/dns/api/v1/changes/get} - * - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?object} callback.metadata - Metadata of the change from the API. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * change.getMetadata(function(err, metadata, apiResponse) { - * if (!err) { - * // metadata = { - * // kind: 'dns#change', - * // additions: [{...}], - * // deletions: [{...}], - * // startTime: '2015-07-21T14:40:06.056Z', - * // id: '1', - * // status: 'done' - * // } - * } - * }); - * - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * change.getMetadata().then(function(data) { - * var metadata = data[0]; - * var apiResponse = data[1]; - * }); - */ - getMetadata: true - }; - - common.ServiceObject.call(this, { - parent: zone, - baseUrl: '/changes', - id: id, - methods: methods - }); -} - -util.inherits(Change, common.ServiceObject); - -/** - * Create a change. - * - * @param {object} config - See {module:dns/zone#createChange}. - * - * @example - * var config = { - * add: { - * // ... - * } - * }; - * - * change.create(config, function(err, change, apiResponse) { - * if (!err) { - * // The change was created successfully. - * } - * }); - * - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * change.create(config).then(function(data) { - * var change = data[0]; - * var apiResponse = data[1]; - * }); - */ -Change.prototype.create = function(config, callback) { - var self = this; - - this.parent.createChange(config, function(err, change, apiResponse) { - if (err) { - callback(err, null, apiResponse); - return; - } - - self.id = change.id; - self.metadata = change.metadata; - - callback(null, self, apiResponse); - }); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Change); - - -module.exports = Change; diff --git a/packages/dns/src/index.js b/packages/dns/src/index.js deleted file mode 100644 index 3e60ccc13fd..00000000000 --- a/packages/dns/src/index.js +++ /dev/null @@ -1,266 +0,0 @@ -/*! - * Copyright 2014 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module dns - */ - -'use strict'; - -var arrify = require('arrify'); -var common = require('@google-cloud/common'); -var extend = require('extend'); -var is = require('is'); -var util = require('util'); - -/** - * @type {module:dns/zone} - * @private - */ -var Zone = require('./zone.js'); - -/** - * [Cloud DNS](https://cloud.google.com/dns/what-is-cloud-dns) is a high- - * performance, resilient, global DNS service that provides a cost-effective way - * to make your applications and services available to your users. This - * programmable, authoritative DNS service can be used to easily publish and - * manage DNS records using the same infrastructure relied upon by Google. - * - * @constructor - * @alias module:dns - * - * @resource [What is Cloud DNS?]{@link https://cloud.google.com/dns/what-is-cloud-dns} - * - * @param {object} options - [Configuration object](#/docs). - */ -function DNS(options) { - if (!(this instanceof DNS)) { - options = common.util.normalizeArguments(this, options); - return new DNS(options); - } - - var config = { - baseUrl: 'https://www.googleapis.com/dns/v1', - scopes: [ - 'https://www.googleapis.com/auth/ndev.clouddns.readwrite', - 'https://www.googleapis.com/auth/cloud-platform' - ], - packageJson: require('../package.json') - }; - - common.Service.call(this, config, options); -} - -util.inherits(DNS, common.Service); - -/** - * Create a managed zone. - * - * @resource [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} - * - * @throws {error} If a zone name is not provided. - * @throws {error} If a zone dnsName is not provided. - * - * @param {string} name - Unique name for the zone. E.g. "my-zone" - * @param {object} config - Configuration object. - * @param {string} config.dnsName - DNS name for the zone. E.g. "example.com." - * @param {string=} config.description - Description text for the zone. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/zone} callback.zone - A new {module:dns/zone} object. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * var config = { - * dnsName: 'example.com.', // note the period at the end of the domain. - * description: 'This zone is awesome!' - * }; - * - * dns.createZone('my-awesome-zone', config, function(err, zone, apiResponse) { - * if (!err) { - * // The zone was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * dns.createZone('my-awesome-zone', config).then(function(data) { - * var zone = data[0]; - * var apiResponse = data[1]; - * }); - */ -DNS.prototype.createZone = function(name, config, callback) { - var self = this; - - if (!name) { - throw new Error('A zone name is required.'); - } - - if (!config || !config.dnsName) { - throw new Error('A zone dnsName is required.'); - } - - config.name = name; - - // Required by the API. - config.description = config.description || ''; - - this.request({ - method: 'POST', - uri: '/managedZones', - json: config - }, function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - var zone = self.zone(resp.name); - zone.metadata = resp; - - callback(null, zone, resp); - }); -}; - -/** - * Gets a list of managed zones for the project. - * - * @resource [ManagedZones: list API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/list} - * - * @param {object=} query - Query object. - * @param {boolean} query.autoPaginate - Have pagination handled automatically. - * Default: true. - * @param {number} query.maxApiCalls - Maximum number of API calls to make. - * @param {number} query.maxResults - Maximum number of results to return. - * @param {string} query.pageToken - Page token. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/zone[]} callback.zones - An array of {module:dns/zone} - * objects. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * dns.getZones(function(err, zones, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * dns.getZones().then(function(data) { - * var zones = data[0]; - * }); - */ -DNS.prototype.getZones = function(query, callback) { - var self = this; - - if (is.fn(query)) { - callback = query; - query = {}; - } - - this.request({ - uri: '/managedZones', - qs: query - }, function(err, resp) { - if (err) { - callback(err, null, null, resp); - return; - } - - var zones = arrify(resp.managedZones).map(function(zone) { - var zoneInstance = self.zone(zone.name); - zoneInstance.metadata = zone; - return zoneInstance; - }); - - var nextQuery = null; - - if (resp.nextPageToken) { - nextQuery = extend({}, query, { - pageToken: resp.nextPageToken - }); - } - - callback(null, zones, nextQuery, resp); - }); -}; - -/** - * Gets a list of {module:dns/zone} objects for the project as a readable object - * stream. - * - * @param {object=} query - Configuration object. See - * {module:dns#getZones} for a complete list of options. - * @return {stream} - * - * @example - * dns.getZonesStream() - * .on('error', console.error) - * .on('data', function(zone) { - * // zone is a Zone object. - * }) - * .on('end', function() { - * // All zones retrieved. - * }); - * - * //- - * // If you anticipate many results, you can end a stream early to prevent - * // unnecessary processing and API requests. - * //- - * dns.getZonesStream() - * .on('data', function(zone) { - * this.end(); - * }); - */ -DNS.prototype.getZonesStream = common.paginator.streamify('getZones'); - -/** - * Create a zone object representing a managed zone. - * - * @throws {error} If a zone name is not provided. - * - * @param {string} name - The unique name of the zone. - * @return {module:dns/zone} - * - * @example - * var zone = dns.zone('my-zone'); - */ -DNS.prototype.zone = function(name) { - if (!name) { - throw new Error('A zone name is required.'); - } - - return new Zone(this, name); -}; - -/*! Developer Documentation - * - * These methods can be auto-paginated. - */ -common.paginator.extend(DNS, 'getZones'); - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(DNS, { - exclude: ['zone'] -}); - -DNS.Zone = Zone; - -module.exports = DNS; diff --git a/packages/dns/src/record.js b/packages/dns/src/record.js deleted file mode 100644 index eb8d53ef0f1..00000000000 --- a/packages/dns/src/record.js +++ /dev/null @@ -1,177 +0,0 @@ -/*! - * Copyright 2014 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module dns/record - */ - -'use strict'; - -var arrify = require('arrify'); -var common = require('@google-cloud/common'); -var extend = require('extend'); -var format = require('string-format-obj'); - -/** - * Create a Resource Record object. - * - * @constructor - * @alias module:dns/record - * - * @param {object} type - The record type, e.g. `A`, `AAAA`, `MX`. - * @param {object} metadata - The metadata of this record. - * @param {string} metadata.name - The name of the record, e.g. - * `www.example.com.`. - * @param {string[]} metadata.data - Defined in - * [RFC 1035, section 5](https://goo.gl/9EiM0e) and - * [RFC 1034, section 3.6.1](https://goo.gl/Hwhsu9). - * @param {number} metadata.ttl - Seconds that the resource is cached by - * resolvers. - * - * @example - * var zone = dns.zone('my-awesome-zone'); - * - * var record = zone.record('a', { - * name: 'example.com.', - * ttl: 86400, - * data: '1.2.3.4' - * }); - */ -function Record(zone, type, metadata) { - this.zone_ = zone; - - this.type = type; - this.metadata = metadata; - - extend(this, this.toJSON()); - - if (this.rrdatas) { - this.data = this.rrdatas; - delete this.rrdatas; - } -} - -/** - * Create a Record instance from a resource record set in a zone file. - * - * @private - * - * @param {module:dns/zone} zone [description] - * @param {string} type - The record type, e.g. `A`, `AAAA`, `MX`. - * @param {object} bindData - Metadata parsed from dns-zonefile. Properties vary - * based on the type of record. - * @return {module:dns/record} - */ -Record.fromZoneRecord_ = function(zone, type, bindData) { - var typeToZoneFormat = { - a: '{ip}', - aaaa: '{ip}', - cname: '{alias}', - mx: '{preference} {host}', - ns: '{host}', - soa: '{mname} {rname} {serial} {retry} {refresh} {expire} {minimum}', - spf: '{data}', - srv: '{priority} {weight} {port} {target}', - txt: '{txt}' - }; - - var metadata = { - data: format(typeToZoneFormat[type.toLowerCase()], bindData), - name: bindData.name, - ttl: bindData.ttl - }; - - return new Record(zone, type, metadata); -}; - -/** - * Delete this record by creating a change on your zone. This is a convenience - * method for: - * - * zone.createChange({ - * delete: record - * }, function(err, change, apiResponse) {}); - * - * @resource [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} - * - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/change} callback.change - A {module:dns/change} object. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * record.delete(function(err, change, apiResponse) { - * if (!err) { - * // Delete change modification was created. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * record.delete().then(function(data) { - * var change = data[0]; - * var apiResponse = data[1]; - * }); - */ -Record.prototype.delete = function(callback) { - this.zone_.deleteRecords(this, callback); -}; - -/** - * Serialize the record instance to the format the API expects. - * - * @private - */ -Record.prototype.toJSON = function() { - var recordObject = extend({}, this.metadata, { - type: this.type.toUpperCase() - }); - - if (recordObject.data) { - recordObject.rrdatas = arrify(recordObject.data); - delete recordObject.data; - } - - return recordObject; -}; - -/** - * Convert the record to a string, formatted for a zone file. - * - * @private - * - * @return {string} - */ -Record.prototype.toString = function() { - var json = this.toJSON(); - - return (json.rrdatas || [{}]).map(function(data) { - json.rrdata = data; - return format('{name} {ttl} IN {type} {rrdata}', json); - }).join('\n'); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Record, { - exclude: ['toJSON', 'toString'] -}); - -module.exports = Record; diff --git a/packages/dns/src/zone.js b/packages/dns/src/zone.js deleted file mode 100644 index 3c2821669e0..00000000000 --- a/packages/dns/src/zone.js +++ /dev/null @@ -1,982 +0,0 @@ -/*! - * Copyright 2014 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module dns/zone - */ - -'use strict'; - -var arrify = require('arrify'); -var common = require('@google-cloud/common'); -var exec = require('methmeth'); -var extend = require('extend'); -var fs = require('fs'); -var is = require('is'); -var util = require('util'); -var zonefile = require('dns-zonefile'); - -/** - * @type {module:dns/change} - * @private - */ -var Change = require('./change.js'); - -/** - * @type {module:dns/record} - * @private - */ -var Record = require('./record.js'); - -/** - * A Zone object is used to interact with your project's managed zone. It will - * help you add or delete records, delete your zone, and many other convenience - * methods. - * - * @constructor - * @alias module:dns/zone - * - * @example - * var zone = dns.zone('zone-id'); - */ -function Zone(dns, name) { - var methods = { - /** - * Create a zone. - * - * @param {object} config - See {module:dns#createZone}. - * - * @example - * var config = { - * dnsName: 'example.com.', - * // ... - * }; - * - * zone.create(config, function(err, zone, apiResponse) { - * if (!err) { - * // The zone was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.create(config).then(function(data) { - * var zone = data[0]; - * var apiResponse = data[1]; - * }); - */ - create: true, - - /** - * Check if the zone exists. - * - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this - * request. - * @param {boolean} callback.exists - Whether the zone exists or not. - * - * @example - * zone.exists(function(err, exists) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.exists().then(function(data) { - * var exists = data[0]; - * }); - */ - exists: true, - - /** - * Get a zone if it exists. - * - * You may optionally use this to "get or create" an object by providing an - * object with `autoCreate` set to `true`. Any extra configuration that is - * normally required for the `create` method must be contained within this - * object as well. - * - * @param {options=} options - Configuration object. - * @param {boolean} options.autoCreate - Automatically create the object if - * it does not exist. Default: `false` - * - * @example - * zone.get(function(err, zone, apiResponse) { - * // `zone.metadata` has been populated. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.get().then(function(data) { - * var zone = data[0]; - * var apiResponse = data[1]; - * }); - */ - get: true, - - /** - * Get the metadata for the zone. - * - * @resource [ManagedZones: get API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/get} - * - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?object} callback.metadata - Metadata of the zone from the API. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * zone.getMetadata(function(err, metadata, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.getMetadata().then(function(data) { - * var metadata = data[0]; - * var apiResponse = data[1]; - * }); - */ - getMetadata: true - }; - - common.ServiceObject.call(this, { - parent: dns, - baseUrl: '/managedZones', - id: name, - createMethod: dns.createZone.bind(dns), - methods: methods - }); - - this.name = name; -} - -util.inherits(Zone, common.ServiceObject); - -/** - * Add records to this zone. This is a convenience wrapper around - * {module:dns/zone#createChange}. - * - * @resource [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} - * - * @param {module:dns/record|module:dns/record[]} record - The record objects to - * add. - * @param {?error} callback.err - An API error. - * @param {?module:dns/change} callback.change - A {module:dns/change} object. - * @param {object} callback.apiResponse - Raw API response. - */ -Zone.prototype.addRecords = function(records, callback) { - this.createChange({ - add: records - }, callback); -}; - -/** - * Create a reference to a change object in this zone. - * - * @param {string} id - The change id. - * @return {module:dns/change} - * - * @example - * var change = zone.change('change-id'); - */ -Zone.prototype.change = function(id) { - return new Change(this, id); -}; - -/** - * Create a change of resource record sets for the zone. - * - * @resource [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} - * - * @param {object} config - The configuration object. - * @param {module:dns/record|module:dns/record[]} config.add - Record objects - * to add to this zone. - * @param {module:dns/record|module:dns/record[]} config.delete - Record - * objects to delete from this zone. Be aware that the resource records here - * must match exactly to be deleted. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/change} callback.change - A {module:dns/change} object. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * var oldARecord = zone.record('a', { - * name: 'example.com.', - * data: '1.2.3.4', - * ttl: 86400 - * }); - * - * var newARecord = zone.record('a', { - * name: 'example.com.', - * data: '5.6.7.8', - * ttl: 86400 - * }); - * - * var config = { - * add: newARecord, - * delete: oldARecord - * }; - * - * zone.createChange(config, function(err, change, apiResponse) { - * if (!err) { - * // The change was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.createChange(config).then(function(data) { - * var change = data[0]; - * var apiResponse = data[1]; - * }); - */ -Zone.prototype.createChange = function(config, callback) { - var self = this; - - if (!config || !config.add && !config.delete) { - throw new Error('Cannot create a change with no additions or deletions.'); - } - - var body = extend({}, config, { - additions: arrify(config.add).map(exec('toJSON')), - deletions: arrify(config.delete).map(exec('toJSON')) - }); - - delete body.add; - delete body.delete; - - this.request({ - method: 'POST', - uri: '/changes', - json: body - }, function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - var change = self.change(resp.id); - change.metadata = resp; - - callback(null, change, resp); - }); -}; - -/** - * Delete the zone. - * - * Only empty zones can be deleted. Set options.force to `true` to call - * {module:dns/zone#empty} before deleting the zone. Two API calls will then be - * made (one to empty, another to delete), which means this is not an - * atomic request. - * - * @resource [ManagedZones: delete API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/delete} - * - * @param {object=} options - Configuration object. - * @param {boolean} options.force - Empty the zone before deleting. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * zone.delete(function(err, apiResponse) { - * if (!err) { - * // The zone is now deleted. - * } - * }); - * - * //- - * // Use `force` to first empty the zone before deleting it. - * //- - * zone.delete({ - * force: true - * }, function(err, apiResponse) { - * if (!err) { - * // The zone is now deleted. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.delete().then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Zone.prototype.delete = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - if (options.force) { - this.empty(this.delete.bind(this, callback)); - return; - } - - common.ServiceObject.prototype.delete.call(this, callback); -}; - -/** - * Delete records from this zone. This is a convenience wrapper around - * {module:dns/zone#createChange}. - * - * This method accepts {module:dns/record} objects or string record types in - * its place. This means that you can delete all A records or NS records, etc. - * If used this way, two API requests are made (one to get, then another to - * delete), which means the operation is not atomic and could - * result in unexpected changes. - * - * @resource [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} - * - * @param {module:dns/record|module:dns/record[]|string} record - If given a - * string, it is interpreted as a record type. All records that match that - * type will be retrieved and then deleted. You can also provide a - * {module:dns/record} object or array of objects. - * @param {?error} callback.err - An API error. - * @param {?module:dns/change} callback.change - A {module:dns/change} object. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * var oldARecord = zone.record('a', { - * name: 'example.com.', - * data: '1.2.3.4', - * ttl: 86400 - * }); - * - * var callback = function(err, change, apiResponse) { - * if (!err) { - * // Delete change modification was created. - * } - * }; - * - * zone.deleteRecords(oldARecord, callback); - * - * //- - * // Delete multiple records at once. - * //- - * var oldNs1Record = zone.record('ns', { - * name: 'example.com.', - * data: 'ns-cloud1.googledomains.com.', - * ttl: 86400 - * }); - * - * var oldNs2Record = zone.record('ns', { - * name: 'example.com.', - * data: 'ns-cloud2.googledomains.com.', - * ttl: 86400 - * }); - * - * zone.deleteRecords([ - * oldNs1Record, - * oldNs2Record - * ], callback); - * - * //- - * // Possibly a simpler way to perform the above change is deleting records by - * // type. - * //- - * zone.deleteRecords('ns', callback); - * - * //- - * // You can also delete records of multiple types. - * //- - * zone.deleteRecords(['ns', 'a'], callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.deleteRecords(oldARecord).then(function(data) { - * var change = data[0]; - * var apiResponse = data[1]; - * }); - */ -Zone.prototype.deleteRecords = function(records, callback) { - records = arrify(records); - - if (is.string(records[0])) { - this.deleteRecordsByType_(records, callback); - return; - } - - this.createChange({ - delete: records - }, callback); -}; - -/** - * Emptying your zone means leaving only 'NS' and 'SOA' records. This method - * will first fetch the non-NS and non-SOA records from your zone using - * {module:dns/zone#getRecords}, then use {module:dns/zone#createChange} to - * create a deletion change. - * - * @resource [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} - * - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/change} callback.change - A {module:dns/change} object. - * @param {object} callback.apiResponse - Raw API response. - */ -Zone.prototype.empty = function(callback) { - var self = this; - - this.getRecords(function(err, records) { - if (err) { - callback(err); - return; - } - - var recordsToDelete = records.filter(function(record) { - return record.type !== 'NS' && record.type !== 'SOA'; - }); - - if (recordsToDelete.length === 0) { - callback(); - } else { - self.deleteRecords(recordsToDelete, callback); - } - }); -}; - -/** - * Provide a path to a zone file to copy records into the zone. - * - * @resource [ResourceRecordSets: list API Documentation]{@link https://cloud.google.com/dns/api/v1/resourceRecordSets/list} - * - * @param {string} localPath - The fully qualified path to the zone file. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API or file system error. - * - * @example - * var zoneFilename = '/Users/stephen/zonefile.zone'; - * - * zone.export(zoneFilename, function(err) { - * if (!err) { - * // The zone file was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.export(zoneFilename).then(function() {}); - */ -Zone.prototype.export = function(localPath, callback) { - this.getRecords(function(err, records) { - if (err) { - callback(err); - return; - } - - var stringRecords = records.map(exec('toString')).join('\n'); - - fs.writeFile(localPath, stringRecords, 'utf-8', function(err) { - callback(err || null); - }); - }); -}; - -/** - * Get the list of changes associated with this zone. A change is an atomic - * update to a collection of records. - * - * @resource [Changes: get API Documentation]{@link https://cloud.google.com/dns/api/v1/changes/get} - * - * @param {object=} query - The query object. - * @param {boolean} query.autoPaginate - Have pagination handled automatically. - * Default: true. - * @param {number} query.maxApiCalls - Maximum number of API calls to make. - * @param {number} query.maxResults - Maximum number of results to return. - * @param {string} query.pageToken - The page token. - * @param {string} query.sort - Set to 'asc' for ascending, and 'desc' for - * descending or omit for no sorting. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/change[]} callback.changes - An array of - * {module:dns/change} objects. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * var callback = function(err, changes, nextQuery, apiResponse) { - * // The `metadata` property is populated for you with the metadata at the - * // time of fetching. - * changes[0].metadata; - * - * // However, in cases where you are concerned the metadata could have - * // changed, use the `getMetadata` method. - * changes[0].getMetadata(function(err, metadata) {}); - - * if (nextQuery) { - * // nextQuery will be non-null if there are more results. - * zone.getChanges(nextQuery, callback); - * } - * }; - * - * zone.getChanges(callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.getChanges().then(function(data) { - * var changes = data[0]; - * }); - */ -Zone.prototype.getChanges = function(query, callback) { - var self = this; - - if (is.fn(query)) { - callback = query; - query = {}; - } - - if (query.sort) { - query.sortOrder = query.sort === 'asc' ? 'ascending' : 'descending'; - delete query.sort; - } - - this.request({ - uri: '/changes', - qs: query - }, function(err, resp) { - if (err) { - callback(err, null, null, resp); - return; - } - - var changes = (resp.changes || []).map(function(change) { - var changeInstance = self.change(change.id); - changeInstance.metadata = change; - return changeInstance; - }); - - var nextQuery = null; - if (resp.nextPageToken) { - nextQuery = extend({}, query, { - pageToken: resp.nextPageToken - }); - } - - callback(null, changes, nextQuery, resp); - }); -}; - -/** - * Get the list of {module:dns/change} objects associated with this zone as a - * readable object stream. - * - * @param {object=} query - Configuration object. See - * {module:dns/zone#getChanges} for a complete list of options. - * @return {stream} - * - * @example - * zone.getChangesStream() - * .on('error', console.error) - * .on('data', function(change) { - * // change is a Change object. - * }) - * .on('end', function() { - * // All changes retrieved. - * }); - * - * //- - * // If you anticipate many results, you can end a stream early to prevent - * // unnecessary processing and API requests. - * //- - * zone.getChangesStream() - * .on('data', function(change) { - * this.end(); - * }); - */ -Zone.prototype.getChangesStream = common.paginator.streamify('getChanges'); - -/** - * Get the list of records for this zone. - * - * @resource [ResourceRecordSets: list API Documentation]{@link https://cloud.google.com/dns/api/v1/resourceRecordSets/list} - * - * @param {object=} query - The query object. - * @param {boolean} query.autoPaginate - Have pagination handled automatically. - * Default: true. - * @param {number} query.maxApiCalls - Maximum number of API calls to make. - * @param {number} query.maxResults - Maximum number of results to be returned. - * @param {string} query.name - Restricts the list to return only records with - * this fully qualified domain name. - * @param {string} query.pageToken - The page token. - * @param {string} query.type - Restricts the list to return only records of - * this type. If present, the "name" parameter must also be present. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/record[]} callback.records - An array of - * {module:dns/record} objects. - * @param {object} callback.apiResponse - Raw API response. - * - * @example - * var callback = function(err, records, nextQuery, apiResponse) { - * if (!err) { - * // records is an array of Record objects. - * } - * - * if (nextQuery) { - * zone.getRecords(nextQuery, callback); - * } - * }; - * - * zone.getRecords(callback); - * - * //- - * // Provide a query for further customization. - * //- - * - * // Get the namespace records for example.com. - * var query = { - * name: 'example.com.', - * type: 'NS' - * }; - * - * zone.getRecords(query, callback); - * - * //- - * // If you only want records of a specific type or types, provide them in - * // place of the query object. - * //- - * zone.getRecords('ns', function(err, records) { - * if (!err) { - * // records is an array of NS Record objects in your zone. - * } - * }); - * - * //- - * // You can also specify multiple record types. - * //- - * zone.getRecords(['ns', 'a', 'cname'], function(err, records) { - * if (!err) { - * // records is an array of NS, A, and CNAME records in your zone. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.getRecords(query).then(function(data) { - * var records = data[0]; - * }); - */ -Zone.prototype.getRecords = function(query, callback) { - var self = this; - - if (is.fn(query)) { - callback = query; - query = {}; - } - - if (is.string(query) || is.array(query)) { - var filterByTypes_ = {}; - - // For faster lookups, store the record types the user wants in an object. - arrify(query).forEach(function(type) { - filterByTypes_[type.toUpperCase()] = true; - }); - - query = { - filterByTypes_: filterByTypes_ - }; - } - - var requestQuery = extend({}, query); - delete requestQuery.filterByTypes_; - - this.request({ - uri: '/rrsets', - qs: requestQuery - }, function(err, resp) { - if (err) { - callback(err, null, null, resp); - return; - } - - var records = (resp.rrsets || []).map(function(record) { - return self.record(record.type, record); - }); - - if (query.filterByTypes_) { - records = records.filter(function(record) { - return query.filterByTypes_[record.type]; - }); - } - - var nextQuery = null; - if (resp.nextPageToken) { - nextQuery = extend({}, query, { - pageToken: resp.nextPageToken - }); - } - - callback(null, records, nextQuery, resp); - }); -}; - -/** - * Get the list of {module:dns/record} objects for this zone as a readable - * object stream. - * - * @param {object=} query - Configuration object. See - * {module:dns/zone#getRecords} for a complete list of options. - * @return {stream} - * - * @example - * zone.getRecordsStream() - * .on('error', console.error) - * .on('data', function(record) { - * // record is a Record object. - * }) - * .on('end', function() { - * // All records retrieved. - * }); - * - * //- - * // If you anticipate many results, you can end a stream early to prevent - * // unnecessary processing and API requests. - * //- - * zone.getRecordsStream() - * .on('data', function(change) { - * this.end(); - * }); - */ -Zone.prototype.getRecordsStream = common.paginator.streamify('getRecords'); - -/** - * Copy the records from a zone file into this zone. - * - * @resource [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} - * - * @param {string} localPath - The fully qualified path to the zone file. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API or file system error. - * @param {?module:dns/change} callback.change - A {module:dns/change} object. - * @param {?object} callback.apiResponse - Raw API response. - * - * @example - * var zoneFilename = '/Users/dave/zonefile.zone'; - * - * zone.import(zoneFilename, function(err, change, apiResponse) { - * if (!err) { - * // The change was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.import(zoneFilename).then(function(data) { - * var change = data[0]; - * var apiResponse = data[1]; - * }); - */ -Zone.prototype.import = function(localPath, callback) { - var self = this; - - fs.readFile(localPath, 'utf-8', function(err, file) { - if (err) { - callback(err); - return; - } - - var parsedZonefile = zonefile.parse(file); - var recordTypes = Object.keys(parsedZonefile); - var recordsToCreate = []; - - recordTypes.forEach(function(recordType) { - var recordTypeSet = arrify(parsedZonefile[recordType]); - - recordTypeSet.forEach(function(record) { - recordsToCreate.push(Record.fromZoneRecord_(self, recordType, record)); - }); - }); - - self.addRecords(recordsToCreate, callback); - }); -}; - -/** - * A {module:dns/record} object can be used to construct a record you want to - * add to your zone, or to refer to an existing one. - * - * Note that using this method will not itself make any API requests. You will - * use the object returned in other API calls, for example to add a record to - * your zone or to delete an existing one. - * - * @param {string} type - The type of record to construct or the type of record - * you are referencing. - * @param {object} metadata - The metadata of this record. - * @param {string} metadata.name - The name of the record, e.g. - * `www.example.com.`. - * @param {string[]} metadata.data - Defined in - * [RFC 1035, section 5](https://goo.gl/9EiM0e) and - * [RFC 1034, section 3.6.1](https://goo.gl/Hwhsu9). - * @param {number} metadata.ttl - Seconds that the resource is cached by - * resolvers. - * @return {module:dns/record} - * - * @example - * //- - * // Reference an existing record to delete from your zone. - * //- - * var oldARecord = zone.record('a', { - * name: 'example.com.', - * data: '1.2.3.4', - * ttl: 86400 - * }); - * - * //- - * // Construct a record to add to your zone. - * //- - * var newARecord = zone.record('a', { - * name: 'example.com.', - * data: '5.6.7.8', - * ttl: 86400 - * }); - * - * //- - * // Use these records together to create a change. - * //- - * zone.createChange({ - * add: newARecord, - * delete: oldARecord - * }, function(err, change, apiResponse) {}); - */ -Zone.prototype.record = function(type, metadata) { - return new Record(this, type, metadata); -}; - -/** - * Provide a record type that should be deleted and replaced with other records. - * - * This is not an atomic request. Two API requests are made - * (one to get records of the type that you've requested, then another to - * replace them), which means the operation is not atomic and could result in - * unexpected changes. - * - * @resource [ManagedZones: create API Documentation]{@link https://cloud.google.com/dns/api/v1/managedZones/create} - * - * @param {string|string[]} recordTypes - Type(s) of records to replace. - * @param {module:dns/record|module:dns/record[]} newRecords - The record - * objects to add. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/change} callback.change - A {module:dns/change} object. - * @param {?object} callback.apiResponse - Raw API response. - * - * @example - * var newNs1Record = zone.record('ns', { - * name: 'example.com.', - * data: 'ns-cloud1.googledomains.com.', - * ttl: 86400 - * }); - * - * var newNs2Record = zone.record('ns', { - * name: 'example.com.', - * data: 'ns-cloud2.googledomains.com.', - * ttl: 86400 - * }); - * - * var newNsRecords = [ - * newNs1Record, - * newNs2Record - * ]; - * - * zone.replaceRecords('ns', newNsRecords, function(err, change, apiResponse) { - * if (!err) { - * // The change was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * zone.replaceRecords('ns', newNsRecords).then(function(data) { - * var change = data[0]; - * var apiResponse = data[1]; - * }); - */ -Zone.prototype.replaceRecords = function(recordType, newRecords, callback) { - var self = this; - - this.getRecords(recordType, function(err, recordsToDelete) { - if (err) { - callback(err); - return; - } - - self.createChange({ - add: newRecords, - delete: recordsToDelete - }, callback); - }); -}; - -/** - * Delete records from the zone matching an array of types. - * - * @private - * - * @param {string[]} recordTypes - Types of records to delete. Ex: 'NS', 'A'. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An API error. - * @param {?module:dns/change} callback.change - A {module:dns/change} object. - * @param {?object} callback.apiResponse - Raw API response. - * - * @example - * zone.deleteRecordsByType_(['NS', 'A'], function(err, change, apiResponse) { - * if (!err) { - * // The change was created successfully. - * } - * }); - */ -Zone.prototype.deleteRecordsByType_ = function(recordTypes, callback) { - var self = this; - - this.getRecords(recordTypes, function(err, records) { - if (err) { - callback(err); - return; - } - - if (records.length === 0) { - callback(); - return; - } - - self.deleteRecords(records, callback); - }); -}; - -/*! Developer Documentation - * - * These methods can be auto-paginated. - */ -common.paginator.extend(Zone, ['getChanges', 'getRecords']); - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Zone, { - exclude: ['change', 'record'] -}); - -module.exports = Zone; diff --git a/packages/dns/system-test/data/zonefile.zone b/packages/dns/system-test/data/zonefile.zone deleted file mode 100644 index 9b123e1c583..00000000000 --- a/packages/dns/system-test/data/zonefile.zone +++ /dev/null @@ -1,2 +0,0 @@ -{DNS_DOMAIN} 21600 IN SPF "v=spf1" "mx:{DNS_DOMAIN}" "-all" -{DNS_DOMAIN} 21600 IN TXT "google-site-verification=xxxxxxxxxxxxYYYYYYXXX" diff --git a/packages/dns/system-test/dns.js b/packages/dns/system-test/dns.js deleted file mode 100644 index 4aeab6214d0..00000000000 --- a/packages/dns/system-test/dns.js +++ /dev/null @@ -1,376 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var assert = require('assert'); -var async = require('async'); -var exec = require('methmeth'); -var format = require('string-format-obj'); -var fs = require('fs'); -var tmp = require('tmp'); -var uuid = require('uuid'); - -var DNS = require('../'); -var env = require('../../../system-test/env.js'); - -var dns = new DNS(env); -var DNS_DOMAIN = process.env.GCLOUD_TESTS_DNS_DOMAIN; - -// Only run the tests if there is a domain to test with. -(DNS_DOMAIN ? describe : describe.skip)('dns', function() { - if (!DNS_DOMAIN) { - // The test runner still executes this function, even if it is skipped. - return; - } - - var ZONE_NAME = 'test-zone-' + uuid.v4().substr(0, 18); - var ZONE = dns.zone(ZONE_NAME); - - var records = { - a: ZONE.record('a', { - ttl: 86400, - name: DNS_DOMAIN, - data: '1.2.3.4' - }), - - aaaa: ZONE.record('aaaa', { - ttl: 86400, - name: DNS_DOMAIN, - data: '2607:f8b0:400a:801::1005' - }), - - cname: ZONE.record('cname', { - ttl: 86400, - name: 'mail.' + DNS_DOMAIN, - data: 'example.com.' - }), - - mx: ZONE.record('mx', { - ttl: 86400, - name: DNS_DOMAIN, - data: [ - '10 mail.' + DNS_DOMAIN, - '20 mail2.' + DNS_DOMAIN - ] - }), - - naptr: ZONE.record('naptr', { - ttl: 300, - name: '2.1.2.1.5.5.5.0.7.7.1.e164.arpa.', - data: [ - '100 10 \"u\" \"sip+E2U\" \"!^.*$!sip:information@foo.se!i\" .', - '102 10 \"u\" \"smtp+E2U\" \"!^.*$!mailto:information@foo.se!i\" .' - ] - }), - - ns: ZONE.record('ns', { - ttl: 86400, - name: DNS_DOMAIN, - data: 'ns-cloud1.googledomains.com.' - }), - - ptr: ZONE.record('ptr', { - ttl: 60, - name: '2.1.0.10.in-addr.arpa.', - data: 'server.' + DNS_DOMAIN - }), - - soa: ZONE.record('soa', { - ttl: 21600, - name: DNS_DOMAIN, - data: [ - 'ns-cloud1.googledomains.com.', - 'dns-admin.google.com.', - '1 21600 3600 1209600 300' - ].join(' ') - }), - - spf: ZONE.record('spf', { - ttl: 21600, - name: DNS_DOMAIN, - data: 'v=spf1 mx:' + DNS_DOMAIN.replace(/.$/, '') + ' -all' - }), - - srv: ZONE.record('srv', { - ttl: 21600, - name: 'sip.' + DNS_DOMAIN, - data: '0 5 5060 sip.' + DNS_DOMAIN - }), - - txt: ZONE.record('txt', { - ttl: 21600, - name: DNS_DOMAIN, - data: 'google-site-verification=xxxxxxxxxxxxYYYYYYXXX' - }) - }; - - before(function(done) { - dns.getZones(function(err, zones) { - if (err) { - done(err); - return; - } - - async.each(zones, exec('delete', { force: true }), function(err) { - if (err) { - done(err); - return; - } - - ZONE.create({ dnsName: DNS_DOMAIN }, done); - }); - }); - }); - - after(function(done) { - ZONE.delete({ force: true }, done); - }); - - it('should return 0 or more zones', function(done) { - dns.getZones(function(err, zones) { - assert.ifError(err); - assert(zones.length >= 0); - done(); - }); - }); - - describe('Zones', function() { - it('should get the metadata for a zone', function(done) { - ZONE.getMetadata(function(err, metadata) { - assert.ifError(err); - assert.equal(metadata.name, ZONE_NAME); - done(); - }); - }); - - it('should support all types of records', function(done) { - var recordsToCreate = [ - records.a, - records.aaaa, - records.cname, - records.mx, - // records.naptr, - records.ns, - // records.ptr, - records.soa, - records.spf, - records.srv, - records.txt - ]; - - ZONE.replaceRecords(['ns', 'soa'], recordsToCreate, done); - }); - - it('should import records from a zone file', function(done) { - var zoneFilename = require.resolve('./data/zonefile.zone'); - var zoneFileTemplate = fs.readFileSync(zoneFilename, 'utf-8'); - zoneFileTemplate = format(zoneFileTemplate, { - DNS_DOMAIN: DNS_DOMAIN - }); - - tmp.setGracefulCleanup(); - tmp.file(function _tempFileCreated(err, tmpFilePath) { - assert.ifError(err); - - fs.writeFileSync(tmpFilePath, zoneFileTemplate, 'utf-8'); - - ZONE.empty(function(err) { - assert.ifError(err); - - ZONE.import(tmpFilePath, function(err) { - assert.ifError(err); - - ZONE.getRecords(['spf', 'txt'], function(err, records) { - assert.ifError(err); - - var spfRecord = records.filter(function(record) { - return record.type === 'SPF'; - })[0]; - - assert.strictEqual( - spfRecord.toJSON().rrdatas[0], - '"v=spf1" "mx:' + DNS_DOMAIN + '" "-all"' - ); - - var txtRecord = records.filter(function(record) { - return record.type === 'TXT'; - })[0]; - - assert.strictEqual( - txtRecord.toJSON().rrdatas[0], - '"google-site-verification=xxxxxxxxxxxxYYYYYYXXX"' - ); - - done(); - }); - }); - }); - }); - }); - - it('should export records to a zone file', function(done) { - tmp.setGracefulCleanup(); - tmp.file(function tempFileCreated(err, tmpFilename) { - assert.ifError(err); - - async.series([ - function(next) { - ZONE.empty(next); - }, - - function(next) { - var recordsToCreate = [ - records.spf, - records.srv - ]; - - ZONE.addRecords(recordsToCreate, next); - }, - - function(next) { - ZONE.export(tmpFilename, next); - } - ], done); - }); - }); - - describe('changes', function() { - it('should create a change', function(done) { - var record = ZONE.record('srv', { - ttl: 3600, - name: DNS_DOMAIN, - data: '10 0 5222 127.0.0.1.' - }); - - var change = ZONE.change(); - - change.create({ add: record }, function(err) { - assert.ifError(err); - - var addition = change.metadata.additions[0]; - delete addition.kind; - assert.deepEqual(addition, record.toJSON()); - - done(); - }); - }); - - it('should get a list of changes', function(done) { - ZONE.getChanges(function(err, changes) { - assert.ifError(err); - assert(changes.length >= 0); - done(); - }); - }); - - it('should get metadata', function(done) { - ZONE.getChanges(function(err, changes) { - assert.ifError(err); - - var change = changes[0]; - var expectedMetadata = change.metadata; - - change.getMetadata(function(err, metadata) { - assert.ifError(err); - - delete metadata.status; - delete expectedMetadata.status; - assert.deepEqual(metadata, expectedMetadata); - - done(); - }); - }); - }); - }); - }); - - describe('Records', function() { - it('should return 0 or more records', function(done) { - ZONE.getRecords(function(err, records) { - assert.ifError(err); - assert(records.length >= 0); - done(); - }); - }); - - it('should cursor through records by type', function(done) { - var newRecords = [ - ZONE.record('cname', { - ttl: 86400, - name: '1.' + DNS_DOMAIN, - data: DNS_DOMAIN - }), - ZONE.record('cname', { - ttl: 86400, - name: '2.' + DNS_DOMAIN, - data: DNS_DOMAIN - }) - ]; - - ZONE.replaceRecords('cname', newRecords, function(err) { - assert.ifError(err); - - function onRecordsReceived(err, records, nextQuery) { - if (nextQuery) { - ZONE.getRecords(nextQuery, onRecordsReceived); - return; - } - - ZONE.deleteRecords(newRecords, done); - } - - ZONE.getRecords({ - types: 'cname', - maxResults: 2 - }, onRecordsReceived); - }); - }); - - it('should replace records', function(done) { - var name = 'test-zone-' + uuid.v4().substr(0, 18); - - // Do this in a new zone so no existing records are affected. - dns.createZone(name, { dnsName: DNS_DOMAIN }, function(err, zone) { - assert.ifError(err); - - zone.getRecords('ns', function(err, originalRecords) { - assert.ifError(err); - - var originalData = originalRecords[0].data; - - var newRecord = zone.record('ns', { - ttl: 3600, - name: DNS_DOMAIN, - data: ['ns1.nameserver.net.', 'ns2.nameserver.net.'] - }); - - zone.replaceRecords('ns', newRecord, function(err, change) { - assert.ifError(err); - - var deleted = change.metadata.deletions[0].rrdatas; - var added = change.metadata.additions[0].rrdatas; - - assert.deepEqual(deleted, originalData); - assert.deepEqual(added, newRecord.data); - - done(); - }); - }); - }); - }); - }); -}); diff --git a/packages/dns/test/change.js b/packages/dns/test/change.js deleted file mode 100644 index 8dd02417852..00000000000 --- a/packages/dns/test/change.js +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var assert = require('assert'); -var extend = require('extend'); -var nodeutil = require('util'); -var proxyquire = require('proxyquire'); -var ServiceObject = require('@google-cloud/common').ServiceObject; -var util = require('@google-cloud/common').util; - -var promisified = false; -var fakeUtil = extend({}, util, { - promisifyAll: function(Class) { - if (Class.name === 'Change') { - promisified = true; - } - } -}); - -function FakeServiceObject() { - this.calledWith_ = arguments; - ServiceObject.apply(this, arguments); -} - -nodeutil.inherits(FakeServiceObject, ServiceObject); - -describe('Change', function() { - var Change; - var change; - - var ZONE = { - name: 'zone-name', - createChange: util.noop - }; - - var CHANGE_ID = 'change-id'; - - before(function() { - Change = proxyquire('../src/change.js', { - '@google-cloud/common': { - ServiceObject: FakeServiceObject, - util: fakeUtil - } - }); - }); - - beforeEach(function() { - change = new Change(ZONE, CHANGE_ID); - }); - - describe('instantiation', function() { - it('should inherit from ServiceObject', function() { - assert(change instanceof ServiceObject); - - var calledWith = change.calledWith_[0]; - - assert.strictEqual(calledWith.parent, ZONE); - assert.strictEqual(calledWith.baseUrl, '/changes'); - assert.strictEqual(calledWith.id, CHANGE_ID); - assert.deepEqual(calledWith.methods, { - exists: true, - get: true, - getMetadata: true - }); - }); - - it('should promisify all the things', function() { - assert(promisified); - }); - }); - - describe('change', function() { - it('should call the parent change method', function(done) { - var config = {}; - - change.parent.createChange = function(config_) { - assert.strictEqual(config, config_); - done(); - }; - - change.create(config, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = {}; - - beforeEach(function() { - change.parent.createChange = function(config, callback) { - callback(error, null, apiResponse); - }; - }); - - it('should execute callback with error & apiResponse', function(done) { - change.create({}, function(err, change, apiResponse_) { - assert.strictEqual(err, error); - assert.strictEqual(change, null); - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - }); - - describe('success', function() { - var changeInstance = { - id: 'id', - metadata: {} - }; - var apiResponse = {}; - - beforeEach(function() { - change.parent.createChange = function(config, callback) { - callback(null, changeInstance, apiResponse); - }; - }); - - it('should execute callback with self & API response', function(done) { - change.create({}, function(err, change_, apiResponse_) { - assert.ifError(err); - - assert.strictEqual(change_, change); - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - - it('should assign the ID and metadata from the change', function(done) { - change.create({}, function(err, change_) { - assert.ifError(err); - - assert.strictEqual(change_.id, changeInstance.id); - assert.strictEqual(change_.metadata, changeInstance.metadata); - - done(); - }); - }); - }); - }); -}); diff --git a/packages/dns/test/index.js b/packages/dns/test/index.js deleted file mode 100644 index 938535492b4..00000000000 --- a/packages/dns/test/index.js +++ /dev/null @@ -1,391 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var arrify = require('arrify'); -var assert = require('assert'); -var extend = require('extend'); -var nodeutil = require('util'); -var proxyquire = require('proxyquire'); -var Service = require('@google-cloud/common').Service; -var util = require('@google-cloud/common').util; - -var extended = false; -var fakePaginator = { - extend: function(Class, methods) { - if (Class.name !== 'DNS') { - return; - } - - extended = true; - methods = arrify(methods); - assert.equal(Class.name, 'DNS'); - assert.deepEqual(methods, ['getZones']); - }, - streamify: function(methodName) { - return methodName; - } -}; - -function FakeService() { - this.calledWith_ = arguments; - Service.apply(this, arguments); -} - -nodeutil.inherits(FakeService, Service); - -var promisified = false; -var fakeUtil = extend({}, util, { - makeAuthenticatedRequestFactory: util.noop, - promisifyAll: function(Class, options) { - if (Class.name !== 'DNS') { - return; - } - - promisified = true; - assert.deepEqual(options.exclude, ['zone']); - } -}); - -function FakeZone() { - this.calledWith_ = arguments; -} - -describe('DNS', function() { - var DNS; - var dns; - - var PROJECT_ID = 'project-id'; - - before(function() { - DNS = proxyquire('../', { - '@google-cloud/common': { - Service: FakeService, - paginator: fakePaginator, - util: fakeUtil - }, - './zone.js': FakeZone - }); - }); - - beforeEach(function() { - dns = new DNS({ - projectId: PROJECT_ID - }); - }); - - describe('instantiation', function() { - it('should extend the correct methods', function() { - assert(extended); // See `fakePaginator.extend` - }); - - it('should streamify the correct methods', function() { - assert.strictEqual(dns.getZonesStream, 'getZones'); - }); - - it('should promisify all the things', function() { - assert(promisified); - }); - - it('should normalize the arguments', function() { - var normalizeArguments = fakeUtil.normalizeArguments; - var normalizeArgumentsCalled = false; - var fakeOptions = { projectId: PROJECT_ID }; - var fakeContext = {}; - - fakeUtil.normalizeArguments = function(context, options) { - normalizeArgumentsCalled = true; - assert.strictEqual(context, fakeContext); - assert.strictEqual(options, fakeOptions); - return options; - }; - - DNS.call(fakeContext, fakeOptions); - assert(normalizeArgumentsCalled); - - fakeUtil.normalizeArguments = normalizeArguments; - }); - - it('should inherit from Service', function() { - assert(dns instanceof Service); - - var calledWith = dns.calledWith_[0]; - - var baseUrl = 'https://www.googleapis.com/dns/v1'; - assert.strictEqual(calledWith.baseUrl, baseUrl); - assert.deepEqual(calledWith.scopes, [ - 'https://www.googleapis.com/auth/ndev.clouddns.readwrite', - 'https://www.googleapis.com/auth/cloud-platform' - ]); - assert.deepEqual(calledWith.packageJson, require('../package.json')); - }); - }); - - describe('createZone', function() { - var zoneName = 'zone-name'; - var config = { dnsName: 'dns-name' }; - - it('should throw if a zone name is not provided', function() { - assert.throws(function() { - dns.createZone(); - }, /A zone name is required/); - }); - - it('should throw if a zone dnsname is not provided', function() { - assert.throws(function() { - dns.createZone(zoneName); - }, /A zone dnsName is required/); - - assert.throws(function() { - dns.createZone(zoneName, {}); - }, /A zone dnsName is required/); - }); - - it('should use a provided description', function(done) { - var cfg = extend({}, config, { description: 'description' }); - - dns.request = function(reqOpts) { - assert.strictEqual(reqOpts.json.description, cfg.description); - done(); - }; - - dns.createZone(zoneName, cfg, assert.ifError); - }); - - it('should default a description to ""', function(done) { - dns.request = function(reqOpts) { - assert.strictEqual(reqOpts.json.description, ''); - done(); - }; - - dns.createZone(zoneName, config, assert.ifError); - }); - - it('should make the correct API request', function(done) { - dns.request = function(reqOpts) { - assert.strictEqual(reqOpts.method, 'POST'); - assert.strictEqual(reqOpts.uri, '/managedZones'); - - var expectedBody = extend({}, config, { - name: zoneName, - description: '' - }); - assert.deepEqual(reqOpts.json, expectedBody); - - done(); - }; - - dns.createZone(zoneName, config, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = { a: 'b', c: 'd' }; - - beforeEach(function() { - dns.request = function(reqOpts, callback) { - callback(error, apiResponse); - }; - }); - - it('should execute callback with error and API response', function(done) { - dns.createZone(zoneName, config, function(err, zone, apiResponse_) { - assert.strictEqual(err, error); - assert.strictEqual(zone, null); - assert.strictEqual(apiResponse_, apiResponse); - done(); - }); - }); - }); - - describe('success', function() { - var apiResponse = { name: zoneName }; - var zone = {}; - - beforeEach(function() { - dns.request = function(reqOpts, callback) { - callback(null, apiResponse); - }; - - dns.zone = function() { - return zone; - }; - }); - - it('should create a zone from the response', function(done) { - dns.zone = function(name) { - assert.strictEqual(name, apiResponse.name); - setImmediate(done); - return zone; - }; - - dns.createZone(zoneName, config, assert.ifError); - }); - - it('should execute callback with zone and API response', function(done) { - dns.createZone(zoneName, config, function(err, zone_, apiResponse_) { - assert.ifError(err); - assert.strictEqual(zone_, zone); - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - - it('should set the metadata to the response', function(done) { - dns.createZone(zoneName, config, function(err, zone) { - assert.strictEqual(zone.metadata, apiResponse); - done(); - }); - }); - }); - }); - - describe('getZones', function() { - it('should make the correct request', function(done) { - var query = { a: 'b', c: 'd' }; - - dns.request = function(reqOpts) { - assert.strictEqual(reqOpts.uri, '/managedZones'); - assert.strictEqual(reqOpts.qs, query); - - done(); - }; - - dns.getZones(query, assert.ifError); - }); - - it('should use an empty query if one was not provided', function(done) { - dns.request = function(reqOpts) { - assert.equal(Object.keys(reqOpts.qs).length, 0); - done(); - }; - - dns.getZones(assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = { a: 'b', c: 'd' }; - - beforeEach(function() { - dns.request = function(reqOpts, callback) { - callback(error, apiResponse); - }; - }); - - it('should execute callback with error and API response', function(done) { - dns.getZones({}, function(err, zones, nextQuery, apiResponse_) { - assert.strictEqual(err, error); - assert.strictEqual(zones, null); - assert.strictEqual(nextQuery, null); - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - }); - - describe('success', function() { - var zone = { name: 'zone-1', a: 'b', c: 'd' }; - var apiResponse = { managedZones: [zone] }; - - beforeEach(function() { - dns.request = function(reqOpts, callback) { - callback(null, apiResponse); - }; - - dns.zone = function() { - return zone; - }; - }); - - it('should create zones from the response', function(done) { - dns.zone = function(zoneName) { - assert.strictEqual(zoneName, zone.name); - setImmediate(done); - return zone; - }; - - dns.getZones({}, assert.ifError); - }); - - it('should set a nextQuery if necessary', function(done) { - var apiResponseWithNextPageToken = extend({}, apiResponse, { - nextPageToken: 'next-page-token' - }); - - var query = { a: 'b', c: 'd' }; - var originalQuery = extend({}, query); - - dns.request = function(reqOpts, callback) { - callback(null, apiResponseWithNextPageToken); - }; - - dns.getZones(query, function(err, zones, nextQuery) { - assert.ifError(err); - - // Check the original query wasn't modified. - assert.deepEqual(query, originalQuery); - - assert.deepEqual(nextQuery, extend({}, query, { - pageToken: apiResponseWithNextPageToken.nextPageToken - })); - - done(); - }); - }); - - it('should execute callback with zones and API response', function(done) { - dns.getZones({}, function(err, zones, nextQuery, apiResponse_) { - assert.ifError(err); - - assert.strictEqual(zones[0], zone); - assert.strictEqual(nextQuery, null); - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - - it('should assign metadata to zones', function(done) { - dns.getZones({}, function(err, zones) { - assert.ifError(err); - assert.strictEqual(zones[0].metadata, zone); - done(); - }); - }); - }); - }); - - describe('zone', function() { - it('should throw if a name is not provided', function() { - assert.throws(function() { - dns.zone(); - }, /A zone name is required/); - }); - - it('should return a Zone', function() { - var newZoneName = 'new-zone-name'; - var newZone = dns.zone(newZoneName); - - assert(newZone instanceof FakeZone); - assert.strictEqual(newZone.calledWith_[0], dns); - assert.strictEqual(newZone.calledWith_[1], newZoneName); - }); - }); -}); diff --git a/packages/dns/test/record.js b/packages/dns/test/record.js deleted file mode 100644 index 1b80afa4d74..00000000000 --- a/packages/dns/test/record.js +++ /dev/null @@ -1,355 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var assert = require('assert'); -var extend = require('extend'); -var proxyquire = require('proxyquire'); -var util = require('@google-cloud/common').util; - -var promisified = false; -var fakeUtil = extend({}, util, { - promisifyAll: function(Class, options) { - if (Class.name !== 'Record') { - return; - } - - promisified = true; - assert.deepEqual(options.exclude, ['toJSON', 'toString']); - } -}); - -describe('Record', function() { - var Record; - var record; - - var ZONE = { - deleteRecords: util.noop - }; - var TYPE = 'A'; - var METADATA = { - name: 'name', - data: [], - ttl: 86400 - }; - - before(function() { - Record = proxyquire('../src/record.js', { - '@google-cloud/common': { - util: fakeUtil - } - }); - }); - - beforeEach(function() { - record = new Record(ZONE, TYPE, METADATA); - }); - - describe('instantiation', function() { - it('should promisify all the things', function() { - assert(promisified); - }); - - it('should localize the zone instance', function() { - assert.strictEqual(record.zone_, ZONE); - }); - - it('should localize the type', function() { - assert.strictEqual(record.type, TYPE); - }); - - it('should localize the metadata', function() { - assert.strictEqual(record.metadata, METADATA); - }); - - it('should assign the parsed metadata', function() { - var parsedMetadata = record.toJSON(); - delete parsedMetadata.rrdatas; - - for (var prop in parsedMetadata) { - assert.strictEqual(record[prop], parsedMetadata[prop]); - } - }); - - it('should re-assign rrdatas to data', function() { - var originalRrdatas = []; - - var recordThatHadRrdatas = new Record(ZONE, TYPE, { - rrdatas: originalRrdatas - }); - - assert.strictEqual(recordThatHadRrdatas.rrdatas, undefined); - assert.strictEqual(recordThatHadRrdatas.data, originalRrdatas); - }); - }); - - describe('fromZoneRecord_', function() { - describe('a', function() { - var aRecord = { - ip: '0.0.0.0', - name: 'name', - ttl: 86400 - }; - - var expectedData = aRecord.ip; - - it('should parse an A record', function() { - var record = Record.fromZoneRecord_(ZONE, 'a', aRecord); - - assert.strictEqual(record.type, 'A'); - assert.deepEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, aRecord.name); - assert.strictEqual(record.metadata.ttl, aRecord.ttl); - }); - }); - - describe('aaaa', function() { - var aaaaRecord = { - ip: '2607:f8b0:400a:801::1005', - name: 'name', - ttl: 86400 - }; - - var expectedData = aaaaRecord.ip; - - it('should parse an AAAA record', function() { - var record = Record.fromZoneRecord_(ZONE, 'aaaa', aaaaRecord); - - assert.strictEqual(record.type, 'AAAA'); - assert.strictEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, aaaaRecord.name); - assert.strictEqual(record.metadata.ttl, aaaaRecord.ttl); - }); - }); - - describe('cname', function() { - var cnameRecord = { - alias: 'example.com.', - name: 'name', - ttl: 86400 - }; - - var expectedData = cnameRecord.alias; - - it('should parse a CNAME record', function() { - var record = Record.fromZoneRecord_(ZONE, 'cname', cnameRecord); - - assert.strictEqual(record.type, 'CNAME'); - assert.strictEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, cnameRecord.name); - assert.strictEqual(record.metadata.ttl, cnameRecord.ttl); - }); - }); - - describe('mx', function() { - var mxRecord = { - preference: 0, - host: 'mail', - name: 'name', - ttl: 86400 - }; - - var expectedData = mxRecord.preference + ' ' + mxRecord.host; - - it('should parse an MX record', function() { - var record = Record.fromZoneRecord_(ZONE, 'mx', mxRecord); - - assert.strictEqual(record.type, 'MX'); - assert.strictEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, mxRecord.name); - assert.strictEqual(record.metadata.ttl, mxRecord.ttl); - }); - }); - - describe('ns', function() { - var nsRecord = { - host: 'example.com', - name: 'name', - ttl: 86400 - }; - - var expectedData = nsRecord.host; - - it('should parse an NS record', function() { - var record = Record.fromZoneRecord_(ZONE, 'ns', nsRecord); - - assert.strictEqual(record.type, 'NS'); - assert.strictEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, nsRecord.name); - assert.strictEqual(record.metadata.ttl, nsRecord.ttl); - }); - }); - - describe('soa', function() { - var soaRecord = { - mname: 'ns1.nameserver.net.', - rname: 'hostmaster.mydomain.com.', - serial: 86400, - retry: 600, - refresh: 3600, - expire: 604800, - minimum: 86400, - name: 'name', - ttl: 86400 - }; - - var expectedData = [ - soaRecord.mname, - soaRecord.rname, - soaRecord.serial, - soaRecord.retry, - soaRecord.refresh, - soaRecord.expire, - soaRecord.minimum - ].join(' '); - - it('should parse an SOA record', function() { - var record = Record.fromZoneRecord_(ZONE, 'soa', soaRecord); - - assert.strictEqual(record.type, 'SOA'); - assert.strictEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, soaRecord.name); - assert.strictEqual(record.metadata.ttl, soaRecord.ttl); - }); - }); - - describe('spf', function() { - var spfRecord = { - data: '"v=spf1" "mx:example.com"', - name: 'name', - ttl: 86400 - }; - - var expectedData = spfRecord.data; - - it('should parse an SPF record', function() { - var record = Record.fromZoneRecord_(ZONE, 'spf', spfRecord); - - assert.strictEqual(record.type, 'SPF'); - assert.strictEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, spfRecord.name); - assert.strictEqual(record.metadata.ttl, spfRecord.ttl); - }); - }); - - describe('srv', function() { - var srvRecord = { - priority: 10, - weight: 0, - port: 5222, - target: 'jabber', - name: 'name', - ttl: 86400 - }; - - var expectedData = [ - srvRecord.priority, - srvRecord.weight, - srvRecord.port, - srvRecord.target - ].join(' '); - - it('should parse an SRV record', function() { - var record = Record.fromZoneRecord_(ZONE, 'srv', srvRecord); - - assert.strictEqual(record.type, 'SRV'); - assert.strictEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, srvRecord.name); - assert.strictEqual(record.metadata.ttl, srvRecord.ttl); - }); - }); - - describe('txt', function() { - var txtRecord = { - txt: 'txt-record-txt', - name: 'name', - ttl: 86400 - }; - - var expectedData = txtRecord.txt; - - it('should parse a TXT record', function() { - var record = Record.fromZoneRecord_(ZONE, 'txt', txtRecord); - - assert.strictEqual(record.type, 'TXT'); - assert.strictEqual(record.metadata.data, expectedData); - assert.strictEqual(record.metadata.name, txtRecord.name); - assert.strictEqual(record.metadata.ttl, txtRecord.ttl); - }); - }); - }); - - describe('delete', function() { - it('should call zone.deleteRecords', function(done) { - record.zone_.deleteRecords = function(records, callback) { - assert.strictEqual(records, record); - callback(); - }; - - record.delete(done); - }); - }); - - describe('toJSON', function() { - it('should format the data for the API', function() { - var expectedRecord = extend({}, METADATA, { - type: 'A', - rrdatas: METADATA.data - }); - delete expectedRecord.data; - - assert.deepEqual(record.toJSON(), expectedRecord); - }); - }); - - describe('toString', function() { - it('should format the data for a zonefile', function() { - var jsonRecord = extend({}, METADATA, { - type: TYPE, - rrdatas: ['example.com.', 'example2.com.'] - }); - - record.toJSON = function() { - return jsonRecord; - }; - - var expectedRecordString = [ - [ - jsonRecord.name, - jsonRecord.ttl, - 'IN', - TYPE, - jsonRecord.rrdatas[0] - ].join(' '), - - [ - jsonRecord.name, - jsonRecord.ttl, - 'IN', - TYPE, - jsonRecord.rrdatas[1] - ].join(' ') - ].join('\n'); - - // That's a bunch of silliness, but it generates simply: - // name 86400 IN A example.com. - // name 86400 IN A example2.com. - - assert.strictEqual(record.toString(), expectedRecordString); - }); - }); -}); diff --git a/packages/dns/test/zone.js b/packages/dns/test/zone.js deleted file mode 100644 index 195fd5e5e2e..00000000000 --- a/packages/dns/test/zone.js +++ /dev/null @@ -1,946 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var arrify = require('arrify'); -var assert = require('assert'); -var extend = require('extend'); -var nodeutil = require('util'); -var proxyquire = require('proxyquire'); -var ServiceObject = require('@google-cloud/common').ServiceObject; -var util = require('@google-cloud/common').util; - -var promisified = false; -var fakeUtil = extend({}, util, { - promisifyAll: function(Class, options) { - if (Class.name !== 'Zone') { - return; - } - - promisified = true; - assert.deepEqual(options.exclude, ['change', 'record']); - } -}); - -var parseOverride; -var fakeDnsZonefile = { - parse: function() { - return (parseOverride || util.noop).apply(null, arguments); - } -}; - -var writeFileOverride; -var readFileOverride; -var fakeFs = { - readFile: function() { - return (readFileOverride || util.noop).apply(null, arguments); - }, - writeFile: function() { - return (writeFileOverride || util.noop).apply(null, arguments); - } -}; - -function FakeChange() { - this.calledWith_ = arguments; -} - -function FakeRecord() { - this.calledWith_ = arguments; -} -FakeRecord.fromZoneRecord_ = function() { - var record = new FakeRecord(); - record.calledWith_ = arguments; - return record; -}; - -function FakeServiceObject() { - this.calledWith_ = arguments; - ServiceObject.apply(this, arguments); -} - -nodeutil.inherits(FakeServiceObject, ServiceObject); - -var extended = false; -var fakePaginator = { - extend: function(Class, methods) { - if (Class.name !== 'Zone') { - return; - } - - extended = true; - methods = arrify(methods); - assert.equal(Class.name, 'Zone'); - assert.deepEqual(methods, ['getChanges', 'getRecords']); - }, - streamify: function(methodName) { - return methodName; - } -}; - -describe('Zone', function() { - var Zone; - var zone; - - var DNS = { - createZone: util.noop - }; - var ZONE_NAME = 'zone-name'; - - before(function() { - Zone = proxyquire('../src/zone.js', { - 'dns-zonefile': fakeDnsZonefile, - fs: fakeFs, - '@google-cloud/common': { - ServiceObject: FakeServiceObject, - paginator: fakePaginator, - util: fakeUtil - }, - './change.js': FakeChange, - './record.js': FakeRecord - }); - }); - - beforeEach(function() { - parseOverride = null; - readFileOverride = null; - writeFileOverride = null; - zone = new Zone(DNS, ZONE_NAME); - }); - - describe('instantiation', function() { - it('should promisify all the things', function() { - assert(promisified); - }); - - it('should extend the correct methods', function() { - assert(extended); // See `fakePaginator.extend` - }); - - it('should streamify the correct methods', function() { - assert.strictEqual(zone.getChangesStream, 'getChanges'); - assert.strictEqual(zone.getRecordsStream, 'getRecords'); - }); - - it('should localize the name', function() { - assert.strictEqual(zone.name, ZONE_NAME); - }); - - it('should inherit from ServiceObject', function(done) { - var dnsInstance = extend({}, DNS, { - createZone: { - bind: function(context) { - assert.strictEqual(context, dnsInstance); - done(); - } - } - }); - - var zone = new Zone(dnsInstance, ZONE_NAME); - assert(zone instanceof ServiceObject); - - var calledWith = zone.calledWith_[0]; - - assert.strictEqual(calledWith.parent, dnsInstance); - assert.strictEqual(calledWith.baseUrl, '/managedZones'); - assert.strictEqual(calledWith.id, ZONE_NAME); - assert.deepEqual(calledWith.methods, { - create: true, - exists: true, - get: true, - getMetadata: true - }); - }); - }); - - describe('addRecords', function() { - it('should create a change with additions', function(done) { - var records = ['a', 'b', 'c']; - - zone.createChange = function(options, callback) { - assert.strictEqual(options.add, records); - callback(); - }; - - zone.addRecords(records, done); - }); - }); - - describe('change', function() { - it('should return a Change object', function() { - var changeId = 'change-id'; - - var change = zone.change(changeId); - - assert(change instanceof FakeChange); - assert.strictEqual(change.calledWith_[0], zone); - assert.strictEqual(change.calledWith_[1], changeId); - }); - }); - - describe('createChange', function() { - it('should throw error if add or delete is not provided', function() { - assert.throws(function() { - zone.createChange({}, util.noop); - }, /Cannot create a change with no additions or deletions/); - }); - - it('should parse and rename add to additions', function(done) { - var recordsToAdd = [ - { toJSON: function() { return 'a'; } }, - { toJSON: function() { return 'a'; } } - ]; - var expectedAdditions = ['a', 'a']; - - zone.request = function(reqOpts) { - assert.strictEqual(reqOpts.json.add, undefined); - assert.deepEqual(reqOpts.json.additions, expectedAdditions); - done(); - }; - - zone.createChange({ add: recordsToAdd }, assert.ifError); - }); - - it('should parse and rename delete to deletions', function(done) { - var recordsToDelete = [ - { toJSON: function() { return 'a'; } }, - { toJSON: function() { return 'a'; } } - ]; - var expectedDeletions = ['a', 'a']; - - zone.request = function(reqOpts) { - assert.strictEqual(reqOpts.json.delete, undefined); - assert.deepEqual(reqOpts.json.deletions, expectedDeletions); - done(); - }; - - zone.createChange({ delete: recordsToDelete }, assert.ifError); - }); - - it('should make correct API request', function(done) { - zone.request = function(reqOpts) { - assert.strictEqual(reqOpts.method, 'POST'); - assert.strictEqual(reqOpts.uri, '/changes'); - - done(); - }; - - zone.createChange({ add: [] }, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = { a: 'b', c: 'd' }; - - beforeEach(function() { - zone.request = function(reqOpts, callback) { - callback(error, apiResponse); - }; - }); - - it('should execute callback with error & API response', function(done) { - zone.createChange({ add: [] }, function(err, change, apiResponse_) { - assert.strictEqual(err, error); - assert.strictEqual(apiResponse_, apiResponse); - done(); - }); - }); - }); - - describe('success', function() { - var apiResponse = { id: 1, a: 'b', c: 'd' }; - - beforeEach(function() { - zone.request = function(reqOpts, callback) { - callback(null, apiResponse); - }; - }); - - it('should execute callback with Change & API response', function(done) { - var change = {}; - - zone.change = function(id) { - assert.strictEqual(id, apiResponse.id); - return change; - }; - - zone.createChange({ add: [] }, function(err, change_, apiResponse_) { - assert.ifError(err); - - assert.strictEqual(change_, change); - assert.strictEqual(change_.metadata, apiResponse); - - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - }); - }); - - describe('delete', function() { - describe('force', function() { - it('should empty the zone', function(done) { - zone.empty = function() { - done(); - }; - - zone.delete({ force: true }, assert.ifError); - }); - - it('should try to delete again after emptying', function(done) { - FakeServiceObject.prototype.delete = function() { - done(); - }; - - zone.empty = function(callback) { - callback(); - }; - - zone.delete({ force: true }, assert.ifError); - }); - }); - - it('should make the correct API request', function(done) { - FakeServiceObject.prototype.delete = function(callback) { - assert.strictEqual(this, zone); - callback(); - }; - - zone.delete(done); - }); - }); - - describe('deleteRecords', function() { - it('should delete records by type if a string is given', function(done) { - var recordsToDelete = 'ns'; - - zone.deleteRecordsByType_ = function(types, callback) { - assert.deepEqual(types, [recordsToDelete]); - callback(); - }; - - zone.deleteRecords(recordsToDelete, done); - }); - - it('should create a change if record objects given', function(done) { - var recordsToDelete = { a: 'b', c: 'd' }; - - zone.createChange = function(options, callback) { - assert.deepEqual(options.delete, [recordsToDelete]); - callback(); - }; - - zone.deleteRecords(recordsToDelete, done); - }); - }); - - describe('empty', function() { - it('should get all records', function(done) { - zone.getRecords = function() { - done(); - }; - - zone.empty(assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - - beforeEach(function() { - zone.getRecords = function(callback) { - callback(error); - }; - }); - - it('should execute callback with error', function(done) { - zone.empty(function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - }); - - describe('success', function() { - var records = [ - { type: 'A' }, - { type: 'AAAA' }, - { type: 'CNAME' }, - { type: 'MX' }, - { type: 'NAPTR' }, - { type: 'NS' }, - { type: 'PTR' }, - { type: 'SOA' }, - { type: 'SPF' }, - { type: 'SRV' }, - { type: 'TXT' } - ]; - - var expectedRecordsToDelete = records.filter(function(record) { - return record.type !== 'NS' && record.type !== 'SOA'; - }); - - beforeEach(function() { - zone.getRecords = function(callback) { - callback(null, records); - }; - }); - - it('should execute callback if no records matched', function(done) { - zone.getRecords = function(callback) { - callback(null, []); - }; - - zone.empty(done); - }); - - it('should delete non-NS and non-SOA records', function(done) { - zone.deleteRecords = function(recordsToDelete, callback) { - assert.deepEqual(recordsToDelete, expectedRecordsToDelete); - callback(); - }; - - zone.empty(done); - }); - }); - }); - - describe('export', function() { - var path = './zonefile'; - - var records = [ - { toString: function() { return 'a'; } }, - { toString: function() { return 'a'; } }, - { toString: function() { return 'a'; } }, - { toString: function() { return 'a'; } }, - ]; - - var expectedZonefileContents = 'a\na\na\na'; - - beforeEach(function() { - zone.getRecords = function(callback) { - callback(null, records); - }; - }); - - describe('get records', function() { - describe('error', function() { - var error = new Error('Error.'); - - it('should execute callback with error', function(done) { - zone.getRecords = function(callback) { - callback(error); - }; - - zone.export(path, function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - }); - - describe('success', function() { - it('should get all records', function(done) { - zone.getRecords = function() { - done(); - }; - - zone.export(path, assert.ifError); - }); - }); - }); - - describe('write file', function() { - it('should write correct zone file', function(done) { - writeFileOverride = function(path_, content, encoding) { - assert.strictEqual(path_, path); - assert.strictEqual(content, expectedZonefileContents); - assert.strictEqual(encoding, 'utf-8'); - - done(); - }; - - zone.export(path, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - - beforeEach(function() { - writeFileOverride = function(path, content, encoding, callback) { - callback(error); - }; - }); - - it('should execute the callback with an error', function(done) { - zone.export(path, function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - }); - - describe('success', function() { - beforeEach(function() { - writeFileOverride = function(path, content, encoding, callback) { - callback(); - }; - }); - - it('should execute the callback', function(done) { - zone.export(path, function(err) { - assert.ifError(err); - done(); - }); - }); - }); - }); - }); - - describe('getChanges', function() { - it('should accept only a callback', function(done) { - zone.request = function(reqOpts) { - assert.deepEqual(reqOpts.qs, {}); - done(); - }; - - zone.getChanges(assert.ifError); - }); - - it('should accept a sort', function(done) { - var query = { sort: 'desc' }; - - zone.request = function(reqOpts) { - assert.strictEqual(reqOpts.qs.sortOrder, 'descending'); - assert.strictEqual(reqOpts.qs.sort, undefined); - - done(); - }; - - zone.getChanges(query, assert.ifError); - }); - - it('should make the correct API request', function(done) { - var query = { a: 'b', c: 'd' }; - - zone.request = function(reqOpts) { - assert.strictEqual(reqOpts.uri, '/changes'); - assert.strictEqual(reqOpts.qs, query); - - done(); - }; - - zone.getChanges(query, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = { a: 'b', c: 'd' }; - - beforeEach(function() { - zone.request = function(reqOpts, callback) { - callback(error, apiResponse); - }; - }); - - it('should execute callback with error & API response', function(done) { - zone.getChanges({}, function(err, changes, nextQuery, apiResponse_) { - assert.strictEqual(err, error); - assert.strictEqual(apiResponse_, apiResponse); - done(); - }); - }); - }); - - describe('success', function() { - var apiResponse = { - changes: [{ id: 1 }] - }; - - beforeEach(function() { - zone.request = function(reqOpts, callback) { - callback(null, apiResponse); - }; - }); - - it('should build a nextQuery if necessary', function(done) { - var nextPageToken = 'next-page-token'; - var apiResponseWithNextPageToken = extend({}, apiResponse, { - nextPageToken: nextPageToken - }); - var expectedNextQuery = { - pageToken: nextPageToken - }; - - zone.request = function(reqOpts, callback) { - callback(null, apiResponseWithNextPageToken); - }; - - zone.getChanges({}, function(err, changes, nextQuery) { - assert.ifError(err); - - assert.deepEqual(nextQuery, expectedNextQuery); - - done(); - }); - }); - - it('should execute callback with Changes & API response', function(done) { - var change = {}; - - zone.change = function(id) { - assert.strictEqual(id, apiResponse.changes[0].id); - return change; - }; - - zone.getChanges({}, function(err, changes, nextQuery, apiResponse_) { - assert.ifError(err); - - assert.strictEqual(changes[0], change); - assert.strictEqual(changes[0].metadata, apiResponse.changes[0]); - - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - }); - }); - - describe('getRecords', function() { - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = { a: 'b', c: 'd' }; - - beforeEach(function() { - zone.request = function(reqOpts, callback) { - callback(error, apiResponse); - }; - }); - - it('should execute callback with error & API response', function(done) { - zone.getRecords({}, function(err, changes, nextQuery, apiResponse_) { - assert.strictEqual(err, error); - assert.strictEqual(apiResponse_, apiResponse); - done(); - }); - }); - - it('should not require a query', function(done) { - zone.getRecords(function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - }); - - describe('success', function() { - var apiResponse = { - rrsets: [{ type: 'NS' }] - }; - - beforeEach(function() { - zone.request = function(reqOpts, callback) { - callback(null, apiResponse); - }; - }); - - it('should execute callback with nextQuery if necessary', function(done) { - var nextPageToken = 'next-page-token'; - var apiResponseWithNextPageToken = extend({}, apiResponse, { - nextPageToken: nextPageToken - }); - var expectedNextQuery = { pageToken: nextPageToken }; - - zone.request = function(reqOpts, callback) { - callback(null, apiResponseWithNextPageToken); - }; - - zone.getRecords({}, function(err, records, nextQuery) { - assert.ifError(err); - - assert.deepEqual(nextQuery, expectedNextQuery); - - done(); - }); - }); - - it('should execute callback with Records & API response', function(done) { - var record = {}; - - zone.record = function(type, recordObject) { - assert.strictEqual(type, apiResponse.rrsets[0].type); - assert.strictEqual(recordObject, apiResponse.rrsets[0]); - return record; - }; - - zone.getRecords({}, function(err, records, nextQuery, apiResponse_) { - assert.ifError(err); - - assert.strictEqual(records[0], record); - - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - - it('should not require a query', function(done) { - zone.getRecords(done); - }); - }); - - describe('filtering', function() { - it('should accept a string type', function(done) { - var types = ['MX', 'CNAME']; - - zone.getRecords(types, function(err, records) { - assert.ifError(err); - - assert.strictEqual(records.length, 0); - - done(); - }); - }); - - it('should accept an array of types', function(done) { - var type = 'MX'; - - zone.getRecords(type, function(err, records) { - assert.ifError(err); - - assert.strictEqual(records.length, 0); - - done(); - }); - }); - - it('should not send filterByTypes_ in API request', function(done) { - zone.request = function(reqOpts) { - assert.strictEqual(reqOpts.qs.filterByTypes_, undefined); - done(); - }; - - zone.getRecords('NS', assert.ifError); - }); - }); - }); - }); - - describe('import', function() { - var path = './zonefile'; - - it('should read from the file', function(done) { - readFileOverride = function(path_, encoding) { - assert.strictEqual(path, path); - assert.strictEqual(encoding, 'utf-8'); - done(); - }; - - zone.import(path, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - - beforeEach(function() { - readFileOverride = function(path, encoding, callback) { - callback(error); - }; - }); - - it('should execute the callback', function(done) { - zone.import(path, function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - }); - - describe('success', function() { - var recordType = 'ns'; - var parsedZonefile = {}; - parsedZonefile[recordType] = { a: 'b', c: 'd' }; - - beforeEach(function() { - parseOverride = function() { - return parsedZonefile; - }; - - readFileOverride = function(path, encoding, callback) { - callback(); - }; - }); - - it('should add records', function(done) { - zone.addRecords = function(recordsToCreate, callback) { - assert.strictEqual(recordsToCreate.length, 1); - - var recordToCreate = recordsToCreate[0]; - - assert(recordToCreate instanceof FakeRecord); - - var args = recordToCreate.calledWith_; - assert.strictEqual(args[0], zone); - assert.strictEqual(args[1], recordType); - assert.strictEqual(args[2], parsedZonefile[recordType]); - - callback(); - }; - - zone.import(path, done); - }); - }); - }); - - describe('record', function() { - it('should return a Record object', function() { - var type = 'a'; - var metadata = { a: 'b', c: 'd' }; - - var record = zone.record(type, metadata); - - assert(record instanceof FakeRecord); - - var args = record.calledWith_; - assert.strictEqual(args[0], zone); - assert.strictEqual(args[1], type); - assert.strictEqual(args[2], metadata); - }); - }); - - describe('replaceRecords', function() { - it('should get records', function(done) { - var recordType = 'ns'; - - zone.getRecords = function(recordType_) { - assert.strictEqual(recordType_, recordType); - done(); - }; - - zone.replaceRecords(recordType, [], assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - - beforeEach(function() { - zone.getRecords = function(recordType, callback) { - callback(error); - }; - }); - - it('should execute callback with error', function(done) { - zone.replaceRecords('a', [], function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - }); - - describe('success', function() { - var recordsToCreate = [ - { a: 'b', c: 'd' }, - { a: 'b', c: 'd' }, - { a: 'b', c: 'd' } - ]; - - var recordsToDelete = [ - { a: 'b', c: 'd' }, - { a: 'b', c: 'd' }, - { a: 'b', c: 'd' } - ]; - - beforeEach(function() { - zone.getRecords = function(recordType, callback) { - callback(null, recordsToDelete); - }; - }); - - it('should create a change', function(done) { - zone.createChange = function(options, callback) { - assert.strictEqual(options.add, recordsToCreate); - assert.strictEqual(options.delete, recordsToDelete); - - callback(); - }; - - zone.replaceRecords('a', recordsToCreate, done); - }); - }); - }); - - describe('deleteRecordsByType_', function() { - it('should get records', function(done) { - var recordType = 'ns'; - - zone.getRecords = function(recordType_) { - assert.strictEqual(recordType_, recordType); - done(); - }; - - zone.deleteRecordsByType_(recordType, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - - beforeEach(function() { - zone.getRecords = function(recordType, callback) { - callback(error); - }; - }); - - it('should execute callback with error', function(done) { - zone.deleteRecordsByType_('a', function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - }); - - describe('success', function() { - var recordsToDelete = [ - { a: 'b', c: 'd' }, - { a: 'b', c: 'd' }, - { a: 'b', c: 'd' } - ]; - - beforeEach(function() { - zone.getRecords = function(recordType, callback) { - callback(null, recordsToDelete); - }; - }); - - it('should execute callback if no records matched', function(done) { - zone.getRecords = function(recordType, callback) { - callback(null, []); - }; - - zone.deleteRecordsByType_('a', done); - }); - - it('should delete records', function(done) { - zone.deleteRecords = function(records, callback) { - assert.strictEqual(records, recordsToDelete); - - callback(); - }; - - zone.deleteRecordsByType_('a', done); - }); - }); - }); -}); diff --git a/packages/logging/README.md b/packages/logging/README.md deleted file mode 100644 index 2e1241fb730..00000000000 --- a/packages/logging/README.md +++ /dev/null @@ -1,123 +0,0 @@ -# @google-cloud/logging ([GA][versioning]) -> Google Stackdriver Logging Client Library for Node.js - -This module allows you to work with the Stackdriver Logging API. If you are already using [`winston`][winston] -or [`Bunyan`][bunyan] for logging, you might want to check out [`@google-cloud/logging-winston`][logging-winston] and -[`@google-cloud/logging-bunyan`][logging-bunyan] as higher level starting points. - -*Looking for more Google APIs than just Logging? You might want to check out [`google-cloud`][google-cloud].* - -- [API Documentation][gcloud-logging-docs] -- [Official Documentation][cloud-logging-docs] - - -```sh -$ npm install --save @google-cloud/logging -``` -```js -var logging = require('@google-cloud/logging')({ - projectId: 'grape-spaceship-123', - keyFilename: '/path/to/keyfile.json' -}); - -// Create a sink using a Bucket as a destination. -// $ npm install --save @google-cloud/storage -var gcs = require('@google-cloud/storage')({ - projectId: 'grape-spaceship-123', - keyFilename: '/path/to/keyfile.json' -}); - -logging.createSink('my-new-sink', { - destination: gcs.bucket('my-sink') -}, function(err, sink) {}); - -// Write a critical entry to a log. -var syslog = logging.log('syslog'); - -var metadata = { - resource: { - type: 'gce_instance', - labels: { - zone: 'global', - instance_id: '3' - } - } -}; - -var entry = syslog.entry(metadata, { - delegate: process.env.user -}); - -syslog.critical(entry, function(err) {}); - -// Get all entries in your project. -logging.getEntries(function(err, entries) { - if (!err) { - // `entries` contains all of the entries from the logs in your project. - } -}); - -// Promises are also supported by omitting callbacks. -logging.getEntries().then(function(data) { - var entries = data[0]; -}); - -// It's also possible to integrate with third-party Promise libraries. -var logging = require('@google-cloud/logging')({ - promise: require('bluebird') -}); -``` - - -## Authentication - -It's incredibly easy to get authenticated and start using Google's APIs. You can set your credentials on a global basis as well as on a per-API basis. See each individual API section below to see how you can auth on a per-API-basis. This is useful if you want to use different accounts for different Cloud services. - -### On Google Cloud Platform - -If you are running this client on Google Cloud Platform, we handle authentication for you with no configuration. You just need to make sure that when you [set up the GCE instance][gce-how-to], you add the correct scopes for the APIs you want to access. - -``` js -var logging = require('@google-cloud/logging')(); -// ...you're good to go! -``` - -### Elsewhere - -If you are not running this client on Google Cloud Platform, you need a Google Developers service account. To create a service account: - -1. Visit the [Google Developers Console][dev-console]. -2. Create a new project or click on an existing project. -3. Navigate to **APIs & auth** > **APIs section** and turn on the following APIs (you may need to enable billing in order to use these services): - * Stackdriver Logging API -4. Navigate to **APIs & auth** > **Credentials** and then: - * If you want to use a new service account key, click on **Create credentials** and select **Service account key**. After the account key is created, you will be prompted to download the JSON key file that the library uses to authenticate your requests. - * If you want to generate a new service account key for an existing service account, click on **Generate new JSON key** and download the JSON key file. - -``` js -var projectId = process.env.GCLOUD_PROJECT; // E.g. 'grape-spaceship-123' - -var logging = require('@google-cloud/logging')({ - projectId: projectId, - - // The path to your key file: - keyFilename: '/path/to/keyfile.json' - - // Or the contents of the key file: - credentials: require('./path/to/keyfile.json') -}); - -// ...you're good to go! -``` - - -[versioning]: https://github.com/GoogleCloudPlatform/google-cloud-node#versioning -[google-cloud]: https://github.com/GoogleCloudPlatform/google-cloud-node/ -[gce-how-to]: https://cloud.google.com/compute/docs/authentication#using -[dev-console]: https://console.developers.google.com/project -[gcloud-logging-docs]: https://googlecloudplatform.github.io/google-cloud-node/#/docs/logging -[cloud-logging-docs]: https://cloud.google.com/logging/docs -[winston]: https://github.com/winstonjs/winston -[bunyan]: https://github.com/trentm/node-bunyan -[logging-winston]: https://www.npmjs.com/package/@google-cloud/logging-winston -[logging-bunyan]: https://www.npmjs.com/package/@google-cloud/logging-bunyan diff --git a/packages/logging/package.json b/packages/logging/package.json deleted file mode 100644 index 9bea1e25ba3..00000000000 --- a/packages/logging/package.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "name": "@google-cloud/logging", - "version": "1.0.6", - "author": "Google Inc.", - "description": "Stackdriver Logging Client Library for Node.js", - "contributors": [ - { - "name": "Burcu Dogan", - "email": "jbd@google.com" - }, - { - "name": "Johan Euphrosine", - "email": "proppy@google.com" - }, - { - "name": "Patrick Costello", - "email": "pcostell@google.com" - }, - { - "name": "Ryan Seys", - "email": "ryan@ryanseys.com" - }, - { - "name": "Silvano Luciani", - "email": "silvano@google.com" - }, - { - "name": "Stephen Sawchuk", - "email": "sawchuk@gmail.com" - } - ], - "main": "./src/index.js", - "files": [ - "src", - "AUTHORS", - "CONTRIBUTORS", - "LICENSE" - ], - "repository": "googlecloudplatform/google-cloud-node", - "keywords": [ - "google apis client", - "google api client", - "google apis", - "google api", - "google", - "google cloud platform", - "google cloud", - "cloud", - "google logging", - "logging", - "stackdriver logging", - "stackdriver" - ], - "dependencies": { - "@google-cloud/common": "^0.13.0", - "@google-cloud/common-grpc": "^0.4.0", - "arrify": "^1.0.0", - "eventid": "^0.1.0", - "extend": "^3.0.0", - "gcp-metadata": "^0.2.0", - "google-auto-auth": "^0.7.1", - "google-gax": "^0.13.0", - "google-proto-files": "^0.12.0", - "is": "^3.0.1", - "pumpify": "^1.3.5", - "snakecase-keys": "^1.1.0", - "stream-events": "^1.0.1", - "string-format-obj": "^1.0.0", - "through2": "^2.0.3" - }, - "devDependencies": { - "@google-cloud/bigquery": "*", - "@google-cloud/pubsub": "*", - "@google-cloud/storage": "*", - "async": "^2.1.4", - "methmeth": "^1.0.0", - "mocha": "^3.0.1", - "propprop": "^0.3.0", - "proxyquire": "^1.7.10", - "uuid": "^3.0.1" - }, - "scripts": { - "publish-module": "node ../../scripts/publish.js logging", - "test": "mocha test/*.js", - "system-test": "mocha system-test/*.js --no-timeouts --bail" - }, - "license": "Apache-2.0", - "engines": { - "node": ">=4.0.0" - } -} diff --git a/packages/logging/src/entry.js b/packages/logging/src/entry.js deleted file mode 100644 index f8175041bc8..00000000000 --- a/packages/logging/src/entry.js +++ /dev/null @@ -1,168 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module logging/entry - */ - -'use strict'; - -var commonGrpc = require('@google-cloud/common-grpc'); -var EventId = require('eventid'); -var extend = require('extend'); -var is = require('is'); - -var eventId = new EventId(); - -/** - * Create an entry object to define new data to insert into a log. - * - * @resource [LogEntry JSON representation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry} - * - * @alias module:logging/entry - * @constructor - * - * @param {object=} metadata - See a - * [LogEntry Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry). - * @param {object|string} data - The data to use as the value for this log - * entry. - * - * If providing an object, these value types are supported: - * - `String` - * - `Number` - * - `Boolean` - * - `Buffer` - * - `Object` - * - `Array` - * - * Any other types are stringified with `String(value)`. - * @return {module:logging/entry} - * - * @example - * var syslog = logging.log('syslog'); - * - * var metadata = { - * resource: { - * type: 'gce_instance', - * labels: { - * zone: 'global', - * instance_id: '3' - * } - * } - * }; - * - * var entry = syslog.entry(metadata, { - * delegate: 'my_username' - * }); - * - * syslog.alert(entry, function(err, apiResponse) { - * if (!err) { - * // Log entry inserted successfully. - * } - * }); - * - * //- - * // You will also receive `Entry` objects when using - * // {module:logging#getEntries} and {module:logging/log#getEntries}. - * //- - * logging.getEntries(function(err, entries) { - * if (!err) { - * // entries[0].data = The data value from the log entry. - * } - * }); - */ -function Entry(metadata, data) { - this.metadata = extend({ - timestamp: new Date() - }, metadata); - - // JavaScript date has a very coarse granularity (millisecond), which makes - // it quite likely that multiple log entries would have the same timestamp. - // The Logging API doesn't guarantee to preserve insertion order for entries - // with the same timestamp. The service does use `insertId` as a secondary - // ordering for entries with the same timestamp. `insertId` needs to be - // globally unique (within the project) however. - // - // We use a globally unique monotonically increasing EventId as the - // insertId. - this.metadata.insertId = this.metadata.insertId || eventId.new(); - - this.data = data; -} - -/** - * Create an Entry object from an API response, such as `entries:list`. - * - * @private - * - * @param {object} entry - An API representation of an entry. See a - * [LogEntry](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry). - * @return {module:logging/entry} - */ -Entry.fromApiResponse_ = function(entry) { - var data = entry[entry.payload]; - - if (entry.payload === 'jsonPayload') { - data = commonGrpc.Service.structToObj_(data); - } - - var serializedEntry = new Entry(entry, data); - - if (serializedEntry.metadata.timestamp) { - var ms = serializedEntry.metadata.timestamp.seconds * 1000; - ms += serializedEntry.metadata.timestamp.nanos / 1e6; - serializedEntry.metadata.timestamp = new Date(ms); - } - - return serializedEntry; -}; - -/** - * Serialize an entry to the format the API expects. - * - * @param {object=} options - Configuration object. - * @param {boolean} options.removeCircular - Replace circular references in an - * object with a string value, `[Circular]`. - * @private - */ -Entry.prototype.toJSON = function(options) { - options = options || {}; - - var entry = extend(true, {}, this.metadata); - - if (is.object(this.data)) { - entry.jsonPayload = commonGrpc.Service.objToStruct_(this.data, { - removeCircular: !!options.removeCircular, - stringify: true - }); - } else if (is.string(this.data)) { - entry.textPayload = this.data; - } - - if (is.date(entry.timestamp)) { - var seconds = entry.timestamp.getTime() / 1000; - var secondsRounded = Math.floor(seconds); - - entry.timestamp = { - seconds: secondsRounded, - nanos: Math.floor((seconds - secondsRounded) * 1e9) - }; - } - - return entry; -}; - -module.exports = Entry; diff --git a/packages/logging/src/index.js b/packages/logging/src/index.js deleted file mode 100644 index 3894d8431eb..00000000000 --- a/packages/logging/src/index.js +++ /dev/null @@ -1,802 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module logging - */ - -'use strict'; - -var arrify = require('arrify'); -var common = require('@google-cloud/common'); -var extend = require('extend'); -var format = require('string-format-obj'); -var googleAuth = require('google-auto-auth'); -var is = require('is'); -var pumpify = require('pumpify'); -var streamEvents = require('stream-events'); -var through = require('through2'); - -var PKG = require('../package.json'); -var v2 = require('./v2'); - -/** - * @type {module:logging/entry} - * @private - */ -var Entry = require('./entry.js'); - -/** - * @type {module:logging/log} - * @private - */ -var Log = require('./log.js'); - -/** - * @type {module:logging/sink} - * @private - */ -var Sink = require('./sink.js'); - -/** - * [Stackdriver Logging](https://cloud.google.com/logging/docs) allows you to - * store, search, analyze, monitor, and alert on log data and events from Google - * Cloud Platform and Amazon Web Services (AWS). - * - * @constructor - * @alias module:logging - - * @resource [What is Stackdriver Logging?]{@link https://cloud.google.com/logging/docs} - * @resource [Introduction to the Stackdriver Logging API]{@link https://cloud.google.com/logging/docs/api} - * @resource [Logging to Stackdriver from Bunyan]{@link https://www.npmjs.com/package/@google-cloud/logging-bunyan} - * @resource [Logging to Stackdriver from Winston]{@link https://www.npmjs.com/package/@google-cloud/logging-winston} - * - * @param {object} options - [Configuration object](#/docs). - */ -function Logging(options) { - if (!(this instanceof Logging)) { - options = common.util.normalizeArguments(this, options); - return new Logging(options); - } - - var options_ = extend({ - scopes: v2.ALL_SCOPES, - libName: 'gccl', - libVersion: PKG.version - }, options); - - this.api = {}; - this.auth = googleAuth(options_); - this.options = options_; - this.projectId = options.projectId || '{{projectId}}'; -} - -// jscs:disable maximumLineLength -/** - * Create a sink. - * - * @resource [Sink Overview]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks} - * @resource [Advanced Logs Filters]{@link https://cloud.google.com/logging/docs/view/advanced_filters} - * @resource [projects.sinks.create API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/create} - * - * @throws {Error} if a name is not provided. - * @throws {Error} if a config object is not provided. - * - * @param {string} name - Name of the sink. - * @param {object} config - See a - * [Sink resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks#LogSink). - * @param {object} config.gaxOptions - Request configuration options, outlined - * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. - * @param {module:storage/bucket|module:bigquery/dataset|module:pubsub/topic} config.destination - - * The destination. The proper ACL scopes will be granted to the provided - * destination. - * @param {string=} config.filter - An advanced logs filter. Only log entries - * matching the filter are written. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {module:logging/sink} callback.sink - The created Sink object. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * var gcs = require('@google-cloud/storage')({ - * projectId: 'grape-spaceship-123' - * }); - * - * var config = { - * destination: gcs.bucket('logging-bucket'), - * filter: 'severity = ALERT' - * }; - * - * function callback(err, sink, apiResponse) { - * // `sink` is a Sink object. - * } - * - * logging.createSink('new-sink-name', config, callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * logging.createSink('new-sink-name', config).then(function(data) { - * var sink = data[0]; - * var apiResponse = data[1]; - * }); - */ -Logging.prototype.createSink = function(name, config, callback) { - // jscs:enable maximumLineLength - var self = this; - - if (!is.string(name)) { - throw new Error('A sink name must be provided.'); - } - - if (!is.object(config)) { - throw new Error('A sink configuration object must be provided.'); - } - - if (common.util.isCustomType(config.destination, 'bigquery/dataset')) { - this.setAclForDataset_(name, config, callback); - return; - } - - if (common.util.isCustomType(config.destination, 'pubsub/topic')) { - this.setAclForTopic_(name, config, callback); - return; - } - - if (common.util.isCustomType(config.destination, 'storage/bucket')) { - this.setAclForBucket_(name, config, callback); - return; - } - - var reqOpts = { - parent: 'projects/' + this.projectId, - sink: extend({}, config, { name: name }) - }; - - delete reqOpts.sink.gaxOptions; - - this.request({ - client: 'configServiceV2Client', - method: 'createSink', - reqOpts: reqOpts, - gaxOpts: config.gaxOptions - }, function(err, resp) { - if (err) { - callback(err, null, resp); - return; - } - - var sink = self.sink(resp.name); - sink.metadata = resp; - - callback(null, sink, resp); - }); -}; - -/** - * Create an entry object. - * - * Note that using this method will not itself make any API requests. You will - * use the object returned in other API calls, such as - * {module:logging/log#write}. - * - * @resource [LogEntry JSON representation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry} - * - * @param {object=|string=} resource - See a - * [Monitored Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource). - * @param {object|string} data - The data to use as the value for this log - * entry. - * @return {module:logging/entry} - * - * @example - * var resource = { - * type: 'gce_instance', - * labels: { - * zone: 'global', - * instance_id: '3' - * } - * }; - * - * var entry = logging.entry(resource, { - * delegate: 'my_username' - * }); - * - * entry.toJSON(); - * // { - * // resource: { - * // type: 'gce_instance', - * // labels: { - * // zone: 'global', - * // instance_id: '3' - * // } - * // }, - * // jsonPayload: { - * // delegate: 'my_username' - * // } - * // } - */ -Logging.prototype.entry = function(resource, data) { - return new Entry(resource, data); -}; - -/** - * List the entries in your logs. - * - * @resource [entries.list API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list} - * - * @param {object=} options - Filtering options. - * @param {boolean} options.autoPaginate - Have pagination handled - * automatically. Default: true. - * @param {string} options.filter - An - * [advanced logs filter](https://cloud.google.com/logging/docs/view/advanced_filters). - * An empty filter matches all log entries. - * @param {object} options.gaxOptions - Request configuration options, outlined - * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. - * @param {string} options.orderBy - How the results should be sorted, - * `timestamp` (oldest first) and `timestamp desc` (newest first, - * **default**). - * @param {number} options.pageSize - Maximum number of logs to return. - * @param {string} options.pageToken - A previously-returned page token - * representing part of the larger set of results to view. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {module:logging/entry[]} callback.entries - Entries from your logs. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * logging.getEntries(function(err, entries) { - * // `entries` is an array of Stackdriver Logging entry objects. - * // See the `data` property to read the data from the entry. - * }); - * - * //- - * // To control how many API requests are made and page through the results - * // manually, set `autoPaginate` to `false`. - * //- - * function callback(err, entries, nextQuery, apiResponse) { - * if (nextQuery) { - * // More results exist. - * logging.getEntries(nextQuery, callback); - * } - * } - * - * logging.getEntries({ - * autoPaginate: false - * }, callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * logging.getEntries().then(function(data) { - * var entries = data[0]; - * }); - */ -Logging.prototype.getEntries = function(options, callback) { - if (is.fn(options)) { - callback = options; - options = {}; - } - - var reqOpts = extend({ - orderBy: 'timestamp desc' - }, options); - - reqOpts.resourceNames = arrify(reqOpts.resourceNames); - reqOpts.resourceNames.push('projects/' + this.projectId); - - delete reqOpts.autoPaginate; - delete reqOpts.gaxOptions; - - var gaxOptions = extend({ - autoPaginate: options.autoPaginate - }, options.gaxOptions); - - this.request({ - client: 'loggingServiceV2Client', - method: 'listLogEntries', - reqOpts: reqOpts, - gaxOpts: gaxOptions - }, function() { - var entries = arguments[1]; - - if (entries) { - arguments[1] = entries.map(Entry.fromApiResponse_); - } - - callback.apply(null, arguments); - }); -}; - -/** - * List the {module:logging/entry} objects in your logs as a readable object - * stream. - * - * @param {object=} options - Configuration object. See - * {module:logging#getEntries} for a complete list of options. - * @return {stream} - * - * @example - * logging.getEntriesStream() - * .on('error', console.error) - * .on('data', function(entry) { - * // `entry` is a Stackdriver Logging entry object. - * // See the `data` property to read the data from the entry. - * }) - * .on('end', function() { - * // All entries retrieved. - * }); - * - * //- - * // If you anticipate many results, you can end a stream early to prevent - * // unnecessary processing and API requests. - * //- - * logging.getEntriesStream() - * .on('data', function(entry) { - * this.end(); - * }); - */ -Logging.prototype.getEntriesStream = function(options) { - var self = this; - - options = options || {}; - - var requestStream; - - var userStream = streamEvents(pumpify.obj()); - - userStream.abort = function() { - if (requestStream) { - requestStream.abort(); - } - }; - - var toEntryStream = through.obj(function(entry, _, next) { - next(null, Entry.fromApiResponse_(entry)); - }); - - userStream.once('reading', function() { - var reqOpts = extend({ - orderBy: 'timestamp desc' - }, options); - reqOpts.resourceNames = arrify(reqOpts.resourceNames); - reqOpts.resourceNames.push('projects/' + self.projectId); - - delete reqOpts.autoPaginate; - delete reqOpts.gaxOptions; - - var gaxOptions = extend({ - autoPaginate: options.autoPaginate - }, options.gaxOptions); - - requestStream = self.request({ - client: 'loggingServiceV2Client', - method: 'listLogEntriesStream', - reqOpts: reqOpts, - gaxOpts: gaxOptions - }); - - userStream.setPipeline(requestStream, toEntryStream); - }); - - return userStream; -}; - -/** - * Get the sinks associated with this project. - * - * @resource [projects.sinks.list API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/list} - * - * @param {object=} options - Configuration object. - * @param {boolean} options.autoPaginate - Have pagination handled - * automatically. Default: true. - * @param {object} options.gaxOptions - Request configuration options, outlined - * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {module:logging/sink[]} callback.sinks - Sink objects. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * logging.getSinks(function(err, sinks) { - * // sinks is an array of Sink objects. - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * logging.getSinks().then(function(data) { - * var sinks = data[0]; - * }); - */ -Logging.prototype.getSinks = function(options, callback) { - var self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - var reqOpts = extend({}, options, { - parent: 'projects/' + this.projectId - }); - - delete reqOpts.autoPaginate; - delete reqOpts.gaxOptions; - - var gaxOptions = extend({ - autoPaginate: options.autoPaginate - }, options.gaxOptions); - - this.request({ - client: 'configServiceV2Client', - method: 'listSinks', - reqOpts: reqOpts, - gaxOpts: gaxOptions - }, function() { - var sinks = arguments[1]; - - if (sinks) { - arguments[1] = sinks.map(function(sink) { - var sinkInstance = self.sink(sink.name); - sinkInstance.metadata = sink; - return sinkInstance; - }); - } - - callback.apply(null, arguments); - }); -}; - -/** - * Get the {module:logging/sink} objects associated with this project as a - * readable object stream. - * - * @param {object=} options - Configuration object. See - * {module:logging#getSinks} for a complete list of options. - * @return {stream} - * - * @example - * logging.getSinksStream() - * .on('error', console.error) - * .on('data', function(sink) { - * // `sink` is a Sink object. - * }) - * .on('end', function() { - * // All sinks retrieved. - * }); - * - * //- - * // If you anticipate many results, you can end a stream early to prevent - * // unnecessary processing and API requests. - * //- - * logging.getSinksStream() - * .on('data', function(sink) { - * this.end(); - * }); - */ -Logging.prototype.getSinksStream = function(options) { - var self = this; - - options = options || {}; - - var requestStream; - var userStream = streamEvents(pumpify.obj()); - - userStream.abort = function() { - if (requestStream) { - requestStream.abort(); - } - }; - - var toSinkStream = through.obj(function(sink, _, next) { - var sinkInstance = self.sink(sink.name); - sinkInstance.metadata = sink; - next(null, sinkInstance); - }); - - userStream.once('reading', function() { - var reqOpts = extend({}, options, { - parent: 'projects/' + self.projectId - }); - - delete reqOpts.gaxOptions; - - var gaxOptions = extend({ - autoPaginate: options.autoPaginate - }, options.gaxOptions); - - requestStream = self.request({ - client: 'configServiceV2Client', - method: 'listSinksStream', - reqOpts: reqOpts, - gaxOpts: gaxOptions - }); - - userStream.setPipeline(requestStream, toSinkStream); - }); - - return userStream; -}; - -/** - * Get a reference to a Stackdriver Logging log. - * - * @resource [Log Overview]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs} - * - * @param {string} name - Name of the existing log. - * @param {object=} options - Configuration object. - * @param {boolean} options.removeCircular - Replace circular references in - * logged objects with a string value, `[Circular]`. (Default: false) - * @return {module:logging/log} - * - * @example - * var log = logging.log('my-log'); - */ -Logging.prototype.log = function(name, options) { - return new Log(this, name, options); -}; - -/** - * Get a reference to a Stackdriver Logging sink. - * - * @resource [Sink Overview]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks} - * - * @param {string} name - Name of the existing sink. - * @return {module:logging/sink} - * - * @example - * var sink = logging.sink('my-sink'); - */ -Logging.prototype.sink = function(name) { - return new Sink(this, name); -}; - -/** - * Funnel all API requests through this method, to be sure we have a project ID. - * - * @param {object} config - Configuration object. - * @param {object} config.gaxOpts - GAX options. - * @param {function} config.method - The gax method to call. - * @param {object} config.reqOpts - Request options. - * @param {function=} callback - The callback function. - */ -Logging.prototype.request = function(config, callback) { - var self = this; - var isStreamMode = !callback; - - var gaxStream; - var stream; - - if (isStreamMode) { - stream = streamEvents(through.obj()); - - stream.abort = function() { - if (gaxStream && gaxStream.cancel) { - gaxStream.cancel(); - } - }; - - stream.once('reading', makeRequestStream); - } else { - makeRequestCallback(); - } - - function prepareGaxRequest(callback) { - self.auth.getProjectId(function(err, projectId) { - if (err) { - callback(err); - return; - } - - var gaxClient = self.api[config.client]; - - if (!gaxClient) { - // Lazily instantiate client. - gaxClient = v2(self.options)[config.client](self.options); - self.api[config.client] = gaxClient; - } - - var reqOpts = extend(true, {}, config.reqOpts); - reqOpts = common.util.replaceProjectIdToken(reqOpts, projectId); - - var requestFn = gaxClient[config.method].bind( - gaxClient, - reqOpts, - config.gaxOpts - ); - - callback(null, requestFn); - }); - } - - function makeRequestCallback() { - if (global.GCLOUD_SANDBOX_ENV) { - return; - } - - prepareGaxRequest(function(err, requestFn) { - if (err) { - callback(err); - return; - } - - requestFn(callback); - }); - } - - function makeRequestStream() { - if (global.GCLOUD_SANDBOX_ENV) { - return through.obj(); - } - - prepareGaxRequest(function(err, requestFn) { - if (err) { - stream.destroy(err); - return; - } - - gaxStream = requestFn(); - - gaxStream - .on('error', function(err) { - stream.destroy(err); - }) - .pipe(stream); - }); - } - - return stream; -}; - -/** - * This method is called when creating a sink with a Bucket destination. The - * bucket must first grant proper ACL access to the Stackdriver Logging account. - * - * The parameters are the same as what {module:logging#createSink} accepts. - * - * @private - */ -Logging.prototype.setAclForBucket_ = function(name, config, callback) { - var self = this; - var bucket = config.destination; - - bucket.acl.owners.addGroup('cloud-logs@google.com', function(err, apiResp) { - if (err) { - callback(err, null, apiResp); - return; - } - - config.destination = 'storage.googleapis.com/' + bucket.name; - - self.createSink(name, config, callback); - }); -}; - -/** - * This method is called when creating a sink with a Dataset destination. The - * dataset must first grant proper ACL access to the Stackdriver Logging - * account. - * - * The parameters are the same as what {module:logging#createSink} accepts. - * - * @private - */ -Logging.prototype.setAclForDataset_ = function(name, config, callback) { - var self = this; - var dataset = config.destination; - - dataset.getMetadata(function(err, metadata, apiResp) { - if (err) { - callback(err, null, apiResp); - return; - } - - var access = [].slice.call(arrify(metadata.access)); - - access.push({ - role: 'WRITER', - groupByEmail: 'cloud-logs@google.com' - }); - - dataset.setMetadata({ - access: access - }, function(err, apiResp) { - if (err) { - callback(err, null, apiResp); - return; - } - - config.destination = format('{baseUrl}/projects/{pId}/datasets/{dId}', { - baseUrl: 'bigquery.googleapis.com', - pId: dataset.parent.projectId, - dId: dataset.id - }); - - self.createSink(name, config, callback); - }); - }); -}; - -/** - * This method is called when creating a sink with a Topic destination. The - * topic must first grant proper ACL access to the Stackdriver Logging account. - * - * The parameters are the same as what {module:logging#createSink} accepts. - * - * @private - */ -Logging.prototype.setAclForTopic_ = function(name, config, callback) { - var self = this; - var topic = config.destination; - - topic.iam.getPolicy(function(err, policy, apiResp) { - if (err) { - callback(err, null, apiResp); - return; - } - - policy.bindings = arrify(policy.bindings); - - policy.bindings.push({ - role: 'roles/pubsub.publisher', - members: [ - 'serviceAccount:cloud-logs@system.gserviceaccount.com' - ] - }); - - topic.iam.setPolicy(policy, function(err, policy, apiResp) { - if (err) { - callback(err, null, apiResp); - return; - } - - config.destination = format('{baseUrl}/{topicName}', { - baseUrl: 'pubsub.googleapis.com', - topicName: topic.name - }); - - self.createSink(name, config, callback); - }); - }); -}; - -/*! Developer Documentation - * - * These methods can be auto-paginated. - */ -common.paginator.extend(Logging, ['getEntries', 'getSinks']); - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Logging, { - exclude: [ - 'entry', - 'log', - 'request', - 'sink' - ] -}); - -Logging.Entry = Entry; -Logging.Log = Log; -Logging.Logging = Logging; -Logging.Sink = Sink; - -module.exports = Logging; -module.exports.v2 = v2; diff --git a/packages/logging/src/log.js b/packages/logging/src/log.js deleted file mode 100644 index acde7b57e46..00000000000 --- a/packages/logging/src/log.js +++ /dev/null @@ -1,658 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module logging/log - */ - -'use strict'; - -var arrify = require('arrify'); -var common = require('@google-cloud/common'); -var extend = require('extend'); -var is = require('is'); -var snakeCaseKeys = require('snakecase-keys'); - -/** - * @type {module:logging/entry} - * @private - */ -var Entry = require('./entry.js'); - -/** - * @type {module:logging/metadata} - * @private - */ -var Metadata = require('./metadata.js'); - -/*! Developer Documentation - * - * @param {module:logging} logging - Parent Logging instance. - */ -/** - * A log is a named collection of entries, each entry representing a timestamped - * event. Logs can be produced by Google Cloud Platform services, by third-party - * services, or by your applications. For example, the log `apache-access` is - * produced by the Apache Web Server, but the log - * `compute.googleapis.com/activity_log` is produced by Google Compute Engine. - * - * @resource [Introduction to Logs]{@link https://cloud.google.com/logging/docs/basic-concepts#logs} - * - * @alias module:logging/log - * @constructor - * - * @param {string} name - Name of the log. - * @param {object=} options - Configuration object. - * @param {boolean} options.removeCircular - Replace circular references in - * logged objects with a string value, `[Circular]`. (Default: false) - * - * @example - * var log = logging.log('syslog'); - */ -function Log(logging, name, options) { - options = options || {}; - - this.formattedName_ = Log.formatName_(logging.projectId, name); - this.removeCircular_ = options.removeCircular === true; - this.metadata_ = new Metadata(logging); - - this.logging = logging; - this.name = this.formattedName_.split('/').pop(); -} - -/** - * Return an array of log entries with the desired severity assigned. - * - * @private - * - * @param {object|object[]} entries - Log entries. - * @param {string} severity - The desired severity level. - */ -Log.assignSeverityToEntries_ = function(entries, severity) { - return arrify(entries).map(function(entry) { - var metadata = extend(true, {}, entry.metadata, { - severity: severity - }); - - return extend(new Entry(), entry, { - metadata: metadata - }); - }); -}; - -/** - * Format the name of a log. A log's full name is in the format of - * 'projects/{projectId}/logs/{logName}'. - * - * @private - * - * @return {string} - */ -Log.formatName_ = function(projectId, name) { - var path = 'projects/' + projectId + '/logs/'; - name = name.replace(path, ''); - - if (decodeURIComponent(name) === name) { - // The name has not been encoded yet. - name = encodeURIComponent(name); - } - - return path + name; -}; - -/** - * Write a log entry with a severity of "ALERT". - * - * This is a simple wrapper around {module:logging/log#write}. All arguments are - * the same as documented there. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.alert(entry, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.alert(entry).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.alert = function(entry, options, callback) { - this.write(Log.assignSeverityToEntries_(entry, 'ALERT'), options, callback); -}; - -/** - * Write a log entry with a severity of "CRITICAL". - * - * This is a simple wrapper around {module:logging/log#write}. All arguments are - * the same as documented there. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.critical(entry, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.critical(entry).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.critical = function(entry, options, callback) { - var entries = Log.assignSeverityToEntries_(entry, 'CRITICAL'); - this.write(entries, options, callback); -}; - -/** - * Write a log entry with a severity of "DEBUG". - * - * This is a simple wrapper around {module:logging/log#write}. All arguments are - * the same as documented there. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.debug(entry, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.debug(entry).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.debug = function(entry, options, callback) { - this.write(Log.assignSeverityToEntries_(entry, 'DEBUG'), options, callback); -}; - -/** - * Delete the log. - * - * @resource [projects.logs.delete API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.logs/delete} - * - * @param {object=} gaxOptions - Request configuration options, outlined - * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. - * @param {function=} callback - The callback function. - * @param {?error} callback.err - An error returned while making this - * request. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * log.delete(function(err, apiResponse) { - * if (!err) { - * // The log was deleted. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.delete().then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.delete = function(gaxOptions, callback) { - if (is.fn(gaxOptions)) { - callback = gaxOptions; - gaxOptions = {}; - } - - var reqOpts = { - logName: this.formattedName_ - }; - - this.logging.request({ - client: 'loggingServiceV2Client', - method: 'deleteLog', - reqOpts: reqOpts, - gaxOpts: gaxOptions - }, callback); -}; - -/** - * Write a log entry with a severity of "EMERGENCY". - * - * This is a simple wrapper around {module:logging/log#write}. All arguments are - * the same as documented there. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.emergency(entry, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.emergency(entry).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.emergency = function(entry, options, callback) { - var entries = Log.assignSeverityToEntries_(entry, 'EMERGENCY'); - this.write(entries, options, callback); -}; - -/** - * Create an entry object for this log. - * - * Note that using this method will not itself make any API requests. You will - * use the object returned in other API calls, such as - * {module:logging/log#write}. - * - * @resource [LogEntry JSON representation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry} - * - * @param {object=} metadata - See a - * [LogEntry Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry). - * @param {object|string} data - The data to use as the value for this log - * entry. - * @return {module:logging/entry} - * - * @example - * var metadata = { - * resource: { - * type: 'gce_instance', - * labels: { - * zone: 'global', - * instance_id: '3' - * } - * } - * }; - * - * var entry = log.entry(metadata, { - * delegate: 'my_username' - * }); - * - * entry.toJSON(); - * // { - * // logName: 'projects/grape-spaceship-123/logs/syslog', - * // resource: { - * // type: 'gce_instance', - * // labels: { - * // zone: 'global', - * // instance_id: '3' - * // } - * // }, - * // jsonPayload: { - * // delegate: 'my_username' - * // } - * // } - */ -Log.prototype.entry = function(metadata, data) { - if (!data) { - data = metadata; - metadata = {}; - } - - return this.logging.entry(metadata, data); -}; - -/** - * Write a log entry with a severity of "ERROR". - * - * This is a simple wrapper around {module:logging/log#write}. All arguments are - * the same as documented there. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.error(entry, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.error(entry).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.error = function(entry, options, callback) { - this.write(Log.assignSeverityToEntries_(entry, 'ERROR'), options, callback); -}; - -/** - * This method is a wrapper around {module:logging#getEntries}, but with a - * filter specified to only return entries from this log. - * - * @resource [entries.list API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/list} - * - * @param {object=} options - Filtering options. - * @param {boolean} options.autoPaginate - Have pagination handled - * automatically. Default: true. - * @param {string} options.filter - An - * [advanced logs filter](https://cloud.google.com/logging/docs/view/advanced_filters). - * An empty filter matches all log entries. - * @param {number} options.maxApiCalls - Maximum number of API calls to make. - * @param {number} options.maxResults - Maximum number of results to return. - * @param {string} options.orderBy - How the results should be sorted, - * `timestamp` (oldest first) and `timestamp desc` (newest first, - * **default**). - * @param {number} options.pageSize - Maximum number of logs to return. - * @param {string} options.pageToken - A previously-returned page token - * representing part of the larger set of results to view. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {module:logging/entry[]} callback.entries - Entries from this log. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * log.getEntries(function(err, entries) { - * // `entries` is an array of Stackdriver Logging entry objects. - * // See the `data` property to read the data from the entry. - * }); - * - * //- - * // To control how many API requests are made and page through the results - * // manually, set `autoPaginate` to `false`. - * //- - * function callback(err, entries, nextQuery, apiResponse) { - * if (nextQuery) { - * // More results exist. - * log.getEntries(nextQuery, callback); - * } - * } - * - * log.getEntries({ - * autoPaginate: false - * }, callback); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.getEntries().then(function(data) { - * var entries = data[0]; - * }); - */ -Log.prototype.getEntries = function(options, callback) { - if (is.function(options)) { - callback = options; - options = {}; - } - - options = extend({ - filter: 'logName="' + this.formattedName_ + '"' - }, options); - - return this.logging.getEntries(options, callback); -}; - -/** - * This method is a wrapper around {module:logging#getEntriesStream}, but with a - * filter specified to only return {module:logging/entry} objects from this log. - * - * @param {object=} options - Configuration object. See - * {module:logging/log#getEntries} for a complete list of options. - * @return {stream} - * - * @example - * log.getEntriesStream() - * .on('error', console.error) - * .on('data', function(entry) { - * // `entry` is a Stackdriver Logging entry object. - * // See the `data` property to read the data from the entry. - * }) - * .on('end', function() { - * // All entries retrieved. - * }); - * - * //- - * // If you anticipate many results, you can end a stream early to prevent - * // unnecessary processing and API requests. - * //- - * log.getEntriesStream() - * .on('data', function(entry) { - * this.end(); - * }); - */ -Log.prototype.getEntriesStream = function(options) { - options = extend({ - filter: 'logName="' + this.formattedName_ + '"' - }, options); - - return this.logging.getEntriesStream(options); -}; - -/** - * Write a log entry with a severity of "INFO". - * - * This is a simple wrapper around {module:logging/log#write}. All arguments are - * the same as documented there. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.info(entry, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.info(entry).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.info = function(entry, options, callback) { - this.write(Log.assignSeverityToEntries_(entry, 'INFO'), options, callback); -}; - -/** - * Write a log entry with a severity of "NOTICE". - * - * This is a simple wrapper around {module:logging/log#write}. All arguments are - * the same as documented there. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.notice(entry, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.notice(entry).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.notice = function(entry, options, callback) { - this.write(Log.assignSeverityToEntries_(entry, 'NOTICE'), options, callback); -}; - -/** - * Write a log entry with a severity of "WARNING". - * - * This is a simple wrapper around {module:logging/log#write}. All arguments are - * the same as documented there. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.warning(entry, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.warning(entry).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.warning = function(entry, options, callback) { - this.write(Log.assignSeverityToEntries_(entry, 'WARNING'), options, callback); -}; - -/** - * Write log entries to Stackdriver Logging. - * - * @resource [entries.write API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/entries/write} - * - * @param {module:logging/entry|module:logging/entry[]} entry - A log entry, or - * array of entries, to write. - * @param {object=} options - Configuration object. - * @param {object} options.gaxOptions - Request configuration options, outlined - * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. - * @param {object[]} options.labels - Labels to set on the log. - * @param {object} options.resource - A default monitored resource for entries - * where one isn't specified. - * @param {function} callback - The callback function. - * @param {?error} callback.err - An error returned while making this request. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * var entry = log.entry('gce_instance', { - * instance: 'my_instance' - * }); - * - * log.write(entry, function(err, apiResponse) { - * if (!err) { - * // The log entry was written. - * } - * }); - * - * //- - * // You may also pass multiple log entries to write. - * //- - * var secondEntry = log.entry('compute.googleapis.com', { - * user: 'my_username' - * }); - * - * log.write([ - * entry, - * secondEntry - * ], function(err, apiResponse) { - * if (!err) { - * // The log entries were written. - * } - * }); - * - * //- - * // To save some steps, you can also pass in plain values as your entries. - * // Note, however, that you must provide a configuration object to specify the - * // resource. - * //- - * var entries = [ - * { - * user: 'my_username' - * }, - * { - * home: process.env.HOME - * } - * ]; - * - * var options = { - * resource: 'compute.googleapis.com' - * }; - * - * log.write(entries, options, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * log.write(entries).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Log.prototype.write = function(entry, options, callback) { - var self = this; - - if (is.fn(options)) { - callback = options; - options = {}; - } - - if (!options.resource) { - this.metadata_.getDefaultResource(function(err, resource) { - // Ignore errors (the API will speak up if it has an issue). - writeWithResource(resource); - }); - } else { - if (options.resource.labels) { - options.resource.labels = snakeCaseKeys(options.resource.labels); - } - writeWithResource(options.resource); - } - - function writeWithResource(resource) { - var decoratedEntries; - try { - decoratedEntries = self.decorateEntries_(arrify(entry)); - } catch (err) { - // Ignore errors (the API will speak up if it has an issue). - } - - var reqOpts = extend({ - logName: self.formattedName_, - entries: decoratedEntries, - resource: resource - }, options); - - delete reqOpts.gaxOptions; - - self.logging.request({ - client: 'loggingServiceV2Client', - method: 'writeLogEntries', - reqOpts: reqOpts, - gaxOpts: options.gaxOptions - }, callback); - } -}; - -/** - * All entries are passed through here in order to get them serialized. - * - * @private - * - * @param {object[]} entries - Entry objects. - * @return {object[]} Serialized entries. - * @throws if there is an error during serialization. - */ -Log.prototype.decorateEntries_ = function(entries) { - var self = this; - - return entries.map(function(entry) { - if (!(entry instanceof Entry)) { - entry = self.entry(entry); - } - - return entry.toJSON({ - removeCircular: self.removeCircular_ - }); - }); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Log, { - exclude: ['entry'] -}); - -module.exports = Log; diff --git a/packages/logging/src/metadata.js b/packages/logging/src/metadata.js deleted file mode 100644 index 73e02ac22d3..00000000000 --- a/packages/logging/src/metadata.js +++ /dev/null @@ -1,159 +0,0 @@ -/*! - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module logging/metadata - */ - -'use strict'; - -var gcpMetadata = require('gcp-metadata'); - -/** - * The Metadata class attempts to contact the metadata service and determine, - * based on request success and environment variables, what type of resource - * the library is operating on. - * - * @constructor - * @alias module:logging/metadata - * - * @private - * - * @resource [Logs Resource API Documentation]{@link https://cloud.google.com/logging/docs/api/reference/rest/v2/MonitoredResource} - * - * @param {module:logging} logging - The parent Logging instance. - */ -function Metadata(logging) { - this.logging = logging; -} - -/** - * Create a descriptor for Cloud Functions. - * - * @returns {object} - */ -Metadata.getCloudFunctionDescriptor = function() { - return { - type: 'cloud_function', - labels: { - function_name: process.env.FUNCTION_NAME, - region: process.env.SUPERVISOR_REGION - } - }; -}; - -/** - * Create a descriptor for Google App Engine. - * - * @returns {object} - */ -Metadata.getGAEDescriptor = function() { - return { - type: 'gae_app', - labels: { - module_id: process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME, - version_id: process.env.GAE_VERSION - } - }; -}; - -/** - * Create a descriptor for Google Compute Engine. - * - * @private - * - * @param {function} callback - The callback function. - * @return {object} - */ -Metadata.getGCEDescriptor = function(callback) { - gcpMetadata.instance('id', function(err, _, instanceId) { - if (err) { - callback(err); - return; - } - - callback(null, { - type: 'gce_instance', - labels: { - instance_id: instanceId - } - }); - }); -}; - -/** - * Create a descriptor for Google Container Engine. - * - * @private - * - * @param {function} callback - The callback function. - * @return {object} - */ -Metadata.getGKEDescriptor = function(callback) { - gcpMetadata.instance('attributes/cluster-name', function(e, _, clusterName) { - if (e) { - callback(e); - return; - } - - callback(null, { - type: 'container', - labels: { - // TODO(ofrobots): it would be good to include the namespace_id as - // well. - cluster_name: clusterName - } - }); - }); -}; - -/** - * Create a global descriptor. - * - * @private - * - * @returns {object} - */ -Metadata.getGlobalDescriptor = function() { - return { - type: 'global' - }; -}; - -/** - * Retrieve a resource object describing the current environment. - * - * @param {function} callback - The callback function. - */ -Metadata.prototype.getDefaultResource = function(callback) { - this.logging.auth.getEnvironment(function(err, env) { - if (env.IS_CONTAINER_ENGINE) { - Metadata.getGKEDescriptor(callback); - } else if (env.IS_APP_ENGINE) { - callback(null, Metadata.getGAEDescriptor()); - } else if (env.IS_CLOUD_FUNCTION) { - callback(null, Metadata.getCloudFunctionDescriptor()); - } else if (env.IS_COMPUTE_ENGINE) { - // Test for compute engine should be done after all the rest - everything - // runs on top of compute engine. - Metadata.getGCEDescriptor(callback); - } else { - callback(null, Metadata.getGlobalDescriptor()); - } - }); -}; - -module.exports = Metadata; diff --git a/packages/logging/src/sink.js b/packages/logging/src/sink.js deleted file mode 100644 index 9396cc68fee..00000000000 --- a/packages/logging/src/sink.js +++ /dev/null @@ -1,279 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module logging/sink - */ - -'use strict'; - -var common = require('@google-cloud/common'); -var extend = require('extend'); -var is = require('is'); - -/*! Developer Documentation - * - * @param {module:logging} logging - The Logging instance. - */ -/** - * A sink is an object that lets you to specify a set of log entries to export - * to a particular destination. Stackdriver Logging lets you export log entries - * to destinations including Cloud Storage buckets (for long term log - * storage), Google BigQuery datasets (for log analysis), Google Pub/Sub (for - * streaming to other applications). - * - * @resource [Introduction to Sinks]{@link https://cloud.google.com/logging/docs/basic-concepts#sinks} - * - * @alias module:logging/sink - * @constructor - * - * @param {object} options - [Configuration object](#/docs). - * - * @example - * var sink = logging.sink('my-sink'); - */ -function Sink(logging, name) { - this.logging = logging; - this.name = name; - this.formattedName_ = 'projects/' + logging.projectId + '/sinks/' + name; -} - -/** - * Create a sink. - * - * @param {object} config - See {module:logging#createSink}. - * - * @example - * var config = { - * destination: { - * // ... - * } - * }; - * - * sink.create(config, function(err, sink, apiResponse) { - * if (!err) { - * // The sink was created successfully. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * sink.create(config).then(function(data) { - * var sink = data[0]; - * var apiResponse = data[1]; - * }); - */ -Sink.prototype.create = function(config, callback) { - this.logging.createSink(this.name, config, callback); -}; - -/** - * Delete the sink. - * - * @resource [projects.sink.delete API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/delete} - * - * @param {object=} gaxOptions - Request configuration options, outlined - * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. - * @param {function=} callback - The callback function. - * @param {?error} callback.err - An error returned while making this - * request. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * sink.delete(function(err, apiResponse) { - * if (!err) { - * // The log was deleted. - * } - * }); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * sink.delete().then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Sink.prototype.delete = function(gaxOptions, callback) { - if (is.fn(gaxOptions)) { - callback = gaxOptions; - gaxOptions = {}; - } - - var reqOpts = { - sinkName: this.formattedName_ - }; - - this.logging.request({ - client: 'configServiceV2Client', - method: 'deleteSink', - reqOpts: reqOpts, - gaxOpts: gaxOptions - }, callback); -}; - -/** - * Get the sink's metadata. - * - * @resource [Sink Resource]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks#LogSink} - * @resource [projects.sink.get API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/get} - * - * @param {object=} gaxOptions - Request configuration options, outlined - * here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. - * @param {function=} callback - The callback function. - * @param {?error} callback.err - An error returned while making this - * request. - * @param {object} callback.metadata - The sink's metadata. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * sink.getMetadata(function(err, metadata, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * sink.getMetadata().then(function(data) { - * var metadata = data[0]; - * var apiResponse = data[1]; - * }); - */ -Sink.prototype.getMetadata = function(gaxOptions, callback) { - var self = this; - - if (is.fn(gaxOptions)) { - callback = gaxOptions; - gaxOptions = {}; - } - - var reqOpts = { - sinkName: this.formattedName_ - }; - - this.logging.request({ - client: 'configServiceV2Client', - method: 'getSink', - reqOpts: reqOpts, - gaxOpts: gaxOptions - }, function() { - if (arguments[1]) { - self.metadata = arguments[1]; - } - - callback.apply(null, arguments); - }); -}; - -/** - * Set the sink's filter. - * - * This will override any filter that was previously set. - * - * @resource [Advanced Logs Filters]{@link https://cloud.google.com/logging/docs/view/advanced_filters} - * - * @param {string} filter - The new filter. - * @param {function=} callback - The callback function. - * @param {?error} callback.err - An error returned while making this - * request. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * var filter = 'metadata.severity = ALERT'; - * - * sink.setFilter(filter, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * sink.setFilter(filter).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Sink.prototype.setFilter = function(filter, callback) { - this.setMetadata({ - filter: filter - }, callback); -}; - -/** - * Set the sink's metadata. - * - * @resource [Sink Resource]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks#LogSink} - * @resource [projects.sink.update API Documentation]{@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks/update} - * - * @param {object} metadata - See a - * [Sink resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.sinks#LogSink). - * @param {object=} metadata.gaxOptions - Request configuration options, - * outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. - * @param {function=} callback - The callback function. - * @param {?error} callback.err - An error returned while making this - * request. - * @param {object} callback.apiResponse - The full API response. - * - * @example - * var metadata = { - * filter: 'metadata.severity = ALERT' - * }; - * - * sink.setMetadata(metadata, function(err, apiResponse) {}); - * - * //- - * // If the callback is omitted, we'll return a Promise. - * //- - * sink.setMetadata(metadata).then(function(data) { - * var apiResponse = data[0]; - * }); - */ -Sink.prototype.setMetadata = function(metadata, callback) { - var self = this; - - callback = callback || common.util.noop; - - this.getMetadata(function(err, currentMetadata, apiResponse) { - if (err) { - callback(err, apiResponse); - return; - } - - var reqOpts = { - sinkName: self.formattedName_, - sink: extend({}, currentMetadata, metadata) - }; - - delete reqOpts.sink.gaxOptions; - - self.logging.request({ - client: 'configServiceV2Client', - method: 'updateSink', - reqOpts: reqOpts, - gaxOpts: metadata.gaxOptions - }, function() { - if (arguments[1]) { - self.metadata = arguments[1]; - } - - callback.apply(null, arguments); - }); - }); -}; - -/*! Developer Documentation - * - * All async methods (except for streams) will return a Promise in the event - * that a callback is omitted. - */ -common.util.promisifyAll(Sink); - -module.exports = Sink; diff --git a/packages/logging/src/v2/config_service_v2_client.js b/packages/logging/src/v2/config_service_v2_client.js deleted file mode 100644 index 57ab8e23b30..00000000000 --- a/packages/logging/src/v2/config_service_v2_client.js +++ /dev/null @@ -1,605 +0,0 @@ -/* - * Copyright 2016 Google Inc. All rights reserved. - * - * 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 - * - * http://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. - * - * EDITING INSTRUCTIONS - * This file was generated from the file - * https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_config.proto, - * and updates to that file get reflected here through a refresh process. - * For the short term, the refresh process will only be runnable by Google - * engineers. - * - * The only allowed edits are to method and file documentation. A 3-way - * merge preserves those additions if the generated source changes. - */ -/* TODO: introduce line-wrapping so that it never exceeds the limit. */ -/* jscs: disable maximumLineLength */ -'use strict'; - -var configData = require('./config_service_v2_client_config'); -var extend = require('extend'); -var gax = require('google-gax'); - -var SERVICE_ADDRESS = 'logging.googleapis.com'; - -var DEFAULT_SERVICE_PORT = 443; - -var CODE_GEN_NAME_VERSION = 'gapic/0.1.0'; - -var PAGE_DESCRIPTORS = { - listSinks: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'sinks') -}; - -/** - * The scopes needed to make gRPC calls to all of the methods defined in - * this service. - */ -var ALL_SCOPES = [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write' -]; - -/** - * Service for configuring sinks used to export log entries outside of - * Stackdriver Logging. - * - * This will be created through a builder function which can be obtained by the module. - * See the following example of how to initialize the module and how to access to the builder. - * @see {@link configServiceV2Client} - * - * @example - * var loggingV2 = require('@google-cloud/logging').v2({ - * // optional auth parameters. - * }); - * var client = loggingV2.configServiceV2Client(); - * - * @class - */ -function ConfigServiceV2Client(gaxGrpc, grpcClients, opts) { - opts = extend({ - servicePath: SERVICE_ADDRESS, - port: DEFAULT_SERVICE_PORT, - clientConfig: {} - }, opts); - - var googleApiClient = [ - 'gl-node/' + process.versions.node - ]; - if (opts.libName && opts.libVersion) { - googleApiClient.push(opts.libName + '/' + opts.libVersion); - } - googleApiClient.push( - CODE_GEN_NAME_VERSION, - 'gax/' + gax.version, - 'grpc/' + gaxGrpc.grpcVersion - ); - - var defaults = gaxGrpc.constructSettings( - 'google.logging.v2.ConfigServiceV2', - configData, - opts.clientConfig, - {'x-goog-api-client': googleApiClient.join(' ')}); - - var self = this; - - this.auth = gaxGrpc.auth; - var configServiceV2Stub = gaxGrpc.createStub( - grpcClients.google.logging.v2.ConfigServiceV2, - opts); - var configServiceV2StubMethods = [ - 'listSinks', - 'getSink', - 'createSink', - 'updateSink', - 'deleteSink' - ]; - configServiceV2StubMethods.forEach(function(methodName) { - self['_' + methodName] = gax.createApiCall( - configServiceV2Stub.then(function(configServiceV2Stub) { - return function() { - var args = Array.prototype.slice.call(arguments, 0); - return configServiceV2Stub[methodName].apply(configServiceV2Stub, args); - }; - }), - defaults[methodName], - PAGE_DESCRIPTORS[methodName]); - }); -} - -// Path templates - -var PROJECT_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}'); - -var SINK_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}/sinks/{sink}'); - -/** - * Returns a fully-qualified project resource name string. - * @param {String} project - * @returns {String} - */ -ConfigServiceV2Client.prototype.projectPath = function(project) { - return PROJECT_PATH_TEMPLATE.render({ - project: project - }); -}; - -/** - * Parses the projectName from a project resource. - * @param {String} projectName - * A fully-qualified path representing a project resources. - * @returns {String} - A string representing the project. - */ -ConfigServiceV2Client.prototype.matchProjectFromProjectName = function(projectName) { - return PROJECT_PATH_TEMPLATE.match(projectName).project; -}; - -/** - * Returns a fully-qualified sink resource name string. - * @param {String} project - * @param {String} sink - * @returns {String} - */ -ConfigServiceV2Client.prototype.sinkPath = function(project, sink) { - return SINK_PATH_TEMPLATE.render({ - project: project, - sink: sink - }); -}; - -/** - * Parses the sinkName from a sink resource. - * @param {String} sinkName - * A fully-qualified path representing a sink resources. - * @returns {String} - A string representing the project. - */ -ConfigServiceV2Client.prototype.matchProjectFromSinkName = function(sinkName) { - return SINK_PATH_TEMPLATE.match(sinkName).project; -}; - -/** - * Parses the sinkName from a sink resource. - * @param {String} sinkName - * A fully-qualified path representing a sink resources. - * @returns {String} - A string representing the sink. - */ -ConfigServiceV2Client.prototype.matchSinkFromSinkName = function(sinkName) { - return SINK_PATH_TEMPLATE.match(sinkName).sink; -}; - -/** - * Get the project ID used by this class. - * @aram {function(Error, string)} callback - the callback to be called with - * the current project Id. - */ -ConfigServiceV2Client.prototype.getProjectId = function(callback) { - return this.auth.getProjectId(callback); -}; - -// Service calls - -/** - * Lists sinks. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose sinks are to be listed. - * Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [LogSink]{@link LogSink}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListSinksResponse]{@link ListSinksResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [LogSink]{@link LogSink}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [LogSink]{@link LogSink} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListSinksResponse]{@link ListSinksResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.configServiceV2Client(); - * var formattedParent = client.projectPath("[PROJECT]"); - * // Iterate over all elements. - * client.listSinks({parent: formattedParent}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }).catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listSinks(nextRequest, options).then(callback); - * } - * } - * client.listSinks({parent: formattedParent}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -ConfigServiceV2Client.prototype.listSinks = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listSinks(request, options, callback); -}; - -/** - * Equivalent to {@link listSinks}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listSinks} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The parent resource whose sinks are to be listed. - * Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [LogSink]{@link LogSink} on 'data' event. - * - * @example - * - * var client = loggingV2.configServiceV2Client(); - * var formattedParent = client.projectPath("[PROJECT]"); - * client.listSinksStream({parent: formattedParent}).on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.error(err); - * }); - */ -ConfigServiceV2Client.prototype.listSinksStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listSinks.createStream(this._listSinks, request, options); -}; - -/** - * Gets a sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The parent resource name of the sink: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [LogSink]{@link LogSink}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [LogSink]{@link LogSink}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.configServiceV2Client(); - * var formattedSinkName = client.sinkPath("[PROJECT]", "[SINK]"); - * client.getSink({sinkName: formattedSinkName}).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }).catch(function(err) { - * console.error(err); - * }); - */ -ConfigServiceV2Client.prototype.getSink = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._getSink(request, options, callback); -}; - -/** - * Creates a sink that exports specified log entries to a destination. The - * export of newly-ingested log entries begins immediately, unless the current - * time is outside the sink's start and end times or the sink's - * `writer_identity` is not permitted to write to the destination. A sink can - * export log entries only from the resource owning the sink. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource in which to create the sink: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * - * Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. - * @param {Object} request.sink - * Required. The new sink, whose `name` parameter is a sink identifier that - * is not already in use. - * - * This object should have the same structure as [LogSink]{@link LogSink} - * @param {boolean=} request.uniqueWriterIdentity - * Optional. Determines the kind of IAM identity returned as `writer_identity` - * in the new sink. If this value is omitted or set to false, and if the - * sink's parent is a project, then the value returned as `writer_identity` is - * `cloud-logs@google.com`, the same identity used before the addition of - * writer identities to this API. The sink's destination must be in the same - * project as the sink itself. - * - * If this field is set to true, or if the sink is owned by a non-project - * resource such as an organization, then the value of `writer_identity` will - * be a unique service account used only for exports from the new sink. For - * more information, see `writer_identity` in {@link LogSink}. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [LogSink]{@link LogSink}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [LogSink]{@link LogSink}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.configServiceV2Client(); - * var formattedParent = client.projectPath("[PROJECT]"); - * var sink = {}; - * var request = { - * parent: formattedParent, - * sink: sink - * }; - * client.createSink(request).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }).catch(function(err) { - * console.error(err); - * }); - */ -ConfigServiceV2Client.prototype.createSink = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._createSink(request, options, callback); -}; - -/** - * Updates a sink. If the named sink doesn't exist, then this method is - * identical to - * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create). - * If the named sink does exist, then this method replaces the following - * fields in the existing sink with values from the new sink: `destination`, - * `filter`, `output_version_format`, `start_time`, and `end_time`. - * The updated filter might also have a new `writer_identity`; see the - * `unique_writer_identity` field. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The full resource name of the sink to update, including the - * parent resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * @param {Object} request.sink - * Required. The updated sink, whose name is the same identifier that appears - * as part of `sink_name`. If `sink_name` does not exist, then - * this method creates a new sink. - * - * This object should have the same structure as [LogSink]{@link LogSink} - * @param {boolean=} request.uniqueWriterIdentity - * Optional. See - * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create) - * for a description of this field. When updating a sink, the effect of this - * field on the value of `writer_identity` in the updated sink depends on both - * the old and new values of this field: - * - * + If the old and new values of this field are both false or both true, - * then there is no change to the sink's `writer_identity`. - * + If the old value was false and the new value is true, then - * `writer_identity` is changed to a unique service account. - * + It is an error if the old value was true and the new value is false. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [LogSink]{@link LogSink}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [LogSink]{@link LogSink}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.configServiceV2Client(); - * var formattedSinkName = client.sinkPath("[PROJECT]", "[SINK]"); - * var sink = {}; - * var request = { - * sinkName: formattedSinkName, - * sink: sink - * }; - * client.updateSink(request).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }).catch(function(err) { - * console.error(err); - * }); - */ -ConfigServiceV2Client.prototype.updateSink = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._updateSink(request, options, callback); -}; - -/** - * Deletes a sink. If the sink has a unique `writer_identity`, then that - * service account is also deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.sinkName - * Required. The full resource name of the sink to delete, including the - * parent resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * - * It is an error if the sink does not exist. Example: - * `"projects/my-project-id/sinks/my-sink-id"`. It is an error if - * the sink does not exist. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error)=} callback - * The function which will be called with the result of the API call. - * @return {Promise} - The promise which resolves when API call finishes. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.configServiceV2Client(); - * var formattedSinkName = client.sinkPath("[PROJECT]", "[SINK]"); - * client.deleteSink({sinkName: formattedSinkName}).catch(function(err) { - * console.error(err); - * }); - */ -ConfigServiceV2Client.prototype.deleteSink = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._deleteSink(request, options, callback); -}; - -function ConfigServiceV2ClientBuilder(gaxGrpc) { - if (!(this instanceof ConfigServiceV2ClientBuilder)) { - return new ConfigServiceV2ClientBuilder(gaxGrpc); - } - - var configServiceV2Client = gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/logging/v2/logging_config.proto' - }]); - extend(this, configServiceV2Client.google.logging.v2); - - - /** - * Build a new instance of {@link ConfigServiceV2Client}. - * - * @param {Object=} opts - The optional parameters. - * @param {String=} opts.servicePath - * The domain name of the API remote host. - * @param {number=} opts.port - * The port on which to connect to the remote host. - * @param {grpc.ClientCredentials=} opts.sslCreds - * A ClientCredentials for use with an SSL-enabled channel. - * @param {Object=} opts.clientConfig - * The customized config to build the call settings. See - * {@link gax.constructSettings} for the format. - */ - this.configServiceV2Client = function(opts) { - return new ConfigServiceV2Client(gaxGrpc, configServiceV2Client, opts); - }; - extend(this.configServiceV2Client, ConfigServiceV2Client); -} -module.exports = ConfigServiceV2ClientBuilder; -module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS; -module.exports.ALL_SCOPES = ALL_SCOPES; \ No newline at end of file diff --git a/packages/logging/src/v2/config_service_v2_client_config.json b/packages/logging/src/v2/config_service_v2_client_config.json deleted file mode 100644 index 2c1685982f6..00000000000 --- a/packages/logging/src/v2/config_service_v2_client_config.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "interfaces": { - "google.logging.v2.ConfigServiceV2": { - "retry_codes": { - "idempotent": [ - "DEADLINE_EXCEEDED", - "UNAVAILABLE" - ], - "non_idempotent": [] - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.2, - "max_retry_delay_millis": 1000, - "initial_rpc_timeout_millis": 2000, - "rpc_timeout_multiplier": 1.5, - "max_rpc_timeout_millis": 30000, - "total_timeout_millis": 45000 - } - }, - "methods": { - "ListSinks": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "GetSink": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "CreateSink": { - "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "UpdateSink": { - "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "DeleteSink": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - } - } - } - } -} diff --git a/packages/logging/src/v2/doc/doc_google_api_label.js b/packages/logging/src/v2/doc/doc_google_api_label.js deleted file mode 100644 index 64701d613ac..00000000000 --- a/packages/logging/src/v2/doc/doc_google_api_label.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A description of a label. - * - * @external "google.api.LabelDescriptor" - * @property {string} key - * The label key. - * - * @property {number} valueType - * The type of data that can be assigned to the label. - * - * The number should be among the values of [google.api.LabelDescriptor.ValueType]{@link external:"google.api.LabelDescriptor.ValueType"} - * - * @property {string} description - * A human-readable description for the label. - * - * @see [google.api.LabelDescriptor definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/label.proto} - */ \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_google_api_monitored_resource.js b/packages/logging/src/v2/doc/doc_google_api_monitored_resource.js deleted file mode 100644 index bb2c3107f8f..00000000000 --- a/packages/logging/src/v2/doc/doc_google_api_monitored_resource.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * An object that describes the schema of a {@link MonitoredResource} object using a - * type name and a set of labels. For example, the monitored resource - * descriptor for Google Compute Engine VM instances has a type of - * `"gce_instance"` and specifies the use of the labels `"instance_id"` and - * `"zone"` to identify particular VM instances. - * - * Different APIs can support different monitored resource types. APIs generally - * provide a `list` method that returns the monitored resource descriptors used - * by the API. - * - * @external "google.api.MonitoredResourceDescriptor" - * @property {string} name - * Optional. The resource name of the monitored resource descriptor: - * `"projects/{project_id}/monitoredResourceDescriptors/{type}"` where - * {type} is the value of the `type` field in this object and - * {project_id} is a project ID that provides API-specific context for - * accessing the type. APIs that do not use project information can use the - * resource name format `"monitoredResourceDescriptors/{type}"`. - * - * @property {string} type - * Required. The monitored resource type. For example, the type - * `"cloudsql_database"` represents databases in Google Cloud SQL. - * The maximum length of this value is 256 characters. - * - * @property {string} displayName - * Optional. A concise name for the monitored resource type that might be - * displayed in user interfaces. It should be a Title Cased Noun Phrase, - * without any article or other determiners. For example, - * `"Google Cloud SQL Database"`. - * - * @property {string} description - * Optional. A detailed description of the monitored resource type that might - * be used in documentation. - * - * @property {Object[]} labels - * Required. A set of labels used to describe instances of this monitored - * resource type. For example, an individual Google Cloud SQL database is - * identified by values for the labels `"database_id"` and `"zone"`. - * - * This object should have the same structure as [google.api.LabelDescriptor]{@link external:"google.api.LabelDescriptor"} - * - * @see [google.api.MonitoredResourceDescriptor definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/monitored_resource.proto} - */ - -/** - * An object representing a resource that can be used for monitoring, logging, - * billing, or other purposes. Examples include virtual machine instances, - * databases, and storage devices such as disks. The `type` field identifies a - * {@link MonitoredResourceDescriptor} object that describes the resource's - * schema. Information in the `labels` field identifies the actual resource and - * its attributes according to the schema. For example, a particular Compute - * Engine VM instance could be represented by the following object, because the - * {@link MonitoredResourceDescriptor} for `"gce_instance"` has labels - * `"instance_id"` and `"zone"`: - * - * { "type": "gce_instance", - * "labels": { "instance_id": "12345678901234", - * "zone": "us-central1-a" }} - * - * @external "google.api.MonitoredResource" - * @property {string} type - * Required. The monitored resource type. This field must match - * the `type` field of a {@link MonitoredResourceDescriptor} object. For - * example, the type of a Cloud SQL database is `"cloudsql_database"`. - * - * @property {Object.} labels - * Required. Values for all of the labels listed in the associated monitored - * resource descriptor. For example, Cloud SQL databases use the labels - * `"database_id"` and `"zone"`. - * - * @see [google.api.MonitoredResource definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/monitored_resource.proto} - */ \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_google_logging_type_http_request.js b/packages/logging/src/v2/doc/doc_google_logging_type_http_request.js deleted file mode 100644 index c424c34a7cd..00000000000 --- a/packages/logging/src/v2/doc/doc_google_logging_type_http_request.js +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A common proto for logging HTTP requests. Only contains semantics - * defined by the HTTP specification. Product-specific logging - * information MUST be defined in a separate message. - * - * @external "google.logging.type.HttpRequest" - * @property {string} requestMethod - * The request method. Examples: `"GET"`, `"HEAD"`, `"PUT"`, `"POST"`. - * - * @property {string} requestUrl - * The scheme (http, https), the host name, the path and the query - * portion of the URL that was requested. - * Example: `"http://example.com/some/info?color=red"`. - * - * @property {number} requestSize - * The size of the HTTP request message in bytes, including the request - * headers and the request body. - * - * @property {number} status - * The response code indicating the status of response. - * Examples: 200, 404. - * - * @property {number} responseSize - * The size of the HTTP response message sent back to the client, in bytes, - * including the response headers and the response body. - * - * @property {string} userAgent - * The user agent sent by the client. Example: - * `"Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)"`. - * - * @property {string} remoteIp - * The IP address (IPv4 or IPv6) of the client that issued the HTTP - * request. Examples: `"192.168.1.1"`, `"FE80::0202:B3FF:FE1E:8329"`. - * - * @property {string} serverIp - * The IP address (IPv4 or IPv6) of the origin server that the request was - * sent to. - * - * @property {string} referer - * The referer URL of the request, as defined in - * [HTTP/1.1 Header Field Definitions](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). - * - * @property {Object} latency - * The request processing latency on the server, from the time the request was - * received until the response was sent. - * - * This object should have the same structure as [google.protobuf.Duration]{@link external:"google.protobuf.Duration"} - * - * @property {boolean} cacheLookup - * Whether or not a cache lookup was attempted. - * - * @property {boolean} cacheHit - * Whether or not an entity was served from cache - * (with or without validation). - * - * @property {boolean} cacheValidatedWithOriginServer - * Whether or not the response was validated with the origin server before - * being served from cache. This field is only meaningful if `cache_hit` is - * True. - * - * @property {number} cacheFillBytes - * The number of HTTP response bytes inserted into cache. Set only when a - * cache fill was attempted. - * - * @see [google.logging.type.HttpRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/type/http_request.proto} - */ \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_google_protobuf_any.js b/packages/logging/src/v2/doc/doc_google_protobuf_any.js deleted file mode 100644 index 0697ec15814..00000000000 --- a/packages/logging/src/v2/doc/doc_google_protobuf_any.js +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * `Any` contains an arbitrary serialized protocol buffer message along with a - * URL that describes the type of the serialized message. - * - * Protobuf library provides support to pack/unpack Any values in the form - * of utility functions or additional generated methods of the Any type. - * - * Example 1: Pack and unpack a message in C++. - * - * Foo foo = ...; - * Any any; - * any.PackFrom(foo); - * ... - * if (any.UnpackTo(&foo)) { - * ... - * } - * - * Example 2: Pack and unpack a message in Java. - * - * Foo foo = ...; - * Any any = Any.pack(foo); - * ... - * if (any.is(Foo.class)) { - * foo = any.unpack(Foo.class); - * } - * - * Example 3: Pack and unpack a message in Python. - * - * foo = Foo(...) - * any = Any() - * any.Pack(foo) - * ... - * if any.Is(Foo.DESCRIPTOR): - * any.Unpack(foo) - * ... - * - * The pack methods provided by protobuf library will by default use - * 'type.googleapis.com/full.type.name' as the type URL and the unpack - * methods only use the fully qualified type name after the last '/' - * in the type URL, for example "foo.bar.com/x/y.z" will yield type - * name "y.z". - * - * - * # JSON - * - * The JSON representation of an `Any` value uses the regular - * representation of the deserialized, embedded message, with an - * additional field `@type` which contains the type URL. Example: - * - * package google.profile; - * message Person { - * string first_name = 1; - * string last_name = 2; - * } - * - * { - * "@type": "type.googleapis.com/google.profile.Person", - * "firstName": , - * "lastName": - * } - * - * If the embedded message type is well-known and has a custom JSON - * representation, that representation will be embedded adding a field - * `value` which holds the custom JSON in addition to the `@type` - * field. Example (for message {@link google.protobuf.Duration}): - * - * { - * "@type": "type.googleapis.com/google.protobuf.Duration", - * "value": "1.212s" - * } - * - * @external "google.protobuf.Any" - * @property {string} typeUrl - * A URL/resource name whose content describes the type of the - * serialized protocol buffer message. - * - * For URLs which use the scheme `http`, `https`, or no scheme, the - * following restrictions and interpretations apply: - * - * * If no scheme is provided, `https` is assumed. - * * The last segment of the URL's path must represent the fully - * qualified name of the type (as in `path/google.protobuf.Duration`). - * The name should be in a canonical form (e.g., leading "." is - * not accepted). - * * An HTTP GET on the URL must yield a {@link google.protobuf.Type} - * value in binary format, or produce an error. - * * Applications are allowed to cache lookup results based on the - * URL, or have them precompiled into a binary to avoid any - * lookup. Therefore, binary compatibility needs to be preserved - * on changes to types. (Use versioned type names to manage - * breaking changes.) - * - * Schemes other than `http`, `https` (or the empty scheme) might be - * used with implementation specific semantics. - * - * @property {string} value - * Must be a valid serialized protocol buffer of the above specified type. - * - * @see [google.protobuf.Any definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/any.proto} - */ \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_google_protobuf_duration.js b/packages/logging/src/v2/doc/doc_google_protobuf_duration.js deleted file mode 100644 index b81fd71f130..00000000000 --- a/packages/logging/src/v2/doc/doc_google_protobuf_duration.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A Duration represents a signed, fixed-length span of time represented - * as a count of seconds and fractions of seconds at nanosecond - * resolution. It is independent of any calendar and concepts like "day" - * or "month". It is related to Timestamp in that the difference between - * two Timestamp values is a Duration and it can be added or subtracted - * from a Timestamp. Range is approximately +-10,000 years. - * - * Example 1: Compute Duration from two Timestamps in pseudo code. - * - * Timestamp start = ...; - * Timestamp end = ...; - * Duration duration = ...; - * - * duration.seconds = end.seconds - start.seconds; - * duration.nanos = end.nanos - start.nanos; - * - * if (duration.seconds < 0 && duration.nanos > 0) { - * duration.seconds += 1; - * duration.nanos -= 1000000000; - * } else if (durations.seconds > 0 && duration.nanos < 0) { - * duration.seconds -= 1; - * duration.nanos += 1000000000; - * } - * - * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. - * - * Timestamp start = ...; - * Duration duration = ...; - * Timestamp end = ...; - * - * end.seconds = start.seconds + duration.seconds; - * end.nanos = start.nanos + duration.nanos; - * - * if (end.nanos < 0) { - * end.seconds -= 1; - * end.nanos += 1000000000; - * } else if (end.nanos >= 1000000000) { - * end.seconds += 1; - * end.nanos -= 1000000000; - * } - * - * Example 3: Compute Duration from datetime.timedelta in Python. - * - * td = datetime.timedelta(days=3, minutes=10) - * duration = Duration() - * duration.FromTimedelta(td) - * - * @external "google.protobuf.Duration" - * @property {number} seconds - * Signed seconds of the span of time. Must be from -315,576,000,000 - * to +315,576,000,000 inclusive. - * - * @property {number} nanos - * Signed fractions of a second at nanosecond resolution of the span - * of time. Durations less than one second are represented with a 0 - * `seconds` field and a positive or negative `nanos` field. For durations - * of one second or more, a non-zero value for the `nanos` field must be - * of the same sign as the `seconds` field. Must be from -999,999,999 - * to +999,999,999 inclusive. - * - * @see [google.protobuf.Duration definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/duration.proto} - */ \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_google_protobuf_timestamp.js b/packages/logging/src/v2/doc/doc_google_protobuf_timestamp.js deleted file mode 100644 index ed8fc627b92..00000000000 --- a/packages/logging/src/v2/doc/doc_google_protobuf_timestamp.js +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A Timestamp represents a point in time independent of any time zone - * or calendar, represented as seconds and fractions of seconds at - * nanosecond resolution in UTC Epoch time. It is encoded using the - * Proleptic Gregorian Calendar which extends the Gregorian calendar - * backwards to year one. It is encoded assuming all minutes are 60 - * seconds long, i.e. leap seconds are "smeared" so that no leap second - * table is needed for interpretation. Range is from - * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. - * By restricting to that range, we ensure that we can convert to - * and from RFC 3339 date strings. - * See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). - * - * Example 1: Compute Timestamp from POSIX `time()`. - * - * Timestamp timestamp; - * timestamp.set_seconds(time(NULL)); - * timestamp.set_nanos(0); - * - * Example 2: Compute Timestamp from POSIX `gettimeofday()`. - * - * struct timeval tv; - * gettimeofday(&tv, NULL); - * - * Timestamp timestamp; - * timestamp.set_seconds(tv.tv_sec); - * timestamp.set_nanos(tv.tv_usec * 1000); - * - * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. - * - * FILETIME ft; - * GetSystemTimeAsFileTime(&ft); - * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; - * - * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z - * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. - * Timestamp timestamp; - * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); - * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); - * - * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. - * - * long millis = System.currentTimeMillis(); - * - * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) - * .setNanos((int) ((millis % 1000) * 1000000)).build(); - * - * - * Example 5: Compute Timestamp from current time in Python. - * - * timestamp = Timestamp() - * timestamp.GetCurrentTime() - * - * @external "google.protobuf.Timestamp" - * @property {number} seconds - * Represents seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * - * @property {number} nanos - * Non-negative fractions of a second at nanosecond resolution. Negative - * second values with fractions must still have non-negative nanos values - * that count forward in time. Must be from 0 to 999,999,999 - * inclusive. - * - * @see [google.protobuf.Timestamp definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto} - */ \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_log_entry.js b/packages/logging/src/v2/doc/doc_log_entry.js deleted file mode 100644 index 194223b50f2..00000000000 --- a/packages/logging/src/v2/doc/doc_log_entry.js +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * An individual entry in a log. - * - * @property {string} logName - * Required. The resource name of the log to which this log entry belongs: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - * "folders/[FOLDER_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded within `log_name`. Example: - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * `[LOG_ID]` must be less than 512 characters long and can only include the - * following characters: upper and lower case alphanumeric characters, - * forward-slash, underscore, hyphen, and period. - * - * For backward compatibility, if `log_name` begins with a forward-slash, such - * as `/projects/...`, then the log entry is ingested as usual but the - * forward-slash is removed. Listing the log entry will not show the leading - * slash and filtering for a log name with a leading slash will never return - * any results. - * - * @property {Object} resource - * Required. The monitored resource associated with this log entry. - * Example: a log entry that reports a database error would be - * associated with the monitored resource designating the particular - * database that reported the error. - * - * This object should have the same structure as [google.api.MonitoredResource]{@link external:"google.api.MonitoredResource"} - * - * @property {Object} protoPayload - * The log entry payload, represented as a protocol buffer. Some - * Google Cloud Platform services use this field for their log - * entry payloads. - * - * This object should have the same structure as [google.protobuf.Any]{@link external:"google.protobuf.Any"} - * - * @property {string} textPayload - * The log entry payload, represented as a Unicode string (UTF-8). - * - * @property {Object} jsonPayload - * The log entry payload, represented as a structure that is - * expressed as a JSON object. - * - * This object should have the same structure as [google.protobuf.Struct]{@link external:"google.protobuf.Struct"} - * - * @property {Object} timestamp - * Optional. The time the event described by the log entry occurred. If - * omitted in a new log entry, Stackdriver Logging will insert the time the - * log entry is received. Stackdriver Logging might reject log entries whose - * time stamps are more than a couple of hours in the future. Log entries - * with time stamps in the past are accepted. - * - * This object should have the same structure as [google.protobuf.Timestamp]{@link external:"google.protobuf.Timestamp"} - * - * @property {Object} receiveTimestamp - * Output only. The time the log entry was received by Stackdriver Logging. - * - * This object should have the same structure as [google.protobuf.Timestamp]{@link external:"google.protobuf.Timestamp"} - * - * @property {number} severity - * Optional. The severity of the log entry. The default value is - * `LogSeverity.DEFAULT`. - * - * The number should be among the values of [google.logging.type.LogSeverity]{@link external:"google.logging.type.LogSeverity"} - * - * @property {string} insertId - * Optional. A unique identifier for the log entry. If you provide a value, - * then Stackdriver Logging considers other log entries in the same project, - * with the same `timestamp`, and with the same `insert_id` to be duplicates - * which can be removed. If omitted in new log entries, then Stackdriver - * Logging will insert its own unique identifier. The `insert_id` is used - * to order log entries that have the same `timestamp` value. - * - * @property {Object} httpRequest - * Optional. Information about the HTTP request associated with this - * log entry, if applicable. - * - * This object should have the same structure as [google.logging.type.HttpRequest]{@link external:"google.logging.type.HttpRequest"} - * - * @property {Object.} labels - * Optional. A set of user-defined (key, value) data that provides additional - * information about the log entry. - * - * @property {Object} operation - * Optional. Information about an operation associated with the log entry, if - * applicable. - * - * This object should have the same structure as [LogEntryOperation]{@link LogEntryOperation} - * - * @property {string} trace - * Optional. Resource name of the trace associated with the log entry, if any. - * If it contains a relative resource name, the name is assumed to be relative - * to `//tracing.googleapis.com`. Example: - * `projects/my-projectid/traces/06796866738c859f2f19b7cfb3214824` - * - * @property {Object} sourceLocation - * Optional. Source code location information associated with the log entry, - * if any. - * - * This object should have the same structure as [LogEntrySourceLocation]{@link LogEntrySourceLocation} - * - * @class - * @see [google.logging.v2.LogEntry definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/log_entry.proto} - */ -var LogEntry = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Additional information about a potentially long-running operation with which - * a log entry is associated. - * - * @property {string} id - * Optional. An arbitrary operation identifier. Log entries with the - * same identifier are assumed to be part of the same operation. - * - * @property {string} producer - * Optional. An arbitrary producer identifier. The combination of - * `id` and `producer` must be globally unique. Examples for `producer`: - * `"MyDivision.MyBigCompany.com"`, `"github.com/MyProject/MyApplication"`. - * - * @property {boolean} first - * Optional. Set this to True if this is the first log entry in the operation. - * - * @property {boolean} last - * Optional. Set this to True if this is the last log entry in the operation. - * - * @class - * @see [google.logging.v2.LogEntryOperation definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/log_entry.proto} - */ -var LogEntryOperation = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Additional information about the source code location that produced the log - * entry. - * - * @property {string} file - * Optional. Source file name. Depending on the runtime environment, this - * might be a simple name or a fully-qualified name. - * - * @property {number} line - * Optional. Line within the source file. 1-based; 0 indicates no line number - * available. - * - * @property {string} function - * Optional. Human-readable name of the function or method being invoked, with - * optional context such as the class or package name. This information may be - * used in contexts such as the logs viewer, where a file and line number are - * less meaningful. The format can vary by language. For example: - * `qual.if.ied.Class.method` (Java), `dir/package.func` (Go), `function` - * (Python). - * - * @class - * @see [google.logging.v2.LogEntrySourceLocation definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/log_entry.proto} - */ -var LogEntrySourceLocation = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_logging.js b/packages/logging/src/v2/doc/doc_logging.js deleted file mode 100644 index a74b92ed98b..00000000000 --- a/packages/logging/src/v2/doc/doc_logging.js +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * The parameters to DeleteLog. - * - * @property {string} logName - * Required. The resource name of the log to delete: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - * "folders/[FOLDER_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"`, - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * For more information about log names, see - * {@link LogEntry}. - * - * @class - * @see [google.logging.v2.DeleteLogRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var DeleteLogRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to WriteLogEntries. - * - * @property {string} logName - * Optional. A default log resource name that is assigned to all log entries - * in `entries` that do not specify a value for `log_name`: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/logs/[LOG_ID]" - * "folders/[FOLDER_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"` or - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * For more information about log names, see - * {@link LogEntry}. - * - * @property {Object} resource - * Optional. A default monitored resource object that is assigned to all log - * entries in `entries` that do not specify a value for `resource`. Example: - * - * { "type": "gce_instance", - * "labels": { - * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - * - * See {@link LogEntry}. - * - * This object should have the same structure as [google.api.MonitoredResource]{@link external:"google.api.MonitoredResource"} - * - * @property {Object.} labels - * Optional. Default labels that are added to the `labels` field of all log - * entries in `entries`. If a log entry already has a label with the same key - * as a label in this parameter, then the log entry's label is not changed. - * See {@link LogEntry}. - * - * @property {Object[]} entries - * Required. The log entries to write. Values supplied for the fields - * `log_name`, `resource`, and `labels` in this `entries.write` request are - * inserted into those log entries in this list that do not provide their own - * values. - * - * Stackdriver Logging also creates and inserts values for `timestamp` and - * `insert_id` if the entries do not provide them. The created `insert_id` for - * the N'th entry in this list will be greater than earlier entries and less - * than later entries. Otherwise, the order of log entries in this list does - * not matter. - * - * To improve throughput and to avoid exceeding the - * [quota limit](https://cloud.google.com/logging/quota-policy) for calls to `entries.write`, - * you should write multiple log entries at once rather than - * calling this method for each individual log entry. - * - * This object should have the same structure as [LogEntry]{@link LogEntry} - * - * @property {boolean} partialSuccess - * Optional. Whether valid entries should be written even if some other - * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any - * entry is not written, then the response status is the error associated - * with one of the failed entries and the response includes error details - * keyed by the entries' zero-based index in the `entries.write` method. - * - * @class - * @see [google.logging.v2.WriteLogEntriesRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var WriteLogEntriesRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Result returned from WriteLogEntries. - * empty - * @class - * @see [google.logging.v2.WriteLogEntriesResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var WriteLogEntriesResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Error details for WriteLogEntries with partial success. - * - * @property {Object.} logEntryErrors - * When `WriteLogEntriesRequest.partial_success` is true, records the error - * status for entries that were not written due to a permanent error, keyed - * by the entry's zero-based index in `WriteLogEntriesRequest.entries`. - * - * Failed requests for which no entries are written will not include - * per-entry errors. - * - * @class - * @see [google.logging.v2.WriteLogEntriesPartialErrors definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var WriteLogEntriesPartialErrors = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to `ListLogEntries`. - * - * @property {string[]} projectIds - * Deprecated. Use `resource_names` instead. One or more project identifiers - * or project numbers from which to retrieve log entries. Example: - * `"my-project-1A"`. If present, these project identifiers are converted to - * resource name format and added to the list of resources in - * `resource_names`. - * - * @property {string[]} resourceNames - * Required. Names of one or more parent resources from which to - * retrieve log entries: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * Projects listed in the `project_ids` field are added to this list. - * - * @property {string} filter - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). Only log entries that - * match the filter are returned. An empty filter matches all log entries in - * the resources listed in `resource_names`. Referencing a parent resource - * that is not listed in `resource_names` will cause the filter to return no - * results. - * The maximum length of the filter is 20000 characters. - * - * @property {string} orderBy - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of their `insert_id` values. - * - * @property {number} pageSize - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `next_page_token` in the - * response indicates that more results might be available. - * - * @property {string} pageToken - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `page_token` must be the value of - * `next_page_token` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * - * @class - * @see [google.logging.v2.ListLogEntriesRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var ListLogEntriesRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Result returned from `ListLogEntries`. - * - * @property {Object[]} entries - * A list of log entries. - * - * This object should have the same structure as [LogEntry]{@link LogEntry} - * - * @property {string} nextPageToken - * If there might be more results than those appearing in this response, then - * `nextPageToken` is included. To get the next set of results, call this - * method again using the value of `nextPageToken` as `pageToken`. - * - * If a value for `next_page_token` appears and the `entries` field is empty, - * it means that the search found no log entries so far but it did not have - * time to search all the possible log entries. Retry the method with this - * value for `page_token` to continue the search. Alternatively, consider - * speeding up the search by changing your filter to specify a single log name - * or resource type, or to narrow the time range of the search. - * - * @class - * @see [google.logging.v2.ListLogEntriesResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var ListLogEntriesResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to ListMonitoredResourceDescriptors - * - * @property {number} pageSize - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * - * @property {string} pageToken - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * - * @class - * @see [google.logging.v2.ListMonitoredResourceDescriptorsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var ListMonitoredResourceDescriptorsRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Result returned from ListMonitoredResourceDescriptors. - * - * @property {Object[]} resourceDescriptors - * A list of resource descriptors. - * - * This object should have the same structure as [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"} - * - * @property {string} nextPageToken - * If there might be more results than those appearing in this response, then - * `nextPageToken` is included. To get the next set of results, call this - * method again using the value of `nextPageToken` as `pageToken`. - * - * @class - * @see [google.logging.v2.ListMonitoredResourceDescriptorsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var ListMonitoredResourceDescriptorsResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to ListLogs. - * - * @property {string} parent - * Required. The resource name that owns the logs: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * @property {number} pageSize - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * - * @property {string} pageToken - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * - * @class - * @see [google.logging.v2.ListLogsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var ListLogsRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Result returned from ListLogs. - * - * @property {string[]} logNames - * A list of log names. For example, - * `"projects/my-project/syslog"` or - * `"organizations/123/cloudresourcemanager.googleapis.com%2Factivity"`. - * - * @property {string} nextPageToken - * If there might be more results than those appearing in this response, then - * `nextPageToken` is included. To get the next set of results, call this - * method again using the value of `nextPageToken` as `pageToken`. - * - * @class - * @see [google.logging.v2.ListLogsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto} - */ -var ListLogsResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_logging_config.js b/packages/logging/src/v2/doc/doc_logging_config.js deleted file mode 100644 index 547b2dc54bc..00000000000 --- a/packages/logging/src/v2/doc/doc_logging_config.js +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * Describes a sink used to export log entries to one of the following - * destinations in any project: a Cloud Storage bucket, a BigQuery dataset, or a - * Cloud Pub/Sub topic. A logs filter controls which log entries are - * exported. The sink must be created within a project, organization, billing - * account, or folder. - * - * @property {string} name - * Required. The client-assigned sink identifier, unique within the - * project. Example: `"my-syslog-errors-to-pubsub"`. Sink identifiers are - * limited to 100 characters and can include only the following characters: - * upper and lower-case alphanumeric characters, underscores, hyphens, and - * periods. - * - * @property {string} destination - * Required. The export destination: - * - * "storage.googleapis.com/[GCS_BUCKET]" - * "bigquery.googleapis.com/projects/[PROJECT_ID]/datasets/[DATASET]" - * "pubsub.googleapis.com/projects/[PROJECT_ID]/topics/[TOPIC_ID]" - * - * The sink's `writer_identity`, set when the sink is created, must - * have permission to write to the destination or else the log - * entries are not exported. For more information, see - * [Exporting Logs With Sinks](https://cloud.google.com/logging/docs/api/tasks/exporting-logs). - * - * @property {string} filter - * Optional. - * An [advanced logs filter](https://cloud.google.com/logging/docs/view/advanced_filters). The only - * exported log entries are those that are in the resource owning the sink and - * that match the filter. The filter must use the log entry format specified - * by the `output_version_format` parameter. For example, in the v2 format: - * - * logName="projects/[PROJECT_ID]/logs/[LOG_ID]" AND severity>=ERROR - * - * @property {number} outputVersionFormat - * Optional. The log entry format to use for this sink's exported log - * entries. The v2 format is used by default. - * **The v1 format is deprecated** and should be used only as part of a - * migration effort to v2. - * See [Migration to the v2 API](https://cloud.google.com/logging/docs/api/v2/migration-to-v2). - * - * The number should be among the values of [VersionFormat]{@link VersionFormat} - * - * @property {string} writerIdentity - * Output only. An IAM identity—a service account or group—under - * which Stackdriver Logging writes the exported log entries to the sink's - * destination. This field is set by - * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create) - * and - * [sinks.update](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/update), - * based on the setting of `unique_writer_identity` in those methods. - * - * Until you grant this identity write-access to the destination, log entry - * exports from this sink will fail. For more information, - * see [Granting access for a - * resource](https://cloud.google.com/iam/docs/granting-roles-to-service-accounts#granting_access_to_a_service_account_for_a_resource). - * Consult the destination service's documentation to determine the - * appropriate IAM roles to assign to the identity. - * - * @property {boolean} includeChildren - * Optional. This field applies only to sinks owned by organizations and - * folders. If the field is false, the default, only the logs owned by the - * sink's parent resource are available for export. If the field is true, then - * logs from all the projects, folders, and billing accounts contained in the - * sink's parent resource are also available for export. Whether a particular - * log entry from the children is exported depends on the sink's filter - * expression. For example, if this field is true, then the filter - * `resource.type=gce_instance` would export all Compute Engine VM instance - * log entries from all projects in the sink's parent. To only export entries - * from certain child projects, filter on the project part of the log name: - * - * logName:("projects/test-project1/" OR "projects/test-project2/") AND - * resource.type=gce_instance - * - * @property {Object} startTime - * Optional. The time at which this sink will begin exporting log entries. - * Log entries are exported only if their timestamp is not earlier than the - * start time. The default value of this field is the time the sink is - * created or updated. - * - * This object should have the same structure as [google.protobuf.Timestamp]{@link external:"google.protobuf.Timestamp"} - * - * @property {Object} endTime - * Optional. The time at which this sink will stop exporting log entries. Log - * entries are exported only if their timestamp is earlier than the end time. - * If this field is not supplied, there is no end time. If both a start time - * and an end time are provided, then the end time must be later than the - * start time. - * - * This object should have the same structure as [google.protobuf.Timestamp]{@link external:"google.protobuf.Timestamp"} - * - * @class - * @see [google.logging.v2.LogSink definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_config.proto} - */ -var LogSink = { - // This is for documentation. Actual contents will be loaded by gRPC. - - /** - * Available log entry formats. Log entries can be written to Stackdriver - * Logging in either format and can be exported in either format. - * Version 2 is the preferred format. - * - * @enum {number} - */ - VersionFormat: { - - /** - * An unspecified format version that will default to V2. - */ - VERSION_FORMAT_UNSPECIFIED: 0, - - /** - * `LogEntry` version 2 format. - */ - V2: 1, - - /** - * `LogEntry` version 1 format. - */ - V1: 2 - } -}; - -/** - * The parameters to `ListSinks`. - * - * @property {string} parent - * Required. The parent resource whose sinks are to be listed: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * @property {string} pageToken - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * - * @property {number} pageSize - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * - * @class - * @see [google.logging.v2.ListSinksRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_config.proto} - */ -var ListSinksRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Result returned from `ListSinks`. - * - * @property {Object[]} sinks - * A list of sinks. - * - * This object should have the same structure as [LogSink]{@link LogSink} - * - * @property {string} nextPageToken - * If there might be more results than appear in this response, then - * `nextPageToken` is included. To get the next set of results, call the same - * method again using the value of `nextPageToken` as `pageToken`. - * - * @class - * @see [google.logging.v2.ListSinksResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_config.proto} - */ -var ListSinksResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to `GetSink`. - * - * @property {string} sinkName - * Required. The resource name of the sink: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * - * @class - * @see [google.logging.v2.GetSinkRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_config.proto} - */ -var GetSinkRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to `CreateSink`. - * - * @property {string} parent - * Required. The resource in which to create the sink: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]" - * "folders/[FOLDER_ID]" - * - * Examples: `"projects/my-logging-project"`, `"organizations/123456789"`. - * - * @property {Object} sink - * Required. The new sink, whose `name` parameter is a sink identifier that - * is not already in use. - * - * This object should have the same structure as [LogSink]{@link LogSink} - * - * @property {boolean} uniqueWriterIdentity - * Optional. Determines the kind of IAM identity returned as `writer_identity` - * in the new sink. If this value is omitted or set to false, and if the - * sink's parent is a project, then the value returned as `writer_identity` is - * the same group or service account used by Stackdriver Logging before the - * addition of writer identities to this API. The sink's destination must be - * in the same project as the sink itself. - * - * If this field is set to true, or if the sink is owned by a non-project - * resource such as an organization, then the value of `writer_identity` will - * be a unique service account used only for exports from the new sink. For - * more information, see `writer_identity` in {@link LogSink}. - * - * @class - * @see [google.logging.v2.CreateSinkRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_config.proto} - */ -var CreateSinkRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to `UpdateSink`. - * - * @property {string} sinkName - * Required. The full resource name of the sink to update, including the - * parent resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * - * @property {Object} sink - * Required. The updated sink, whose name is the same identifier that appears - * as part of `sink_name`. If `sink_name` does not exist, then - * this method creates a new sink. - * - * This object should have the same structure as [LogSink]{@link LogSink} - * - * @property {boolean} uniqueWriterIdentity - * Optional. See - * [sinks.create](https://cloud.google.com/logging/docs/api/reference/rest/v2/projects.sinks/create) - * for a description of this field. When updating a sink, the effect of this - * field on the value of `writer_identity` in the updated sink depends on both - * the old and new values of this field: - * - * + If the old and new values of this field are both false or both true, - * then there is no change to the sink's `writer_identity`. - * + If the old value is false and the new value is true, then - * `writer_identity` is changed to a unique service account. - * + It is an error if the old value is true and the new value is false. - * - * @class - * @see [google.logging.v2.UpdateSinkRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_config.proto} - */ -var UpdateSinkRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to `DeleteSink`. - * - * @property {string} sinkName - * Required. The full resource name of the sink to delete, including the - * parent resource and the sink identifier: - * - * "projects/[PROJECT_ID]/sinks/[SINK_ID]" - * "organizations/[ORGANIZATION_ID]/sinks/[SINK_ID]" - * "billingAccounts/[BILLING_ACCOUNT_ID]/sinks/[SINK_ID]" - * "folders/[FOLDER_ID]/sinks/[SINK_ID]" - * - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * - * @class - * @see [google.logging.v2.DeleteSinkRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_config.proto} - */ -var DeleteSinkRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/packages/logging/src/v2/doc/doc_logging_metrics.js b/packages/logging/src/v2/doc/doc_logging_metrics.js deleted file mode 100644 index b76532ab87f..00000000000 --- a/packages/logging/src/v2/doc/doc_logging_metrics.js +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * Describes a logs-based metric. The value of the metric is the - * number of log entries that match a logs filter in a given time interval. - * - * @property {string} name - * Required. The client-assigned metric identifier. - * Examples: `"error_count"`, `"nginx/requests"`. - * - * Metric identifiers are limited to 100 characters and can include - * only the following characters: `A-Z`, `a-z`, `0-9`, and the - * special characters `_-.,+!*',()%/`. The forward-slash character - * (`/`) denotes a hierarchy of name pieces, and it cannot be the - * first character of the name. - * - * The metric identifier in this field must not be - * [URL-encoded](https://en.wikipedia.org/wiki/Percent-encoding). - * However, when the metric identifier appears as the `[METRIC_ID]` - * part of a `metric_name` API parameter, then the metric identifier - * must be URL-encoded. Example: - * `"projects/my-project/metrics/nginx%2Frequests"`. - * - * @property {string} description - * Optional. A description of this metric, which is used in documentation. - * - * @property {string} filter - * Required. An [advanced logs filter](https://cloud.google.com/logging/docs/view/advanced_filters) - * which is used to match log entries. - * Example: - * - * "resource.type=gae_app AND severity>=ERROR" - * - * The maximum length of the filter is 20000 characters. - * - * @property {number} version - * Output only. The API version that created or updated this metric. - * The version also dictates the syntax of the filter expression. When a value - * for this field is missing, the default value of V2 should be assumed. - * - * The number should be among the values of [ApiVersion]{@link ApiVersion} - * - * @class - * @see [google.logging.v2.LogMetric definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_metrics.proto} - */ -var LogMetric = { - // This is for documentation. Actual contents will be loaded by gRPC. - - /** - * Stackdriver Logging API version. - * - * @enum {number} - */ - ApiVersion: { - - /** - * Stackdriver Logging API v2. - */ - V2: 0, - - /** - * Stackdriver Logging API v1. - */ - V1: 1 - } -}; - -/** - * The parameters to ListLogMetrics. - * - * @property {string} parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * - * @property {string} pageToken - * Optional. If present, then retrieve the next batch of results from the - * preceding call to this method. `pageToken` must be the value of - * `nextPageToken` from the previous response. The values of other method - * parameters should be identical to those in the previous call. - * - * @property {number} pageSize - * Optional. The maximum number of results to return from this request. - * Non-positive values are ignored. The presence of `nextPageToken` in the - * response indicates that more results might be available. - * - * @class - * @see [google.logging.v2.ListLogMetricsRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_metrics.proto} - */ -var ListLogMetricsRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Result returned from ListLogMetrics. - * - * @property {Object[]} metrics - * A list of logs-based metrics. - * - * This object should have the same structure as [LogMetric]{@link LogMetric} - * - * @property {string} nextPageToken - * If there might be more results than appear in this response, then - * `nextPageToken` is included. To get the next set of results, call this - * method again using the value of `nextPageToken` as `pageToken`. - * - * @class - * @see [google.logging.v2.ListLogMetricsResponse definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_metrics.proto} - */ -var ListLogMetricsResponse = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to GetLogMetric. - * - * @property {string} metricName - * The resource name of the desired metric: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * - * @class - * @see [google.logging.v2.GetLogMetricRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_metrics.proto} - */ -var GetLogMetricRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to CreateLogMetric. - * - * @property {string} parent - * The resource name of the project in which to create the metric: - * - * "projects/[PROJECT_ID]" - * - * The new metric must be provided in the request. - * - * @property {Object} metric - * The new logs-based metric, which must not have an identifier that - * already exists. - * - * This object should have the same structure as [LogMetric]{@link LogMetric} - * - * @class - * @see [google.logging.v2.CreateLogMetricRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_metrics.proto} - */ -var CreateLogMetricRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to UpdateLogMetric. - * - * @property {string} metricName - * The resource name of the metric to update: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * - * The updated metric must be provided in the request and it's - * `name` field must be the same as `[METRIC_ID]` If the metric - * does not exist in `[PROJECT_ID]`, then a new metric is created. - * - * @property {Object} metric - * The updated metric. - * - * This object should have the same structure as [LogMetric]{@link LogMetric} - * - * @class - * @see [google.logging.v2.UpdateLogMetricRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_metrics.proto} - */ -var UpdateLogMetricRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * The parameters to DeleteLogMetric. - * - * @property {string} metricName - * The resource name of the metric to delete: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * - * @class - * @see [google.logging.v2.DeleteLogMetricRequest definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_metrics.proto} - */ -var DeleteLogMetricRequest = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/packages/logging/src/v2/index.js b/packages/logging/src/v2/index.js deleted file mode 100644 index 77db934f011..00000000000 --- a/packages/logging/src/v2/index.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2016 Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ -'use strict'; - -var loggingServiceV2Client = require('./logging_service_v2_client'); -var configServiceV2Client = require('./config_service_v2_client'); -var metricsServiceV2Client = require('./metrics_service_v2_client'); -var gax = require('google-gax'); -var extend = require('extend'); - -function v2(options) { - options = extend({ - scopes: v2.ALL_SCOPES - }, options); - var gaxGrpc = gax.grpc(options); - return extend( - {}, - loggingServiceV2Client(gaxGrpc), - configServiceV2Client(gaxGrpc), - metricsServiceV2Client(gaxGrpc)); -} - -v2.SERVICE_ADDRESS = loggingServiceV2Client.SERVICE_ADDRESS; -v2.ALL_SCOPES = loggingServiceV2Client.ALL_SCOPES; - -module.exports = v2; diff --git a/packages/logging/src/v2/logging_service_v2_client.js b/packages/logging/src/v2/logging_service_v2_client.js deleted file mode 100644 index 3ed647ab0bb..00000000000 --- a/packages/logging/src/v2/logging_service_v2_client.js +++ /dev/null @@ -1,838 +0,0 @@ -/* - * Copyright 2016 Google Inc. All rights reserved. - * - * 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 - * - * http://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. - * - * EDITING INSTRUCTIONS - * This file was generated from the file - * https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging.proto, - * and updates to that file get reflected here through a refresh process. - * For the short term, the refresh process will only be runnable by Google - * engineers. - * - * The only allowed edits are to method and file documentation. A 3-way - * merge preserves those additions if the generated source changes. - */ -/* TODO: introduce line-wrapping so that it never exceeds the limit. */ -/* jscs: disable maximumLineLength */ -'use strict'; - -var configData = require('./logging_service_v2_client_config'); -var extend = require('extend'); -var gax = require('google-gax'); - -var SERVICE_ADDRESS = 'logging.googleapis.com'; - -var DEFAULT_SERVICE_PORT = 443; - -var CODE_GEN_NAME_VERSION = 'gapic/0.1.0'; - -var PAGE_DESCRIPTORS = { - listLogEntries: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'entries'), - listMonitoredResourceDescriptors: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'resourceDescriptors'), - listLogs: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'logNames') -}; - -/** - * The scopes needed to make gRPC calls to all of the methods defined in - * this service. - */ -var ALL_SCOPES = [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write' -]; - -/** - * Service for ingesting and querying logs. - * - * This will be created through a builder function which can be obtained by the module. - * See the following example of how to initialize the module and how to access to the builder. - * @see {@link loggingServiceV2Client} - * - * @example - * var loggingV2 = require('@google-cloud/logging').v2({ - * // optional auth parameters. - * }); - * var client = loggingV2.loggingServiceV2Client(); - * - * @class - */ -function LoggingServiceV2Client(gaxGrpc, grpcClients, opts) { - opts = extend({ - servicePath: SERVICE_ADDRESS, - port: DEFAULT_SERVICE_PORT, - clientConfig: {} - }, opts); - - var googleApiClient = [ - 'gl-node/' + process.versions.node - ]; - if (opts.libName && opts.libVersion) { - googleApiClient.push(opts.libName + '/' + opts.libVersion); - } - googleApiClient.push( - CODE_GEN_NAME_VERSION, - 'gax/' + gax.version, - 'grpc/' + gaxGrpc.grpcVersion - ); - - var bundleDescriptors = { - writeLogEntries: new gax.BundleDescriptor( - 'entries', - [ - 'logName', - 'resource', - 'labels' - ], - null, - gax.createByteLengthFunction(grpcClients.google.logging.v2.LogEntry)) - }; - - var defaults = gaxGrpc.constructSettings( - 'google.logging.v2.LoggingServiceV2', - configData, - opts.clientConfig, - {'x-goog-api-client': googleApiClient.join(' ')}); - - var self = this; - - this.auth = gaxGrpc.auth; - var loggingServiceV2Stub = gaxGrpc.createStub( - grpcClients.google.logging.v2.LoggingServiceV2, - opts); - var loggingServiceV2StubMethods = [ - 'deleteLog', - 'writeLogEntries', - 'listLogEntries', - 'listMonitoredResourceDescriptors', - 'listLogs' - ]; - loggingServiceV2StubMethods.forEach(function(methodName) { - self['_' + methodName] = gax.createApiCall( - loggingServiceV2Stub.then(function(loggingServiceV2Stub) { - return function() { - var args = Array.prototype.slice.call(arguments, 0); - return loggingServiceV2Stub[methodName].apply(loggingServiceV2Stub, args); - }; - }), - defaults[methodName], - PAGE_DESCRIPTORS[methodName] || bundleDescriptors[methodName]); - }); -} - -// Path templates - -var PROJECT_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}'); - -var LOG_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}/logs/{log}'); - -/** - * Returns a fully-qualified project resource name string. - * @param {String} project - * @returns {String} - */ -LoggingServiceV2Client.prototype.projectPath = function(project) { - return PROJECT_PATH_TEMPLATE.render({ - project: project - }); -}; - -/** - * Parses the projectName from a project resource. - * @param {String} projectName - * A fully-qualified path representing a project resources. - * @returns {String} - A string representing the project. - */ -LoggingServiceV2Client.prototype.matchProjectFromProjectName = function(projectName) { - return PROJECT_PATH_TEMPLATE.match(projectName).project; -}; - -/** - * Returns a fully-qualified log resource name string. - * @param {String} project - * @param {String} log - * @returns {String} - */ -LoggingServiceV2Client.prototype.logPath = function(project, log) { - return LOG_PATH_TEMPLATE.render({ - project: project, - log: log - }); -}; - -/** - * Parses the logName from a log resource. - * @param {String} logName - * A fully-qualified path representing a log resources. - * @returns {String} - A string representing the project. - */ -LoggingServiceV2Client.prototype.matchProjectFromLogName = function(logName) { - return LOG_PATH_TEMPLATE.match(logName).project; -}; - -/** - * Parses the logName from a log resource. - * @param {String} logName - * A fully-qualified path representing a log resources. - * @returns {String} - A string representing the log. - */ -LoggingServiceV2Client.prototype.matchLogFromLogName = function(logName) { - return LOG_PATH_TEMPLATE.match(logName).log; -}; - -/** - * Get the project ID used by this class. - * @aram {function(Error, string)} callback - the callback to be called with - * the current project Id. - */ -LoggingServiceV2Client.prototype.getProjectId = function(callback) { - return this.auth.getProjectId(callback); -}; - -// Service calls - -/** - * Deletes all the log entries in a log. - * The log reappears if it receives new entries. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.logName - * Required. The resource name of the log to delete: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"`, - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * For more information about log names, see - * {@link LogEntry}. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error)=} callback - * The function which will be called with the result of the API call. - * @return {Promise} - The promise which resolves when API call finishes. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.loggingServiceV2Client(); - * var formattedLogName = client.logPath("[PROJECT]", "[LOG]"); - * client.deleteLog({logName: formattedLogName}).catch(function(err) { - * console.error(err); - * }); - */ -LoggingServiceV2Client.prototype.deleteLog = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._deleteLog(request, options, callback); -}; - -/** - * Writes log entries to Stackdriver Logging. All log entries are - * written by this method. - * - * @param {Object} request - * The request object that will be sent. - * @param {Object[]} request.entries - * Required. The log entries to write. Values supplied for the fields - * `log_name`, `resource`, and `labels` in this `entries.write` request are - * added to those log entries that do not provide their own values for the - * fields. - * - * To improve throughput and to avoid exceeding the - * [quota limit](https://cloud.google.com/logging/quota-policy) for calls to `entries.write`, - * you should write multiple log entries at once rather than - * calling this method for each individual log entry. - * - * This object should have the same structure as [LogEntry]{@link LogEntry} - * @param {string=} request.logName - * Optional. A default log resource name that is assigned to all log entries - * in `entries` that do not specify a value for `log_name`: - * - * "projects/[PROJECT_ID]/logs/[LOG_ID]" - * "organizations/[ORGANIZATION_ID]/logs/[LOG_ID]" - * - * `[LOG_ID]` must be URL-encoded. For example, - * `"projects/my-project-id/logs/syslog"` or - * `"organizations/1234567890/logs/cloudresourcemanager.googleapis.com%2Factivity"`. - * For more information about log names, see - * {@link LogEntry}. - * @param {Object=} request.resource - * Optional. A default monitored resource object that is assigned to all log - * entries in `entries` that do not specify a value for `resource`. Example: - * - * { "type": "gce_instance", - * "labels": { - * "zone": "us-central1-a", "instance_id": "00000000000000000000" }} - * - * See {@link LogEntry}. - * - * This object should have the same structure as [google.api.MonitoredResource]{@link external:"google.api.MonitoredResource"} - * @param {Object.=} request.labels - * Optional. Default labels that are added to the `labels` field of all log - * entries in `entries`. If a log entry already has a label with the same key - * as a label in this parameter, then the log entry's label is not changed. - * See {@link LogEntry}. - * @param {boolean=} request.partialSuccess - * Optional. Whether valid entries should be written even if some other - * entries fail due to INVALID_ARGUMENT or PERMISSION_DENIED errors. If any - * entry is not written, the response status will be the error associated - * with one of the failed entries and include error details in the form of - * WriteLogEntriesPartialErrors. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [WriteLogEntriesResponse]{@link WriteLogEntriesResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [WriteLogEntriesResponse]{@link WriteLogEntriesResponse}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.loggingServiceV2Client(); - * var entries = []; - * client.writeLogEntries({entries: entries}).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }).catch(function(err) { - * console.error(err); - * }); - */ -LoggingServiceV2Client.prototype.writeLogEntries = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._writeLogEntries(request, options, callback); -}; - -/** - * Lists log entries. Use this method to retrieve log entries from - * Stackdriver Logging. For ways to export log entries, see - * [Exporting Logs](https://cloud.google.com/logging/docs/export). - * - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.resourceNames - * Required. Names of one or more resources from which to retrieve log - * entries: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * - * Projects listed in the `project_ids` field are added to this list. - * @param {string[]=} request.projectIds - * Deprecated. Use `resource_names` instead. One or more project identifiers - * or project numbers from which to retrieve log entries. Example: - * `"my-project-1A"`. If present, these project identifiers are converted to - * resource name format and added to the list of resources in - * `resource_names`. - * @param {string=} request.filter - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). Only log entries that - * match the filter are returned. An empty filter matches all log entries in - * the resources listed in `resource_names`. Referencing a parent resource - * that is not listed in `resource_names` will cause the filter to return no - * results. - * The maximum length of the filter is 20000 characters. - * @param {string=} request.orderBy - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of `LogEntry.insertId`. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [LogEntry]{@link LogEntry}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListLogEntriesResponse]{@link ListLogEntriesResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [LogEntry]{@link LogEntry}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [LogEntry]{@link LogEntry} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListLogEntriesResponse]{@link ListLogEntriesResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.loggingServiceV2Client(); - * var resourceNames = []; - * // Iterate over all elements. - * client.listLogEntries({resourceNames: resourceNames}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }).catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listLogEntries(nextRequest, options).then(callback); - * } - * } - * client.listLogEntries({resourceNames: resourceNames}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -LoggingServiceV2Client.prototype.listLogEntries = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listLogEntries(request, options, callback); -}; - -/** - * Equivalent to {@link listLogEntries}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listLogEntries} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string[]} request.resourceNames - * Required. Names of one or more resources from which to retrieve log - * entries: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * - * Projects listed in the `project_ids` field are added to this list. - * @param {string[]=} request.projectIds - * Deprecated. Use `resource_names` instead. One or more project identifiers - * or project numbers from which to retrieve log entries. Example: - * `"my-project-1A"`. If present, these project identifiers are converted to - * resource name format and added to the list of resources in - * `resource_names`. - * @param {string=} request.filter - * Optional. A filter that chooses which log entries to return. See [Advanced - * Logs Filters](https://cloud.google.com/logging/docs/view/advanced_filters). Only log entries that - * match the filter are returned. An empty filter matches all log entries in - * the resources listed in `resource_names`. Referencing a parent resource - * that is not listed in `resource_names` will cause the filter to return no - * results. - * The maximum length of the filter is 20000 characters. - * @param {string=} request.orderBy - * Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of `LogEntry.insertId`. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [LogEntry]{@link LogEntry} on 'data' event. - * - * @example - * - * var client = loggingV2.loggingServiceV2Client(); - * var resourceNames = []; - * client.listLogEntriesStream({resourceNames: resourceNames}).on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.error(err); - * }); - */ -LoggingServiceV2Client.prototype.listLogEntriesStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listLogEntries.createStream(this._listLogEntries, request, options); -}; - -/** - * Lists the descriptors for monitored resource types used by Stackdriver - * Logging. - * - * @param {Object} request - * The request object that will be sent. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListMonitoredResourceDescriptorsResponse]{@link ListMonitoredResourceDescriptorsResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListMonitoredResourceDescriptorsResponse]{@link ListMonitoredResourceDescriptorsResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.loggingServiceV2Client(); - * - * // Iterate over all elements. - * client.listMonitoredResourceDescriptors({}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }).catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listMonitoredResourceDescriptors(nextRequest, options).then(callback); - * } - * } - * client.listMonitoredResourceDescriptors({}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -LoggingServiceV2Client.prototype.listMonitoredResourceDescriptors = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listMonitoredResourceDescriptors(request, options, callback); -}; - -/** - * Equivalent to {@link listMonitoredResourceDescriptors}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listMonitoredResourceDescriptors} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"} on 'data' event. - * - * @example - * - * var client = loggingV2.loggingServiceV2Client(); - * - * client.listMonitoredResourceDescriptorsStream({}).on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.error(err); - * }); - */ -LoggingServiceV2Client.prototype.listMonitoredResourceDescriptorsStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listMonitoredResourceDescriptors.createStream(this._listMonitoredResourceDescriptors, request, options); -}; - -/** - * Lists the logs in projects or organizations. - * Only logs that have entries are listed. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name that owns the logs: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of string. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListLogsResponse]{@link ListLogsResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of string. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of string in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListLogsResponse]{@link ListLogsResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.loggingServiceV2Client(); - * var formattedParent = client.projectPath("[PROJECT]"); - * // Iterate over all elements. - * client.listLogs({parent: formattedParent}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }).catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listLogs(nextRequest, options).then(callback); - * } - * } - * client.listLogs({parent: formattedParent}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -LoggingServiceV2Client.prototype.listLogs = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listLogs(request, options, callback); -}; - -/** - * Equivalent to {@link listLogs}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listLogs} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The resource name that owns the logs: - * - * "projects/[PROJECT_ID]" - * "organizations/[ORGANIZATION_ID]" - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits a string on 'data' event. - * - * @example - * - * var client = loggingV2.loggingServiceV2Client(); - * var formattedParent = client.projectPath("[PROJECT]"); - * client.listLogsStream({parent: formattedParent}).on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.error(err); - * }); - */ -LoggingServiceV2Client.prototype.listLogsStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listLogs.createStream(this._listLogs, request, options); -}; - -function LoggingServiceV2ClientBuilder(gaxGrpc) { - if (!(this instanceof LoggingServiceV2ClientBuilder)) { - return new LoggingServiceV2ClientBuilder(gaxGrpc); - } - - var loggingServiceV2Client = gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/logging/v2/logging.proto' - }]); - extend(this, loggingServiceV2Client.google.logging.v2); - - - /** - * Build a new instance of {@link LoggingServiceV2Client}. - * - * @param {Object=} opts - The optional parameters. - * @param {String=} opts.servicePath - * The domain name of the API remote host. - * @param {number=} opts.port - * The port on which to connect to the remote host. - * @param {grpc.ClientCredentials=} opts.sslCreds - * A ClientCredentials for use with an SSL-enabled channel. - * @param {Object=} opts.clientConfig - * The customized config to build the call settings. See - * {@link gax.constructSettings} for the format. - */ - this.loggingServiceV2Client = function(opts) { - return new LoggingServiceV2Client(gaxGrpc, loggingServiceV2Client, opts); - }; - extend(this.loggingServiceV2Client, LoggingServiceV2Client); -} -module.exports = LoggingServiceV2ClientBuilder; -module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS; -module.exports.ALL_SCOPES = ALL_SCOPES; \ No newline at end of file diff --git a/packages/logging/src/v2/logging_service_v2_client_config.json b/packages/logging/src/v2/logging_service_v2_client_config.json deleted file mode 100644 index 2b364fec9a8..00000000000 --- a/packages/logging/src/v2/logging_service_v2_client_config.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "interfaces": { - "google.logging.v2.LoggingServiceV2": { - "retry_codes": { - "idempotent": [ - "DEADLINE_EXCEEDED", - "UNAVAILABLE" - ], - "non_idempotent": [] - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.2, - "max_retry_delay_millis": 1000, - "initial_rpc_timeout_millis": 2000, - "rpc_timeout_multiplier": 1.5, - "max_rpc_timeout_millis": 30000, - "total_timeout_millis": 45000 - }, - "list": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.2, - "max_retry_delay_millis": 1000, - "initial_rpc_timeout_millis": 7000, - "rpc_timeout_multiplier": 1.5, - "max_rpc_timeout_millis": 30000, - "total_timeout_millis": 45000 - } - }, - "methods": { - "DeleteLog": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "WriteLogEntries": { - "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", - "bundling": { - "element_count_threshold": 1000, - "request_byte_threshold": 1048576, - "delay_threshold_millis": 50 - } - }, - "ListLogEntries": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "list" - }, - "ListMonitoredResourceDescriptors": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ListLogs": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - } - } - } - } -} diff --git a/packages/logging/src/v2/metrics_service_v2_client.js b/packages/logging/src/v2/metrics_service_v2_client.js deleted file mode 100644 index 62d5a731e8e..00000000000 --- a/packages/logging/src/v2/metrics_service_v2_client.js +++ /dev/null @@ -1,558 +0,0 @@ -/* - * Copyright 2016 Google Inc. All rights reserved. - * - * 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 - * - * http://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. - * - * EDITING INSTRUCTIONS - * This file was generated from the file - * https://github.com/googleapis/googleapis/blob/master/google/logging/v2/logging_metrics.proto, - * and updates to that file get reflected here through a refresh process. - * For the short term, the refresh process will only be runnable by Google - * engineers. - * - * The only allowed edits are to method and file documentation. A 3-way - * merge preserves those additions if the generated source changes. - */ -/* TODO: introduce line-wrapping so that it never exceeds the limit. */ -/* jscs: disable maximumLineLength */ -'use strict'; - -var configData = require('./metrics_service_v2_client_config'); -var extend = require('extend'); -var gax = require('google-gax'); - -var SERVICE_ADDRESS = 'logging.googleapis.com'; - -var DEFAULT_SERVICE_PORT = 443; - -var CODE_GEN_NAME_VERSION = 'gapic/0.1.0'; - -var PAGE_DESCRIPTORS = { - listLogMetrics: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'metrics') -}; - -/** - * The scopes needed to make gRPC calls to all of the methods defined in - * this service. - */ -var ALL_SCOPES = [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/cloud-platform.read-only', - 'https://www.googleapis.com/auth/logging.admin', - 'https://www.googleapis.com/auth/logging.read', - 'https://www.googleapis.com/auth/logging.write' -]; - -/** - * Service for configuring logs-based metrics. - * - * This will be created through a builder function which can be obtained by the module. - * See the following example of how to initialize the module and how to access to the builder. - * @see {@link metricsServiceV2Client} - * - * @example - * var loggingV2 = require('@google-cloud/logging').v2({ - * // optional auth parameters. - * }); - * var client = loggingV2.metricsServiceV2Client(); - * - * @class - */ -function MetricsServiceV2Client(gaxGrpc, grpcClients, opts) { - opts = extend({ - servicePath: SERVICE_ADDRESS, - port: DEFAULT_SERVICE_PORT, - clientConfig: {} - }, opts); - - var googleApiClient = [ - 'gl-node/' + process.versions.node - ]; - if (opts.libName && opts.libVersion) { - googleApiClient.push(opts.libName + '/' + opts.libVersion); - } - googleApiClient.push( - CODE_GEN_NAME_VERSION, - 'gax/' + gax.version, - 'grpc/' + gaxGrpc.grpcVersion - ); - - var defaults = gaxGrpc.constructSettings( - 'google.logging.v2.MetricsServiceV2', - configData, - opts.clientConfig, - {'x-goog-api-client': googleApiClient.join(' ')}); - - var self = this; - - this.auth = gaxGrpc.auth; - var metricsServiceV2Stub = gaxGrpc.createStub( - grpcClients.google.logging.v2.MetricsServiceV2, - opts); - var metricsServiceV2StubMethods = [ - 'listLogMetrics', - 'getLogMetric', - 'createLogMetric', - 'updateLogMetric', - 'deleteLogMetric' - ]; - metricsServiceV2StubMethods.forEach(function(methodName) { - self['_' + methodName] = gax.createApiCall( - metricsServiceV2Stub.then(function(metricsServiceV2Stub) { - return function() { - var args = Array.prototype.slice.call(arguments, 0); - return metricsServiceV2Stub[methodName].apply(metricsServiceV2Stub, args); - }; - }), - defaults[methodName], - PAGE_DESCRIPTORS[methodName]); - }); -} - -// Path templates - -var PROJECT_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}'); - -var METRIC_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}/metrics/{metric}'); - -/** - * Returns a fully-qualified project resource name string. - * @param {String} project - * @returns {String} - */ -MetricsServiceV2Client.prototype.projectPath = function(project) { - return PROJECT_PATH_TEMPLATE.render({ - project: project - }); -}; - -/** - * Parses the projectName from a project resource. - * @param {String} projectName - * A fully-qualified path representing a project resources. - * @returns {String} - A string representing the project. - */ -MetricsServiceV2Client.prototype.matchProjectFromProjectName = function(projectName) { - return PROJECT_PATH_TEMPLATE.match(projectName).project; -}; - -/** - * Returns a fully-qualified metric resource name string. - * @param {String} project - * @param {String} metric - * @returns {String} - */ -MetricsServiceV2Client.prototype.metricPath = function(project, metric) { - return METRIC_PATH_TEMPLATE.render({ - project: project, - metric: metric - }); -}; - -/** - * Parses the metricName from a metric resource. - * @param {String} metricName - * A fully-qualified path representing a metric resources. - * @returns {String} - A string representing the project. - */ -MetricsServiceV2Client.prototype.matchProjectFromMetricName = function(metricName) { - return METRIC_PATH_TEMPLATE.match(metricName).project; -}; - -/** - * Parses the metricName from a metric resource. - * @param {String} metricName - * A fully-qualified path representing a metric resources. - * @returns {String} - A string representing the metric. - */ -MetricsServiceV2Client.prototype.matchMetricFromMetricName = function(metricName) { - return METRIC_PATH_TEMPLATE.match(metricName).metric; -}; - -/** - * Get the project ID used by this class. - * @aram {function(Error, string)} callback - the callback to be called with - * the current project Id. - */ -MetricsServiceV2Client.prototype.getProjectId = function(callback) { - return this.auth.getProjectId(callback); -}; - -// Service calls - -/** - * Lists logs-based metrics. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [LogMetric]{@link LogMetric}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListLogMetricsResponse]{@link ListLogMetricsResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [LogMetric]{@link LogMetric}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [LogMetric]{@link LogMetric} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListLogMetricsResponse]{@link ListLogMetricsResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.metricsServiceV2Client(); - * var formattedParent = client.projectPath("[PROJECT]"); - * // Iterate over all elements. - * client.listLogMetrics({parent: formattedParent}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }).catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listLogMetrics(nextRequest, options).then(callback); - * } - * } - * client.listLogMetrics({parent: formattedParent}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -MetricsServiceV2Client.prototype.listLogMetrics = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listLogMetrics(request, options, callback); -}; - -/** - * Equivalent to {@link listLogMetrics}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listLogMetrics} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * Required. The name of the project containing the metrics: - * - * "projects/[PROJECT_ID]" - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [LogMetric]{@link LogMetric} on 'data' event. - * - * @example - * - * var client = loggingV2.metricsServiceV2Client(); - * var formattedParent = client.projectPath("[PROJECT]"); - * client.listLogMetricsStream({parent: formattedParent}).on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.error(err); - * }); - */ -MetricsServiceV2Client.prototype.listLogMetricsStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listLogMetrics.createStream(this._listLogMetrics, request, options); -}; - -/** - * Gets a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * The resource name of the desired metric: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [LogMetric]{@link LogMetric}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [LogMetric]{@link LogMetric}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.metricsServiceV2Client(); - * var formattedMetricName = client.metricPath("[PROJECT]", "[METRIC]"); - * client.getLogMetric({metricName: formattedMetricName}).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }).catch(function(err) { - * console.error(err); - * }); - */ -MetricsServiceV2Client.prototype.getLogMetric = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._getLogMetric(request, options, callback); -}; - -/** - * Creates a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.parent - * The resource name of the project in which to create the metric: - * - * "projects/[PROJECT_ID]" - * - * The new metric must be provided in the request. - * @param {Object} request.metric - * The new logs-based metric, which must not have an identifier that - * already exists. - * - * This object should have the same structure as [LogMetric]{@link LogMetric} - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [LogMetric]{@link LogMetric}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [LogMetric]{@link LogMetric}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.metricsServiceV2Client(); - * var formattedParent = client.projectPath("[PROJECT]"); - * var metric = {}; - * var request = { - * parent: formattedParent, - * metric: metric - * }; - * client.createLogMetric(request).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }).catch(function(err) { - * console.error(err); - * }); - */ -MetricsServiceV2Client.prototype.createLogMetric = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._createLogMetric(request, options, callback); -}; - -/** - * Creates or updates a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * The resource name of the metric to update: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * - * The updated metric must be provided in the request and it's - * `name` field must be the same as `[METRIC_ID]` If the metric - * does not exist in `[PROJECT_ID]`, then a new metric is created. - * @param {Object} request.metric - * The updated metric. - * - * This object should have the same structure as [LogMetric]{@link LogMetric} - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [LogMetric]{@link LogMetric}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [LogMetric]{@link LogMetric}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.metricsServiceV2Client(); - * var formattedMetricName = client.metricPath("[PROJECT]", "[METRIC]"); - * var metric = {}; - * var request = { - * metricName: formattedMetricName, - * metric: metric - * }; - * client.updateLogMetric(request).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }).catch(function(err) { - * console.error(err); - * }); - */ -MetricsServiceV2Client.prototype.updateLogMetric = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._updateLogMetric(request, options, callback); -}; - -/** - * Deletes a logs-based metric. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.metricName - * The resource name of the metric to delete: - * - * "projects/[PROJECT_ID]/metrics/[METRIC_ID]" - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error)=} callback - * The function which will be called with the result of the API call. - * @return {Promise} - The promise which resolves when API call finishes. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var client = loggingV2.metricsServiceV2Client(); - * var formattedMetricName = client.metricPath("[PROJECT]", "[METRIC]"); - * client.deleteLogMetric({metricName: formattedMetricName}).catch(function(err) { - * console.error(err); - * }); - */ -MetricsServiceV2Client.prototype.deleteLogMetric = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._deleteLogMetric(request, options, callback); -}; - -function MetricsServiceV2ClientBuilder(gaxGrpc) { - if (!(this instanceof MetricsServiceV2ClientBuilder)) { - return new MetricsServiceV2ClientBuilder(gaxGrpc); - } - - var metricsServiceV2Client = gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/logging/v2/logging_metrics.proto' - }]); - extend(this, metricsServiceV2Client.google.logging.v2); - - - /** - * Build a new instance of {@link MetricsServiceV2Client}. - * - * @param {Object=} opts - The optional parameters. - * @param {String=} opts.servicePath - * The domain name of the API remote host. - * @param {number=} opts.port - * The port on which to connect to the remote host. - * @param {grpc.ClientCredentials=} opts.sslCreds - * A ClientCredentials for use with an SSL-enabled channel. - * @param {Object=} opts.clientConfig - * The customized config to build the call settings. See - * {@link gax.constructSettings} for the format. - */ - this.metricsServiceV2Client = function(opts) { - return new MetricsServiceV2Client(gaxGrpc, metricsServiceV2Client, opts); - }; - extend(this.metricsServiceV2Client, MetricsServiceV2Client); -} -module.exports = MetricsServiceV2ClientBuilder; -module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS; -module.exports.ALL_SCOPES = ALL_SCOPES; \ No newline at end of file diff --git a/packages/logging/src/v2/metrics_service_v2_client_config.json b/packages/logging/src/v2/metrics_service_v2_client_config.json deleted file mode 100644 index 9bfa238cb85..00000000000 --- a/packages/logging/src/v2/metrics_service_v2_client_config.json +++ /dev/null @@ -1,51 +0,0 @@ -{ - "interfaces": { - "google.logging.v2.MetricsServiceV2": { - "retry_codes": { - "idempotent": [ - "DEADLINE_EXCEEDED", - "UNAVAILABLE" - ], - "non_idempotent": [] - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.2, - "max_retry_delay_millis": 1000, - "initial_rpc_timeout_millis": 2000, - "rpc_timeout_multiplier": 1.5, - "max_rpc_timeout_millis": 30000, - "total_timeout_millis": 45000 - } - }, - "methods": { - "ListLogMetrics": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "GetLogMetric": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "CreateLogMetric": { - "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "UpdateLogMetric": { - "timeout_millis": 30000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "DeleteLogMetric": { - "timeout_millis": 30000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - } - } - } - } -} diff --git a/packages/logging/system-test/logging.js b/packages/logging/system-test/logging.js deleted file mode 100644 index 67141d03379..00000000000 --- a/packages/logging/system-test/logging.js +++ /dev/null @@ -1,556 +0,0 @@ -/*! - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var assert = require('assert'); -var async = require('async'); -var bigqueryLibrary = require('@google-cloud/bigquery'); -var exec = require('methmeth'); -var extend = require('extend'); -var is = require('is'); -var prop = require('propprop'); -var pubsubLibrary = require('@google-cloud/pubsub'); -var storageLibrary = require('@google-cloud/storage'); -var uuid = require('uuid'); - -var env = require('../../../system-test/env.js'); -var Logging = require('../'); - -describe('Logging', function() { - var TESTS_PREFIX = 'gcloud-logging-test'; - var WRITE_CONSISTENCY_DELAY_MS = 120000; - - var bigQuery = bigqueryLibrary(env); - var pubsub = pubsubLibrary(env); - var storage = storageLibrary(env); - - var logging = new Logging(env); - - // Create the possible destinations for sinks that we will create. - var bucket = storage.bucket(generateName()); - var dataset = bigQuery.dataset(generateName().replace(/-/g, '_')); - var topic = pubsub.topic(generateName()); - - before(function(done) { - async.parallel([ - bucket.create.bind(bucket), - dataset.create.bind(dataset), - topic.create.bind(topic) - ], done); - }); - - after(function(done) { - async.parallel([ - deleteBuckets, - deleteDatasets, - deleteTopics, - deleteSinks - ], done); - - function deleteBuckets(callback) { - storage.getBuckets({ - prefix: TESTS_PREFIX - }, function(err, buckets) { - if (err) { - done(err); - return; - } - - function deleteBucket(bucket, callback) { - bucket.deleteFiles(function(err) { - if (err) { - callback(err); - return; - } - - bucket.delete(callback); - }); - } - - async.each(buckets, deleteBucket, callback); - }); - } - - function deleteDatasets(callback) { - getAndDelete(bigQuery.getDatasets.bind(bigQuery), callback); - } - - function deleteTopics(callback) { - getAndDelete(pubsub.getTopics.bind(pubsub), callback); - } - - function deleteSinks(callback) { - getAndDelete(logging.getSinks.bind(logging), callback); - } - - function getAndDelete(method, callback) { - method(function(err, objects) { - if (err) { - callback(err); - return; - } - - objects = objects.filter(function(object) { - return (object.name || object.id).indexOf(TESTS_PREFIX) === 0; - }); - - async.each(objects, exec('delete'), callback); - }); - } - }); - - describe('sinks', function() { - it('should create a sink with a Bucket destination', function(done) { - var sink = logging.sink(generateName()); - - sink.create({ - destination: bucket - }, function(err, sink, apiResponse) { - assert.ifError(err); - - var destination = 'storage.googleapis.com/' + bucket.name; - assert.strictEqual(apiResponse.destination, destination); - - done(); - }); - }); - - it('should create a sink with a Dataset destination', function(done) { - var sink = logging.sink(generateName()); - - sink.create({ - destination: dataset - }, function(err, sink, apiResponse) { - assert.ifError(err); - - var destination = 'bigquery.googleapis.com/datasets/' + dataset.id; - - // The projectId may have been replaced depending on how the system - // tests are being run, so let's not care about that. - apiResponse.destination = - apiResponse.destination.replace(/projects\/[^/]*\//, ''); - - assert.strictEqual(apiResponse.destination, destination); - - done(); - }); - }); - - it('should create a sink with a Topic destination', function(done) { - var sink = logging.sink(generateName()); - - sink.create({ - destination: topic - }, function(err, sink, apiResponse) { - assert.ifError(err); - - var destination = 'pubsub.googleapis.com/' + topic.name; - - // The projectId may have been replaced depending on how the system - // tests are being run, so let's not care about that. - assert.strictEqual( - apiResponse.destination.replace(/projects\/[^/]*\//, ''), - destination.replace(/projects\/[^/]*\//, '') - ); - - done(); - }); - }); - - describe('metadata', function() { - var sink = logging.sink(generateName()); - var FILTER = 'severity = ALERT'; - - before(function(done) { - sink.create({ - destination: topic - }, done); - }); - - it('should set metadata', function(done) { - var metadata = { - filter: FILTER - }; - - sink.setMetadata(metadata, function(err, apiResponse) { - assert.ifError(err); - assert.strictEqual(apiResponse.filter, FILTER); - done(); - }); - }); - - it('should set a filter', function(done) { - sink.setFilter(FILTER, function(err, apiResponse) { - assert.ifError(err); - assert.strictEqual(apiResponse.filter, FILTER); - done(); - }); - }); - }); - - describe('listing sinks', function() { - var sink = logging.sink(generateName()); - - before(function(done) { - sink.create({ - destination: topic - }, done); - }); - - it('should list sinks', function(done) { - logging.getSinks(function(err, sinks) { - assert.ifError(err); - assert(sinks.length > 0); - done(); - }); - }); - - it('should list sinks as a stream', function(done) { - logging.getSinksStream({ pageSize: 1 }) - .on('error', done) - .once('data', function() { - this.end(); - done(); - }); - }); - - it('should get metadata', function(done) { - logging.getSinksStream({ pageSize: 1 }) - .on('error', done) - .once('data', function(sink) { - sink.getMetadata(function(err, metadata) { - assert.ifError(err); - assert.strictEqual(is.object(metadata), true); - done(); - }); - }); - }); - }); - }); - - describe('logs', function() { - var log = logging.log('syslog'); - - var logEntries = [ - // string data - log.entry('log entry 1'), - - // object data - log.entry({ delegate: 'my_username' }), - - // various data types - log.entry({ - nonValue: null, - boolValue: true, - arrayValue: [ 1, 2, 3 ] - }), - - // nested object data - log.entry({ - nested: { - delegate: 'my_username' - } - }) - ]; - - var options = { - resource: { - type: 'gce_instance', - labels: { - zone: 'global', - instance_id: '3' - } - } - }; - - it('should list log entries', function(done) { - logging.getEntries({ - autoPaginate: false, - pageSize: 1 - }, function(err, entries) { - assert.ifError(err); - assert.strictEqual(entries.length, 1); - done(); - }); - }); - - it('should list log entries as a stream', function(done) { - logging.getEntriesStream({ - autoPaginate: false, - pageSize: 1 - }) - .on('error', done) - .once('data', function() { - this.end(); - }) - .on('end', done); - }); - - describe('log-specific entries', function() { - before(function(done) { - log.write(logEntries, options, done); - }); - - it('should list log entries', function(done) { - log.getEntries({ - autoPaginate: false, - pageSize: 1 - }, function(err, entries) { - assert.ifError(err); - assert.strictEqual(entries.length, 1); - done(); - }); - }); - - it('should list log entries as a stream', function(done) { - log.getEntriesStream({ - autoPaginate: false, - pageSize: 1 - }) - .on('error', done) - .once('data', function() { - this.end(); - done(); - }); - }); - }); - - it('should write a single entry to a log', function(done) { - log.write(logEntries[0], options, done); - }); - - it('should write multiple entries to a log', function(done) { - log.write(logEntries, options, function(err) { - assert.ifError(err); - - setTimeout(function() { - log.getEntries({ - autoPaginate: false, - pageSize: logEntries.length - }, function(err, entries) { - assert.ifError(err); - - assert.deepEqual(entries.map(prop('data')).reverse(), [ - 'log entry 1', - { - delegate: 'my_username' - }, - { - nonValue: null, - boolValue: true, - arrayValue: [ 1, 2, 3 ] - }, - { - nested: { - delegate: 'my_username' - } - } - ]); - - done(); - }); - }, WRITE_CONSISTENCY_DELAY_MS); - }); - }); - - it('should preserve order of entries', function(done) { - var entry1 = log.entry('1'); - - setTimeout(function() { - var entry2 = log.entry('2'); - var entry3 = log.entry({ timestamp: entry2.metadata.timestamp }, '3'); - - // Re-arrange to confirm the timestamp is sent and honored. - log.write([entry2, entry3, entry1], options, function(err) { - assert.ifError(err); - - setTimeout(function() { - log.getEntries({ - autoPaginate: false, - pageSize: 3 - }, function(err, entries) { - assert.ifError(err); - assert.deepEqual(entries.map(prop('data')), [ '3', '2', '1' ]); - done(); - }); - }, WRITE_CONSISTENCY_DELAY_MS); - }); - }, 1000); - }); - - it('should preserve order for sequential write calls', function(done) { - var messages = ['1', '2', '3', '4', '5']; - - messages.forEach(function(message) { - log.write(log.entry(message)); - }); - - setTimeout(function() { - log.getEntries({ - autoPaginate: false, - pageSize: messages.length - }, function(err, entries) { - assert.ifError(err); - assert.deepEqual(entries.reverse().map(prop('data')), messages); - done(); - }); - }, WRITE_CONSISTENCY_DELAY_MS); - }); - - it('should write an entry with primitive values', function(done) { - var logEntry = log.entry({ - when: new Date(), - matchUser: /username: (.+)/, - matchUserError: new Error('No user found.'), - shouldNotBeSaved: undefined - }); - - log.write(logEntry, options, function(err) { - assert.ifError(err); - - setTimeout(function() { - log.getEntries({ - autoPaginate: false, - pageSize: 1 - }, function(err, entries) { - assert.ifError(err); - - var entry = entries[0]; - - assert.deepEqual(entry.data, { - when: logEntry.data.when.toString(), - matchUser: logEntry.data.matchUser.toString(), - matchUserError: logEntry.data.matchUserError.toString() - }); - - done(); - }); - }, WRITE_CONSISTENCY_DELAY_MS); - }); - }); - - it('should write a log with metadata', function(done) { - var metadata = extend({}, options, { - severity: 'DEBUG' - }); - - var data = { - embeddedData: true - }; - - var logEntry = log.entry(metadata, data); - - log.write(logEntry, function(err) { - assert.ifError(err); - - setTimeout(function() { - log.getEntries({ - autoPaginate: false, - pageSize: 1 - }, function(err, entries) { - assert.ifError(err); - - var entry = entries[0]; - - assert.strictEqual(entry.metadata.severity, metadata.severity); - assert.deepEqual(entry.data, data); - - done(); - }); - }, WRITE_CONSISTENCY_DELAY_MS); - }); - }); - - it('should set the default resource', function(done) { - var text = 'entry-text'; - var entry = log.entry(text); - - log.write(entry, function(err) { - assert.ifError(err); - - setTimeout(function() { - log.getEntries({ - autoPaginate: false, - pageSize: 1 - }, function(err, entries) { - assert.ifError(err); - - var entry = entries[0]; - - assert.strictEqual(entry.data, text); - assert.deepEqual(entry.metadata.resource, { - type: 'global', - labels: { - project_id: env.projectId - } - }); - - done(); - }); - }, WRITE_CONSISTENCY_DELAY_MS); - }); - }); - - it('should write a log with camelcase resource label keys', function(done) { - log.write(logEntries, { - resource: { - type: 'gce_instance', - labels: { - zone: 'global', - instanceId: '3' - } - } - }, done); - }); - - it('should write to a log with alert helper', function(done) { - log.alert(logEntries, options, done); - }); - - it('should write to a log with critical helper', function(done) { - log.critical(logEntries, options, done); - }); - - it('should write to a log with debug helper', function(done) { - log.debug(logEntries, options, done); - }); - - it('should write to a log with emergency helper', function(done) { - log.emergency(logEntries, options, done); - }); - - it('should write to a log with error helper', function(done) { - log.error(logEntries, options, done); - }); - - it('should write to a log with info helper', function(done) { - log.info(logEntries, options, done); - }); - - it('should write to a log with notice helper', function(done) { - log.notice(logEntries, options, done); - }); - - it('should write to a log with warning helper', function(done) { - log.warning(logEntries, options, done); - }); - }); - - function generateName() { - return TESTS_PREFIX + uuid.v1(); - } -}); diff --git a/packages/logging/test/entry.js b/packages/logging/test/entry.js deleted file mode 100644 index aa4b7803f47..00000000000 --- a/packages/logging/test/entry.js +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var assert = require('assert'); -var extend = require('extend'); -var GrpcService = require('@google-cloud/common').GrpcService; -var proxyquire = require('proxyquire'); -var util = require('@google-cloud/common').util; - -function FakeGrpcService() {} - -var fakeEventIdNewOverride; - -function FakeEventId() {} -FakeEventId.prototype.new = function() { - return (fakeEventIdNewOverride || util.noop).apply(null, arguments); -}; - -describe('Entry', function() { - var Entry; - var entry; - - var METADATA = {}; - var DATA = {}; - - before(function() { - Entry = proxyquire('../src/entry.js', { - '@google-cloud/common-grpc': { - Service: FakeGrpcService - }, - eventid: FakeEventId - }); - }); - - beforeEach(function() { - fakeEventIdNewOverride = null; - extend(FakeGrpcService, GrpcService); - entry = new Entry(METADATA, DATA); - }); - - describe('instantiation', function() { - it('should assign timestamp to metadata', function() { - var now = new Date(); - - var expectedTimestampBoundaries = { - start: new Date(now.getTime() - 1000), - end: new Date(now.getTime() + 1000) - }; - - assert(entry.metadata.timestamp >= expectedTimestampBoundaries.start); - assert(entry.metadata.timestamp <= expectedTimestampBoundaries.end); - }); - - it('should not assign timestamp if one is already set', function() { - var timestamp = new Date('2012'); - - var entry = new Entry({ - timestamp: timestamp - }); - - assert.strictEqual(entry.metadata.timestamp, timestamp); - }); - - it('should assign insertId to metadata', function() { - var eventId = 'event-id'; - - fakeEventIdNewOverride = function() { - return eventId; - }; - - var entry = new Entry(); - - assert.strictEqual(entry.metadata.insertId, eventId); - }); - - it('should not assign insertId if one is already set', function() { - var eventId = 'event-id'; - - fakeEventIdNewOverride = function() { - return eventId; - }; - - var userDefinedInsertId = 'user-defined-insert-id'; - - var entry = new Entry({ - insertId: userDefinedInsertId - }); - - assert.strictEqual(entry.metadata.insertId, userDefinedInsertId); - }); - - it('should localize data', function() { - assert.strictEqual(entry.data, DATA); - }); - }); - - describe('fromApiResponse_', function() { - var RESOURCE = {}; - var entry; - var date = new Date(); - - beforeEach(function() { - var seconds = date.getTime() / 1000; - var secondsRounded = Math.floor(seconds); - - FakeGrpcService.structToObj_ = function(data) { - return data; - }; - - entry = Entry.fromApiResponse_({ - resource: RESOURCE, - payload: 'jsonPayload', - jsonPayload: DATA, - extraProperty: true, - timestamp: { - seconds: secondsRounded, - nanos: Math.floor((seconds - secondsRounded) * 1e9) - } - }); - }); - - it('should create an Entry', function() { - assert(entry instanceof Entry); - assert.strictEqual(entry.metadata.resource, RESOURCE); - assert.strictEqual(entry.data, DATA); - assert.strictEqual(entry.metadata.extraProperty, true); - assert.deepEqual(entry.metadata.timestamp, date); - }); - - it('should extend the entry with proto data', function() { - var entry = Entry.fromApiResponse_({ - resource: RESOURCE, - payload: 'protoPayload', - protoPayload: DATA, - extraProperty: true - }); - - assert.strictEqual(entry.data, DATA); - }); - - it('should extend the entry with json data', function() { - assert.strictEqual(entry.data, DATA); - }); - - it('should extend the entry with text data', function() { - var entry = Entry.fromApiResponse_({ - resource: RESOURCE, - payload: 'textPayload', - textPayload: DATA, - extraProperty: true - }); - - assert.strictEqual(entry.data, DATA); - }); - }); - - describe('toJSON', function() { - beforeEach(function() { - FakeGrpcService.objToStruct_ = util.noop; - }); - - it('should not modify the original instance', function() { - var entryBefore = extend(true, {}, entry); - entry.toJSON(); - var entryAfter = extend(true, {}, entry); - assert.deepEqual(entryBefore, entryAfter); - }); - - it('should convert data as a struct and assign to jsonPayload', function() { - var input = {}; - var converted = {}; - - FakeGrpcService.objToStruct_ = function(obj, options) { - assert.strictEqual(obj, input); - assert.deepEqual(options, { - removeCircular: false, - stringify: true - }); - return converted; - }; - - entry.data = input; - var json = entry.toJSON(); - assert.strictEqual(json.jsonPayload, converted); - }); - - it('should pass removeCircular to objToStruct_', function(done) { - FakeGrpcService.objToStruct_ = function(obj, options) { - assert.strictEqual(options.removeCircular, true); - done(); - }; - - entry.data = {}; - entry.toJSON({ removeCircular: true }); - }); - - it('should assign string data as textPayload', function() { - entry.data = 'string'; - var json = entry.toJSON(); - assert.strictEqual(json.textPayload, entry.data); - }); - - it('should convert a date', function() { - var date = new Date(); - entry.metadata.timestamp = date; - - var json = entry.toJSON(); - - var seconds = date.getTime() / 1000; - var secondsRounded = Math.floor(seconds); - - assert.deepEqual(json.timestamp, { - seconds: secondsRounded, - nanos: Math.floor((seconds - secondsRounded) * 1e9) - }); - }); - }); -}); diff --git a/packages/logging/test/index.js b/packages/logging/test/index.js deleted file mode 100644 index 2b333b873a4..00000000000 --- a/packages/logging/test/index.js +++ /dev/null @@ -1,1382 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var arrify = require('arrify'); -var assert = require('assert'); -var extend = require('extend'); -var proxyquire = require('proxyquire'); -var through = require('through2'); -var util = require('@google-cloud/common').util; - -var PKG = require('../package.json'); -var v2 = require('../src/v2/index.js'); - -var extended = false; -var fakePaginator = { - extend: function(Class, methods) { - if (Class.name !== 'Logging') { - return; - } - - extended = true; - methods = arrify(methods); - assert.deepEqual(methods, [ - 'getEntries', - 'getSinks' - ]); - }, - streamify: function(methodName) { - return methodName; - } -}; - -var googleAutoAuthOverride; -function fakeGoogleAutoAuth() { - return (googleAutoAuthOverride || util.noop).apply(null, arguments); -} - -var isCustomTypeOverride; -var promisifed = false; -var replaceProjectIdTokenOverride; -var fakeUtil = extend({}, util, { - isCustomType: function() { - if (isCustomTypeOverride) { - return isCustomTypeOverride.apply(null, arguments); - } - - return false; - }, - promisifyAll: function(Class, options) { - if (Class.name !== 'Logging') { - return; - } - - promisifed = true; - assert.deepEqual(options.exclude, [ - 'entry', - 'log', - 'request', - 'sink' - ]); - }, - replaceProjectIdToken: function(reqOpts) { - if (replaceProjectIdTokenOverride) { - return replaceProjectIdTokenOverride.apply(null, arguments); - } - - return reqOpts; - } -}); - -var v2Override; -function fakeV2() { - return (v2Override || util.noop).apply(null, arguments); -} - -function FakeEntry() { - this.calledWith_ = arguments; -} - -FakeEntry.fromApiResponse_ = function() { - return arguments; -}; - -function FakeLog() { - this.calledWith_ = arguments; -} - -function FakeSink() { - this.calledWith_ = arguments; -} - -describe('Logging', function() { - var Logging; - var logging; - - var PROJECT_ID = 'project-id'; - - before(function() { - Logging = proxyquire('../', { - '@google-cloud/common': { - paginator: fakePaginator, - util: fakeUtil - }, - 'google-auto-auth': fakeGoogleAutoAuth, - './log.js': FakeLog, - './entry.js': FakeEntry, - './sink.js': FakeSink, - './v2': fakeV2 - }); - }); - - beforeEach(function() { - googleAutoAuthOverride = null; - isCustomTypeOverride = null; - replaceProjectIdTokenOverride = null; - v2Override = null; - - logging = new Logging({ - projectId: PROJECT_ID - }); - }); - - describe('instantiation', function() { - it('should extend the correct methods', function() { - assert(extended); // See `fakePaginator.extend` - }); - - it('should promisify all the things', function() { - assert(promisifed); - }); - - it('should normalize the arguments', function() { - var options = { - projectId: PROJECT_ID, - credentials: 'credentials', - email: 'email', - keyFilename: 'keyFile' - }; - - var normalizeArguments = fakeUtil.normalizeArguments; - var normalizeArgumentsCalled = false; - var fakeContext = {}; - - fakeUtil.normalizeArguments = function(context, options_) { - normalizeArgumentsCalled = true; - assert.strictEqual(context, fakeContext); - assert.strictEqual(options, options_); - return options_; - }; - - Logging.call(fakeContext, options); - assert(normalizeArgumentsCalled); - - fakeUtil.normalizeArguments = normalizeArguments; - }); - - it('should initialize the API object', function() { - assert.deepEqual(logging.api, {}); - }); - - it('should cache a local google-auto-auth instance', function() { - var fakeGoogleAutoAuthInstance = {}; - var options = { - a: 'b', - c: 'd' - }; - - googleAutoAuthOverride = function(options_) { - assert.deepEqual(options_, extend({ - scopes: v2.ALL_SCOPES, - libName: 'gccl', - libVersion: PKG.version - }, options)); - return fakeGoogleAutoAuthInstance; - }; - - var logging = new Logging(options); - assert.strictEqual(logging.auth, fakeGoogleAutoAuthInstance); - }); - - it('should localize the options', function() { - var options = { - a: 'b', - c: 'd' - }; - - var logging = new Logging(options); - - assert.notStrictEqual(logging.options, options); - - assert.deepEqual(logging.options, extend({ - scopes: v2.ALL_SCOPES, - libName: 'gccl', - libVersion: PKG.version - }, options)); - }); - - it('should set the projectId', function() { - assert.strictEqual(logging.projectId, PROJECT_ID); - }); - - it('should default the projectId to the token', function() { - var logging = new Logging({}); - assert.strictEqual(logging.projectId, '{{projectId}}'); - }); - }); - - describe('createSink', function() { - var SINK_NAME = 'name'; - - it('should throw if a name is not provided', function() { - assert.throws(function() { - logging.createSink(); - }, /A sink name must be provided\./); - }); - - it('should throw if a config object is not provided', function() { - assert.throws(function() { - logging.createSink(SINK_NAME); - }, /A sink configuration object must be provided\./); - }); - - it('should set acls for a Dataset destination', function(done) { - var dataset = {}; - - var CONFIG = { - destination: dataset - }; - - isCustomTypeOverride = function(destination, type) { - assert.strictEqual(destination, dataset); - return type === 'bigquery/dataset'; - }; - - logging.setAclForDataset_ = function(name, config, callback) { - assert.strictEqual(name, SINK_NAME); - assert.strictEqual(config, CONFIG); - callback(); // done() - }; - - logging.createSink(SINK_NAME, CONFIG, done); - }); - - it('should set acls for a Topic destination', function(done) { - var topic = {}; - - var CONFIG = { - destination: topic - }; - - isCustomTypeOverride = function(destination, type) { - assert.strictEqual(destination, topic); - return type === 'pubsub/topic'; - }; - - logging.setAclForTopic_ = function(name, config, callback) { - assert.strictEqual(name, SINK_NAME); - assert.strictEqual(config, CONFIG); - callback(); // done() - }; - - logging.createSink(SINK_NAME, CONFIG, done); - }); - - it('should set acls for a Bucket destination', function(done) { - var bucket = {}; - - var CONFIG = { - destination: bucket - }; - - isCustomTypeOverride = function(destination, type) { - assert.strictEqual(destination, bucket); - return type === 'storage/bucket'; - }; - - logging.setAclForBucket_ = function(name, config, callback) { - assert.strictEqual(name, SINK_NAME); - assert.strictEqual(config, CONFIG); - callback(); // done() - }; - - logging.createSink(SINK_NAME, CONFIG, done); - }); - - describe('API request', function() { - it('should make the correct API request', function(done) { - var config = { - a: 'b', - c: 'd' - }; - - var expectedConfig = extend({}, config, { - name: SINK_NAME - }); - - logging.request = function(config) { - assert.strictEqual(config.client, 'configServiceV2Client'); - assert.strictEqual(config.method, 'createSink'); - - var expectedParent = 'projects/' + logging.projectId; - assert.strictEqual(config.reqOpts.parent, expectedParent); - assert.deepEqual(config.reqOpts.sink, expectedConfig); - - assert.strictEqual(config.gaxOpts, undefined); - - done(); - }; - - logging.createSink(SINK_NAME, config, assert.ifError); - }); - - it('should accept GAX options', function(done) { - var config = { - a: 'b', - c: 'd', - gaxOptions: {} - }; - - logging.request = function(config_) { - assert.strictEqual(config_.reqOpts.sink.gaxOptions, undefined); - assert.strictEqual(config_.gaxOpts, config.gaxOptions); - done(); - }; - - logging.createSink(SINK_NAME, config, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = {}; - - beforeEach(function() { - logging.request = function(config, callback) { - callback(error, apiResponse); - }; - }); - - it('should exec callback with error & API response', function(done) { - logging.createSink(SINK_NAME, {}, function(err, sink, apiResponse_) { - assert.strictEqual(err, error); - assert.strictEqual(sink, null); - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - }); - - describe('success', function() { - var apiResponse = { - name: SINK_NAME - }; - - beforeEach(function() { - logging.request = function(config, callback) { - callback(null, apiResponse); - }; - }); - - it('should exec callback with Sink & API response', function(done) { - var sink = {}; - - logging.sink = function(name_) { - assert.strictEqual(name_, SINK_NAME); - return sink; - }; - - logging.createSink(SINK_NAME, {}, function(err, sink_, apiResponse_) { - assert.ifError(err); - - assert.strictEqual(sink_, sink); - assert.strictEqual(sink_.metadata, apiResponse); - assert.strictEqual(apiResponse_, apiResponse); - - done(); - }); - }); - }); - }); - }); - - describe('entry', function() { - var RESOURCE = {}; - var DATA = {}; - - it('should return an Entry object', function() { - var entry = logging.entry(RESOURCE, DATA); - assert(entry instanceof FakeEntry); - assert.strictEqual(entry.calledWith_[0], RESOURCE); - assert.strictEqual(entry.calledWith_[1], DATA); - }); - }); - - describe('getEntries', function() { - it('should accept only a callback', function(done) { - logging.request = function(config) { - assert.deepEqual(config.reqOpts, { - orderBy: 'timestamp desc', - resourceNames: ['projects/' + logging.projectId] - }); - done(); - }; - - logging.getEntries(assert.ifError); - }); - - it('should make the correct API request', function(done) { - var options = {}; - - logging.request = function(config) { - assert.strictEqual(config.client, 'loggingServiceV2Client'); - assert.strictEqual(config.method, 'listLogEntries'); - - assert.deepEqual(config.reqOpts, extend(options, { - orderBy: 'timestamp desc', - resourceNames: ['projects/' + logging.projectId] - })); - - assert.deepStrictEqual(config.gaxOpts, { - autoPaginate: undefined - }); - - done(); - }; - - logging.getEntries(options, assert.ifError); - }); - - it('should allow overriding orderBy', function(done) { - var options = { - orderBy: 'timestamp asc' - }; - - logging.request = function(config) { - assert.deepEqual(config.reqOpts.orderBy, options.orderBy); - done(); - }; - - logging.getEntries(options, assert.ifError); - }); - - it('should accept GAX options', function(done) { - var options = { - a: 'b', - c: 'd', - gaxOptions: { - autoPaginate: true - } - }; - - logging.request = function(config) { - assert.strictEqual(config.reqOpts.gaxOptions, undefined); - assert.deepStrictEqual(config.gaxOpts, options.gaxOptions); - done(); - }; - - logging.getEntries(options, assert.ifError); - }); - - describe('error', function() { - var ARGS = [ - new Error('Error.'), - [], - {} - ]; - - beforeEach(function() { - logging.request = function(config, callback) { - callback.apply(null, ARGS); - }; - }); - - it('should execute callback with error & API response', function(done) { - logging.getEntries({}, function() { - var args = [].slice.call(arguments); - assert.deepStrictEqual(args, ARGS); - done(); - }); - }); - }); - - describe('success', function() { - var ARGS = [ - null, - [ - { - logName: 'syslog' - } - ] - ]; - - beforeEach(function() { - logging.request = function(config, callback) { - callback.apply(null, ARGS); - }; - }); - - it('should execute callback with entries & API resp', function(done) { - logging.getEntries({}, function(err, entries) { - assert.ifError(err); - - var argsPassedToFromApiResponse_ = entries[0]; - assert.strictEqual( - argsPassedToFromApiResponse_[0], - ARGS[1][0] - ); - - done(); - }); - }); - }); - }); - - describe('getEntriesStream', function() { - var OPTIONS = { - a: 'b', - c: 'd', - gaxOptions: { - a: 'b', - c: 'd' - } - }; - - var REQUEST_STREAM; - var RESULT = {}; - - beforeEach(function() { - REQUEST_STREAM = through.obj(); - REQUEST_STREAM.push(RESULT); - - logging.request = function() { - return REQUEST_STREAM; - }; - }); - - it('should make request once reading', function(done) { - logging.request = function(config) { - assert.strictEqual(config.client, 'loggingServiceV2Client'); - assert.strictEqual(config.method, 'listLogEntriesStream'); - - assert.deepEqual(config.reqOpts, { - resourceNames: [ - 'projects/' + logging.projectId - ], - orderBy: 'timestamp desc', - a: 'b', - c: 'd' - }); - - assert.deepEqual(config.gaxOpts, { - autoPaginate: undefined, - a: 'b', - c: 'd' - }); - - setImmediate(done); - - return REQUEST_STREAM; - }; - - var stream = logging.getEntriesStream(OPTIONS); - stream.emit('reading'); - }); - - it('should convert results from request to Entry', function(done) { - var stream = logging.getEntriesStream(OPTIONS); - - stream.on('data', function(entry) { - var argsPassedToFromApiResponse_ = entry[0]; - assert.strictEqual( - argsPassedToFromApiResponse_, - RESULT - ); - - done(); - }); - - stream.emit('reading'); - }); - - it('should expose abort function', function(done) { - REQUEST_STREAM.abort = done; - - var stream = logging.getEntriesStream(OPTIONS); - - stream.emit('reading'); - - stream.abort(); - }); - - it('should not require an options object', function() { - assert.doesNotThrow(function() { - var stream = logging.getEntriesStream(); - stream.emit('reading'); - }); - }); - }); - - describe('getSinks', function() { - var OPTIONS = { - a: 'b', - c: 'd', - gaxOptions: { - a: 'b', - c: 'd' - } - }; - - it('should accept only a callback', function(done) { - logging.request = function() { - done(); - }; - - logging.getSinks(assert.ifError); - }); - - it('should make the correct API request', function(done) { - logging.request = function(config) { - assert.strictEqual(config.client, 'configServiceV2Client'); - assert.strictEqual(config.method, 'listSinks'); - - assert.deepEqual(config.reqOpts, { - parent: 'projects/' + logging.projectId, - a: 'b', - c: 'd' - }); - - assert.deepEqual(config.gaxOpts, { - autoPaginate: undefined, - a: 'b', - c: 'd' - }); - - done(); - }; - - logging.getSinks(OPTIONS, assert.ifError); - }); - - describe('error', function() { - var ARGS = [ - new Error('Error.'), - [], - {} - ]; - - beforeEach(function() { - logging.request = function(config, callback) { - callback.apply(null, ARGS); - }; - }); - - it('should execute callback with error & API response', function(done) { - logging.getEntries(OPTIONS, function() { - var args = [].slice.call(arguments); - assert.deepStrictEqual(args, ARGS); - done(); - }); - }); - }); - - describe('success', function() { - var ARGS = [ - null, - [ - { - name: 'sink-name' - } - ], - {} - ]; - - beforeEach(function() { - logging.request = function(config, callback) { - callback.apply(null, ARGS); - }; - }); - - it('should execute callback with Logs & API resp', function(done) { - var sinkInstance = {}; - - logging.sink = function(name) { - assert.strictEqual(name, ARGS[1][0].name); - return sinkInstance; - }; - - logging.getSinks(OPTIONS, function(err, sinks) { - assert.ifError(err); - - assert.strictEqual(sinks[0], sinkInstance); - assert.strictEqual(sinks[0].metadata, ARGS[1][0]); - - done(); - }); - }); - }); - }); - - describe('getSinksStream', function() { - var OPTIONS = { - a: 'b', - c: 'd', - gaxOptions: { - a: 'b', - c: 'd' - } - }; - - var REQUEST_STREAM; - var RESULT = { - name: 'sink-name' - }; - - beforeEach(function() { - REQUEST_STREAM = through.obj(); - REQUEST_STREAM.push(RESULT); - - logging.request = function() { - return REQUEST_STREAM; - }; - }); - - it('should make request once reading', function(done) { - logging.request = function(config) { - assert.strictEqual(config.client, 'configServiceV2Client'); - assert.strictEqual(config.method, 'listSinksStream'); - - assert.deepEqual(config.reqOpts, { - parent: 'projects/' + logging.projectId, - a: 'b', - c: 'd' - }); - - assert.deepEqual(config.gaxOpts, { - autoPaginate: undefined, - a: 'b', - c: 'd' - }); - - setImmediate(done); - - return REQUEST_STREAM; - }; - - var stream = logging.getSinksStream(OPTIONS); - stream.emit('reading'); - }); - - it('should convert results from request to Sink', function(done) { - var stream = logging.getSinksStream(OPTIONS); - - var sinkInstance = {}; - - logging.sink = function(name) { - assert.strictEqual(name, RESULT.name); - return sinkInstance; - }; - - stream.on('data', function(sink) { - assert.strictEqual(sink, sinkInstance); - assert.strictEqual(sink.metadata, RESULT); - done(); - }); - - stream.emit('reading'); - }); - - it('should expose abort function', function(done) { - REQUEST_STREAM.abort = done; - - var stream = logging.getSinksStream(OPTIONS); - - stream.emit('reading'); - - stream.abort(); - }); - }); - - describe('log', function() { - var NAME = 'log-name'; - - it('should return a Log object', function() { - var log = logging.log(NAME); - assert(log instanceof FakeLog); - assert.strictEqual(log.calledWith_[0], logging); - assert.strictEqual(log.calledWith_[1], NAME); - }); - }); - - describe('request', function() { - var CONFIG = { - client: 'client', - method: 'method', - reqOpts: { - a: 'b', - c: 'd' - }, - gaxOpts: {} - }; - - var PROJECT_ID = 'project-id'; - - beforeEach(function() { - logging.auth = { - getProjectId: function(callback) { - callback(null, PROJECT_ID); - } - }; - - logging.api[CONFIG.client] = { - [CONFIG.method]: util.noop - }; - }); - - describe('prepareGaxRequest', function() { - it('should get the project ID', function(done) { - logging.auth.getProjectId = function() { - done(); - }; - - logging.request(CONFIG, assert.ifError); - }); - - it('should return error if getting project ID failed', function(done) { - var error = new Error('Error.'); - - logging.auth.getProjectId = function(callback) { - callback(error); - }; - - logging.request(CONFIG, function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - - it('should initiate and cache the client', function() { - var fakeClient = { - [CONFIG.method]: util.noop - }; - - v2Override = function(options) { - assert.strictEqual(options, logging.options); - - return { - [CONFIG.client]: function(options) { - assert.strictEqual(options, logging.options); - return fakeClient; - } - }; - }; - - logging.api = {}; - - logging.request(CONFIG, assert.ifError); - - assert.strictEqual(logging.api[CONFIG.client], fakeClient); - }); - - it('should use the cached client', function(done) { - v2Override = function() { - done(new Error('Should not re-instantiate a GAX client.')); - }; - - logging.request(CONFIG); - done(); - }); - - it('should replace the project ID token', function(done) { - var replacedReqOpts = {}; - - replaceProjectIdTokenOverride = function(reqOpts, projectId) { - assert.notStrictEqual(reqOpts, CONFIG.reqOpts); - assert.deepEqual(reqOpts, CONFIG.reqOpts); - assert.strictEqual(projectId, PROJECT_ID); - - return replacedReqOpts; - }; - - logging.api[CONFIG.client][CONFIG.method] = { - bind: function(gaxClient, reqOpts) { - assert.strictEqual(reqOpts, replacedReqOpts); - - setImmediate(done); - - return util.noop; - } - }; - - logging.request(CONFIG, assert.ifError); - }); - }); - - describe('makeRequestCallback', function() { - it('should return if in snippet sandbox', function(done) { - logging.auth.getProjectId = function() { - done(new Error('Should not have gotten project ID.')); - }; - - global.GCLOUD_SANDBOX_ENV = true; - var returnValue = logging.request(CONFIG, assert.ifError); - delete global.GCLOUD_SANDBOX_ENV; - - assert.strictEqual(returnValue, undefined); - done(); - }); - - it('should prepare the request', function(done) { - logging.api[CONFIG.client][CONFIG.method] = { - bind: function(gaxClient, reqOpts, gaxOpts) { - assert.strictEqual(gaxClient, logging.api[CONFIG.client]); - assert.deepEqual(reqOpts, CONFIG.reqOpts); - assert.strictEqual(gaxOpts, CONFIG.gaxOpts); - - setImmediate(done); - - return util.noop; - } - }; - - logging.request(CONFIG, assert.ifError); - }); - - it('should execute callback with error', function(done) { - var error = new Error('Error.'); - - logging.api[CONFIG.client][CONFIG.method] = function() { - var callback = [].slice.call(arguments).pop(); - callback(error); - }; - - logging.request(CONFIG, function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - - it('should execute the request function', function() { - logging.api[CONFIG.client][CONFIG.method] = function(done) { - var callback = [].slice.call(arguments).pop(); - callback(null, done); // so it ends the test - }; - - logging.request(CONFIG, assert.ifError); - }); - }); - - describe('makeRequestStream', function() { - var GAX_STREAM; - - beforeEach(function() { - GAX_STREAM = through(); - - logging.api[CONFIG.client][CONFIG.method] = { - bind: function() { - return function() { - return GAX_STREAM; - }; - } - }; - }); - - it('should return if in snippet sandbox', function(done) { - logging.auth.getProjectId = function() { - done(new Error('Should not have gotten project ID.')); - }; - - global.GCLOUD_SANDBOX_ENV = true; - var returnValue = logging.request(CONFIG); - returnValue.emit('reading'); - delete global.GCLOUD_SANDBOX_ENV; - - assert(returnValue instanceof require('stream')); - done(); - }); - - it('should expose an abort function', function(done) { - GAX_STREAM.cancel = done; - - var requestStream = logging.request(CONFIG); - requestStream.emit('reading'); - requestStream.abort(); - }); - - it('should prepare the request once reading', function(done) { - logging.api[CONFIG.client][CONFIG.method] = { - bind: function(gaxClient, reqOpts, gaxOpts) { - assert.strictEqual(gaxClient, logging.api[CONFIG.client]); - assert.deepEqual(reqOpts, CONFIG.reqOpts); - assert.strictEqual(gaxOpts, CONFIG.gaxOpts); - - setImmediate(done); - - return function() { - return GAX_STREAM; - }; - } - }; - - var requestStream = logging.request(CONFIG); - requestStream.emit('reading'); - }); - - it('should destroy the stream with prepare error', function(done) { - var error = new Error('Error.'); - - logging.auth.getProjectId = function(callback) { - callback(error); - }; - - var requestStream = logging.request(CONFIG); - requestStream.emit('reading'); - - requestStream.on('error', function(err) { - assert.strictEqual(err, error); - done(); - }); - }); - - it('should destroy the stream with GAX error', function(done) { - var error = new Error('Error.'); - - var requestStream = logging.request(CONFIG); - requestStream.emit('reading'); - - requestStream.on('error', function(err) { - assert.strictEqual(err, error); - done(); - }); - - GAX_STREAM.emit('error', error); - }); - }); - }); - - describe('sink', function() { - var NAME = 'sink-name'; - - it('should return a Log object', function() { - var sink = logging.sink(NAME); - assert(sink instanceof FakeSink); - assert.strictEqual(sink.calledWith_[0], logging); - assert.strictEqual(sink.calledWith_[1], NAME); - }); - }); - - describe('setAclForBucket_', function() { - var SINK_NAME = 'name'; - var CONFIG; - - var bucket; - - beforeEach(function() { - bucket = { - name: 'bucket-name', - acl: { - owners: { - addGroup: util.noop - } - } - }; - - CONFIG = { - destination: bucket - }; - }); - - it('should add cloud-logs as an owner', function(done) { - bucket.acl.owners.addGroup = function(entity) { - assert.strictEqual(entity, 'cloud-logs@google.com'); - done(); - }; - - logging.setAclForBucket_(SINK_NAME, CONFIG, assert.ifError); - }); - - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = {}; - - beforeEach(function() { - bucket.acl.owners.addGroup = function(entity, callback) { - callback(error, apiResponse); - }; - }); - - it('should return error and API response to callback', function(done) { - logging.setAclForBucket_(SINK_NAME, CONFIG, function(err, sink, resp) { - assert.strictEqual(err, error); - assert.strictEqual(sink, null); - assert.strictEqual(resp, apiResponse); - - done(); - }); - }); - }); - - describe('success', function() { - var apiResponse = {}; - - beforeEach(function() { - bucket.acl.owners.addGroup = function(entity, callback) { - callback(null, apiResponse); - }; - }); - - it('should call createSink with string destination', function(done) { - bucket.acl.owners.addGroup = function(entity, callback) { - logging.createSink = function(name, config, callback) { - assert.strictEqual(name, SINK_NAME); - - assert.strictEqual(config, CONFIG); - - var expectedDestination = 'storage.googleapis.com/' + bucket.name; - assert.strictEqual(config.destination, expectedDestination); - - callback(); // done() - }; - - callback(null, apiResponse); - }; - - logging.setAclForBucket_(SINK_NAME, CONFIG, done); - }); - }); - }); - - describe('setAclForDataset_', function() { - var SINK_NAME = 'name'; - var CONFIG; - var dataset; - - beforeEach(function() { - dataset = { - id: 'dataset-id', - parent: { - projectId: PROJECT_ID - } - }; - - CONFIG = { - destination: dataset - }; - }); - - describe('metadata refresh', function() { - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = {}; - - beforeEach(function() { - dataset.getMetadata = function(callback) { - callback(error, null, apiResponse); - }; - }); - - it('should execute the callback with error & API resp', function(done) { - logging.setAclForDataset_(SINK_NAME, CONFIG, function(err, _, resp) { - assert.strictEqual(err, error); - assert.strictEqual(_, null); - assert.strictEqual(resp, apiResponse); - done(); - }); - }); - }); - - describe('success', function() { - var apiResponse = { - access: [{}, {}] - }; - - var originalAccess = [].slice.call(apiResponse.access); - - beforeEach(function() { - dataset.getMetadata = function(callback) { - callback(null, apiResponse, apiResponse); - }; - }); - - it('should set the correct metadata', function(done) { - var access = { - role: 'WRITER', - groupByEmail: 'cloud-logs@google.com' - }; - - var expectedAccess = [].slice.call(originalAccess).concat(access); - - dataset.setMetadata = function(metadata) { - assert.deepEqual(apiResponse.access, originalAccess); - assert.deepEqual(metadata.access, expectedAccess); - done(); - }; - - logging.setAclForDataset_(SINK_NAME, CONFIG, assert.ifError); - }); - - describe('updating metadata error', function() { - var error = new Error('Error.'); - var apiResponse = {}; - - beforeEach(function() { - dataset.setMetadata = function(metadata, callback) { - callback(error, apiResponse); - }; - }); - - it('should exec callback with error & API response', function(done) { - logging.setAclForDataset_(SINK_NAME, CONFIG, function(err, _, res) { - assert.strictEqual(err, error); - assert.strictEqual(_, null); - assert.strictEqual(res, apiResponse); - done(); - }); - }); - }); - - describe('updating metadata success', function() { - var apiResponse = {}; - - beforeEach(function() { - dataset.setMetadata = function(metadata, callback) { - callback(null, apiResponse); - }; - }); - - it('should call createSink with string destination', function(done) { - logging.createSink = function(name, config, callback) { - var expectedDestination = [ - 'bigquery.googleapis.com', - 'projects', - dataset.parent.projectId, - 'datasets', - dataset.id - ].join('/'); - - assert.strictEqual(name, SINK_NAME); - assert.strictEqual(config, CONFIG); - assert.strictEqual(config.destination, expectedDestination); - callback(); // done() - }; - - logging.setAclForDataset_(SINK_NAME, CONFIG, done); - }); - }); - }); - }); - }); - - describe('setAclForTopic_', function() { - var SINK_NAME = 'name'; - var CONFIG; - var topic; - - beforeEach(function() { - topic = { - name: 'topic-name', - iam: { - getPolicy: util.noop, - setPolicy: util.noop - } - }; - - CONFIG = { - destination: topic - }; - }); - - describe('get policy', function() { - describe('error', function() { - var error = new Error('Error.'); - var apiResponse = {}; - - beforeEach(function() { - topic.iam.getPolicy = function(callback) { - callback(error, null, apiResponse); - }; - }); - - it('should execute the callback with error & API resp', function(done) { - logging.setAclForTopic_(SINK_NAME, CONFIG, function(err, _, resp) { - assert.strictEqual(err, error); - assert.strictEqual(_, null); - assert.strictEqual(resp, apiResponse); - done(); - }); - }); - }); - - describe('success', function() { - var apiResponse = { - bindings: [{}, {}] - }; - - var originalBindings = [].slice.call(apiResponse.bindings); - - beforeEach(function() { - topic.iam.getPolicy = function(callback) { - callback(null, apiResponse, apiResponse); - }; - }); - - it('should set the correct policy bindings', function(done) { - var binding = { - role: 'roles/pubsub.publisher', - members: [ - 'serviceAccount:cloud-logs@system.gserviceaccount.com' - ] - }; - - var expectedBindings = [].slice.call(originalBindings); - expectedBindings.push(binding); - - topic.iam.setPolicy = function(policy) { - assert.strictEqual(policy, apiResponse); - assert.deepEqual(policy.bindings, expectedBindings); - done(); - }; - - logging.setAclForTopic_(SINK_NAME, CONFIG, assert.ifError); - }); - - describe('updating policy error', function() { - var error = new Error('Error.'); - var apiResponse = {}; - - beforeEach(function() { - topic.iam.setPolicy = function(policy, callback) { - callback(error, null, apiResponse); - }; - }); - - it('should exec callback with error & API response', function(done) { - logging.setAclForTopic_(SINK_NAME, CONFIG, function(err, _, res) { - assert.strictEqual(err, error); - assert.strictEqual(_, null); - assert.strictEqual(res, apiResponse); - done(); - }); - }); - }); - - describe('updating policy success', function() { - var apiResponse = {}; - - beforeEach(function() { - topic.iam.setPolicy = function(policy, callback) { - callback(null, apiResponse); - }; - }); - - it('should call createSink with string destination', function(done) { - logging.createSink = function(name, config, callback) { - var expectedDestination = 'pubsub.googleapis.com/' + topic.name; - assert.strictEqual(name, SINK_NAME); - assert.strictEqual(config, CONFIG); - assert.strictEqual(config.destination, expectedDestination); - callback(); // done() - }; - - logging.setAclForTopic_(SINK_NAME, CONFIG, done); - }); - }); - }); - }); - }); -}); diff --git a/packages/logging/test/log.js b/packages/logging/test/log.js deleted file mode 100644 index 1deed4debd3..00000000000 --- a/packages/logging/test/log.js +++ /dev/null @@ -1,755 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var assert = require('assert'); -var extend = require('extend'); -var prop = require('propprop'); -var proxyquire = require('proxyquire'); -var util = require('@google-cloud/common').util; - -var promisifed = false; -var fakeUtil = extend({}, util, { - promisifyAll: function(Class, options) { - if (Class.name !== 'Log') { - return; - } - - promisifed = true; - assert.deepEqual(options.exclude, ['entry']); - } -}); - -var Entry = require('../src/entry.js'); - -function FakeMetadata() { - this.calledWith_ = arguments; -} - -describe('Log', function() { - var Log; - var log; - - var PROJECT_ID = 'project-id'; - var LOG_NAME = 'escaping/required/for/this/log-name'; - var LOG_NAME_ENCODED = encodeURIComponent(LOG_NAME); - var LOG_NAME_FORMATTED = [ - 'projects', - PROJECT_ID, - 'logs', - LOG_NAME_ENCODED - ].join('/'); - - var LOGGING; - - var assignSeverityToEntriesOverride = null; - - before(function() { - Log = proxyquire('../src/log.js', { - '@google-cloud/common': { - util: fakeUtil - }, - './entry.js': Entry, - './metadata.js': FakeMetadata - }); - var assignSeverityToEntries_ = Log.assignSeverityToEntries_; - Log.assignSeverityToEntries_ = function() { - return (assignSeverityToEntriesOverride || assignSeverityToEntries_) - .apply(null, arguments); - }; - }); - - beforeEach(function() { - assignSeverityToEntriesOverride = null; - - LOGGING = { - projectId: PROJECT_ID, - entry: util.noop, - request: util.noop - }; - - log = new Log(LOGGING, LOG_NAME_FORMATTED); - }); - - describe('instantiation', function() { - it('should promisify all the things', function() { - assert(promisifed); - }); - - it('should localize the escaped name', function() { - assert.strictEqual(log.name, LOG_NAME_ENCODED); - }); - - it('should localize removeCircular_ to default value', function() { - assert.strictEqual(log.removeCircular_, false); - }); - - it('should localize the formatted name', function() { - var formattedName = 'formatted-name'; - - var formatName_ = Log.formatName_; - Log.formatName_ = function() { - Log.formatName_ = formatName_; - return formattedName; - }; - - var log = new Log(LOGGING, LOG_NAME_FORMATTED); - - assert.strictEqual(log.formattedName_, formattedName); - }); - - it('should localize an instance of Metadata', function() { - assert(log.metadata_ instanceof FakeMetadata); - assert.strictEqual(log.metadata_.calledWith_[0], LOGGING); - }); - - it('should accept and localize options.removeCircular', function() { - var options = { removeCircular: true }; - var log = new Log(LOGGING, LOG_NAME_FORMATTED, options); - assert.strictEqual(log.removeCircular_, true); - }); - - it('should localize the Logging instance', function() { - assert.strictEqual(log.logging, LOGGING); - }); - - it('should localize the name', function() { - assert.strictEqual(log.name, LOG_NAME_FORMATTED.split('/').pop()); - }); - }); - - describe('assignSeverityToEntries_', function() { - var circular = {}; - circular.circular = circular; - - var ENTRIES = [ - { data: { a: 'b' } }, - { data: { c: 'd' } }, - { data: { e: circular }} - ]; - - var SEVERITY = 'severity'; - - it('should assign severity to a single entry', function() { - assert.deepEqual( - Log.assignSeverityToEntries_(ENTRIES[0], SEVERITY) - .map(prop('metadata')) - .map(prop('severity')), - [ SEVERITY ] - ); - }); - - it('should assign severity property to multiple entries', function() { - assert.deepEqual( - Log.assignSeverityToEntries_(ENTRIES, SEVERITY) - .map(prop('metadata')) - .map(prop('severity')), - [ - SEVERITY, - SEVERITY, - SEVERITY - ] - ); - }); - - it('should not affect original array', function() { - var originalEntries = extend({}, ENTRIES); - - Log.assignSeverityToEntries_(originalEntries, SEVERITY); - - assert.deepEqual(originalEntries, ENTRIES); - }); - }); - - describe('formatName_', function() { - var PROJECT_ID = 'project-id'; - var NAME = 'log-name'; - - var EXPECTED = 'projects/' + PROJECT_ID + '/logs/' + NAME; - - it('should properly format the name', function() { - assert.strictEqual(Log.formatName_(PROJECT_ID, NAME), EXPECTED); - }); - - it('should encode a name that requires it', function() { - var name = 'appengine/logs'; - var expectedName = 'projects/' + PROJECT_ID + '/logs/appengine%2Flogs'; - - assert.strictEqual(Log.formatName_(PROJECT_ID, name), expectedName); - }); - - it('should not encode a name that does not require it', function() { - var name = 'appengine%2Flogs'; - var expectedName = 'projects/' + PROJECT_ID + '/logs/' + name; - - assert.strictEqual(Log.formatName_(PROJECT_ID, name), expectedName); - }); - }); - - describe('delete', function() { - it('should accept gaxOptions', function(done) { - log.logging.request = function(config, callback) { - assert.strictEqual(config.client, 'loggingServiceV2Client'); - assert.strictEqual(config.method, 'deleteLog'); - - assert.deepEqual(config.reqOpts, { - logName: log.formattedName_ - }); - - assert.deepEqual(config.gaxOpts, {}); - - callback(); // done() - }; - - log.delete(done); - }); - - it('should accept gaxOptions', function(done) { - var gaxOptions = {}; - - log.logging.request = function(config) { - assert.strictEqual(config.gaxOpts, gaxOptions); - done(); - }; - - log.delete(gaxOptions, assert.ifError); - }); - }); - - describe('entry', function() { - it('should return an entry from Logging', function() { - var metadata = { - val: true - }; - var data = {}; - - var entryObject = {}; - - log.logging.entry = function(metadata_, data_) { - assert.deepEqual(metadata_, metadata); - assert.strictEqual(data_, data); - return entryObject; - }; - - var entry = log.entry(metadata, data); - assert.strictEqual(entry, entryObject); - }); - - it('should assume one argument means data', function(done) { - var data = {}; - - log.logging.entry = function(metadata, data_) { - assert.strictEqual(data_, data); - done(); - }; - - log.entry(data); - }); - }); - - describe('getEntries', function() { - var EXPECTED_OPTIONS = { - filter: 'logName="' + LOG_NAME_FORMATTED + '"' - }; - - it('should call Logging getEntries with defaults', function(done) { - log.logging.getEntries = function(options, callback) { - assert.deepEqual(options, EXPECTED_OPTIONS); - callback(); // done() - }; - - log.getEntries(done); - }); - - it('should allow overriding the options', function(done) { - var options = { - custom: true, - filter: 'custom filter' - }; - - log.logging.getEntries = function(options_, callback) { - assert.deepEqual(options_, extend({}, EXPECTED_OPTIONS, options)); - callback(); // done() - }; - - log.getEntries(options, done); - }); - }); - - describe('getEntriesStream', function() { - var fakeStream = {}; - var EXPECTED_OPTIONS = { - filter: 'logName="' + LOG_NAME_FORMATTED + '"' - }; - - it('should call Logging getEntriesStream with defaults', function(done) { - log.logging.getEntriesStream = function(options) { - assert.deepEqual(options, EXPECTED_OPTIONS); - setImmediate(done); - return fakeStream; - }; - - var stream = log.getEntriesStream(); - assert.strictEqual(stream, fakeStream); - }); - - it('should allow overriding the options', function(done) { - var options = { - custom: true, - filter: 'custom filter' - }; - - log.logging.getEntriesStream = function(options_) { - assert.deepEqual(options_, extend({}, EXPECTED_OPTIONS, options)); - setImmediate(done); - return fakeStream; - }; - - var stream = log.getEntriesStream(options); - assert.strictEqual(stream, fakeStream); - }); - }); - - describe('write', function() { - var ENTRY = {}; - var OPTIONS = {}; - var FAKE_RESOURCE = 'fake-resource'; - - beforeEach(function() { - log.decorateEntries_ = function(entries) { - return entries; - }; - log.metadata_.getDefaultResource = function(callback) { - callback(null, FAKE_RESOURCE); - }; - }); - - it('should forward options.resource to request', function(done) { - var CUSTOM_RESOURCE = 'custom-resource'; - var optionsWithResource = extend({}, OPTIONS, { - resource: CUSTOM_RESOURCE - }); - - log.logging.request = function(config, callback) { - assert.strictEqual(config.client, 'loggingServiceV2Client'); - assert.strictEqual(config.method, 'writeLogEntries'); - - assert.deepEqual(config.reqOpts, { - logName: log.formattedName_, - entries: [ENTRY], - resource: CUSTOM_RESOURCE - }); - - assert.strictEqual(config.gaxOpts, undefined); - - callback(); - }; - - log.write(ENTRY, optionsWithResource, done); - }); - - it('should transform camelcase label keys to snake case', function(done) { - var CUSTOM_RESOURCE = { - labels: { - camelCaseKey: 'camel-case-key-val' - } - }; - var EXPECTED_RESOURCE = { - labels: { - camel_case_key: 'camel-case-key-val' - } - }; - var optionsWithResource = extend({}, OPTIONS, { - resource: CUSTOM_RESOURCE - }); - - log.logging.request = function(config, callback) { - assert.strictEqual(config.client, 'loggingServiceV2Client'); - assert.strictEqual(config.method, 'writeLogEntries'); - - assert.deepEqual(config.reqOpts, { - logName: log.formattedName_, - entries: [ENTRY], - resource: EXPECTED_RESOURCE - }); - - assert.strictEqual(config.gaxOpts, undefined); - - callback(); - }; - - log.write(ENTRY, optionsWithResource, done); - }); - - it('should make the correct API request', function(done) { - log.logging.request = function(config, callback) { - assert.strictEqual(config.client, 'loggingServiceV2Client'); - assert.strictEqual(config.method, 'writeLogEntries'); - - assert.deepEqual(config.reqOpts, { - logName: log.formattedName_, - entries: [ENTRY], - resource: FAKE_RESOURCE - }); - - assert.strictEqual(config.gaxOpts, undefined); - - callback(); - }; - - log.write(ENTRY, OPTIONS, done); - }); - - it('should arrify & decorate the entries', function(done) { - var decoratedEntries = []; - - log.decorateEntries_ = function(entries) { - assert.strictEqual(entries[0], ENTRY); - return decoratedEntries; - }; - - log.logging.request = function(config) { - assert.strictEqual(config.reqOpts.entries, decoratedEntries); - done(); - }; - - log.write(ENTRY, OPTIONS, assert.ifError); - }); - - it('should not require options', function(done) { - log.logging.request = function(config, callback) { - callback(); // done() - }; - - log.write(ENTRY, done); - }); - }); - - describe('severity shortcuts', function() { - var ENTRY = {}; - var LABELS = []; - - beforeEach(function() { - log.write = util.noop; - }); - - describe('alert', function() { - it('should format the entries', function(done) { - assignSeverityToEntriesOverride = function(entries, severity) { - assert.strictEqual(entries, ENTRY); - assert.strictEqual(severity, 'ALERT'); - - done(); - }; - - log.alert(ENTRY, LABELS, assert.ifError); - }); - - it('should pass correct arguments to write', function(done) { - var assignedEntries = []; - - assignSeverityToEntriesOverride = function() { - return assignedEntries; - }; - - log.write = function(entry, labels, callback) { - assert.strictEqual(entry, assignedEntries); - assert.strictEqual(labels, LABELS); - callback(); // done() - }; - - log.alert(ENTRY, LABELS, done); - }); - }); - - describe('critical', function() { - it('should format the entries', function(done) { - assignSeverityToEntriesOverride = function(entries, severity) { - assert.strictEqual(entries, ENTRY); - assert.strictEqual(severity, 'CRITICAL'); - - done(); - }; - - log.critical(ENTRY, LABELS, assert.ifError); - }); - - it('should pass correct arguments to write', function(done) { - var assignedEntries = []; - - assignSeverityToEntriesOverride = function() { - return assignedEntries; - }; - - log.write = function(entry, labels, callback) { - assert.strictEqual(entry, assignedEntries); - assert.strictEqual(labels, LABELS); - callback(); // done() - }; - - log.critical(ENTRY, LABELS, done); - }); - }); - - describe('debug', function() { - it('should format the entries', function(done) { - assignSeverityToEntriesOverride = function(entries, severity) { - assert.strictEqual(entries, ENTRY); - assert.strictEqual(severity, 'DEBUG'); - - done(); - }; - - log.debug(ENTRY, LABELS, assert.ifError); - }); - - it('should pass correct arguments to write', function(done) { - var assignedEntries = []; - - assignSeverityToEntriesOverride = function() { - return assignedEntries; - }; - - log.write = function(entry, labels, callback) { - assert.strictEqual(entry, assignedEntries); - assert.strictEqual(labels, LABELS); - callback(); // done() - }; - - log.debug(ENTRY, LABELS, done); - }); - }); - - describe('emergency', function() { - it('should format the entries', function(done) { - assignSeverityToEntriesOverride = function(entries, severity) { - assert.strictEqual(entries, ENTRY); - assert.strictEqual(severity, 'EMERGENCY'); - - done(); - }; - - log.emergency(ENTRY, LABELS, assert.ifError); - }); - - it('should pass correct arguments to write', function(done) { - var assignedEntries = []; - - assignSeverityToEntriesOverride = function() { - return assignedEntries; - }; - - log.write = function(entry, labels, callback) { - assert.strictEqual(entry, assignedEntries); - assert.strictEqual(labels, LABELS); - callback(); // done() - }; - - log.emergency(ENTRY, LABELS, done); - }); - }); - - describe('error', function() { - it('should format the entries', function(done) { - assignSeverityToEntriesOverride = function(entries, severity) { - assert.strictEqual(entries, ENTRY); - assert.strictEqual(severity, 'ERROR'); - - done(); - }; - - log.error(ENTRY, LABELS, assert.ifError); - }); - - it('should pass correct arguments to write', function(done) { - var assignedEntries = []; - - assignSeverityToEntriesOverride = function() { - return assignedEntries; - }; - - log.write = function(entry, labels, callback) { - assert.strictEqual(entry, assignedEntries); - assert.strictEqual(labels, LABELS); - callback(); // done() - }; - - log.error(ENTRY, LABELS, done); - }); - }); - - describe('info', function() { - it('should format the entries', function(done) { - assignSeverityToEntriesOverride = function(entries, severity) { - assert.strictEqual(entries, ENTRY); - assert.strictEqual(severity, 'INFO'); - - done(); - }; - - log.info(ENTRY, LABELS, assert.ifError); - }); - - it('should pass correct arguments to write', function(done) { - var assignedEntries = []; - - assignSeverityToEntriesOverride = function() { - return assignedEntries; - }; - - log.write = function(entry, labels, callback) { - assert.strictEqual(entry, assignedEntries); - assert.strictEqual(labels, LABELS); - callback(); // done() - }; - - log.info(ENTRY, LABELS, done); - }); - }); - - describe('notice', function() { - it('should format the entries', function(done) { - assignSeverityToEntriesOverride = function(entries, severity) { - assert.strictEqual(entries, ENTRY); - assert.strictEqual(severity, 'NOTICE'); - - done(); - }; - - log.notice(ENTRY, LABELS, assert.ifError); - }); - - it('should pass correct arguments to write', function(done) { - var assignedEntries = []; - - assignSeverityToEntriesOverride = function() { - return assignedEntries; - }; - - log.write = function(entry, labels, callback) { - assert.strictEqual(entry, assignedEntries); - assert.strictEqual(labels, LABELS); - callback(); // done() - }; - - log.notice(ENTRY, LABELS, done); - }); - }); - - describe('warning', function() { - it('should format the entries', function(done) { - assignSeverityToEntriesOverride = function(entries, severity) { - assert.strictEqual(entries, ENTRY); - assert.strictEqual(severity, 'WARNING'); - - done(); - }; - - log.warning(ENTRY, LABELS, assert.ifError); - }); - - it('should pass correct arguments to write', function(done) { - var assignedEntries = []; - - assignSeverityToEntriesOverride = function() { - return assignedEntries; - }; - - log.write = function(entry, labels, callback) { - assert.strictEqual(entry, assignedEntries); - assert.strictEqual(labels, LABELS); - callback(); // done() - }; - - log.warning(ENTRY, LABELS, done); - }); - }); - }); - - describe('decorateEntries_', function() { - var toJSONResponse = {}; - - function FakeEntry() {} - FakeEntry.prototype.toJSON = function() { - return toJSONResponse; - }; - - beforeEach(function() { - log.entry = function() { - return new FakeEntry(); - }; - - log.metadata_.assignDefaultResource = function(entryJson, callback) { - callback(null, entryJson); - }; - }); - - it('should create an Entry object if one is not provided', function() { - var entry = {}; - - log.entry = function(entry_) { - assert.strictEqual(entry_, entry); - return new FakeEntry(); - }; - - var decoratedEntries = log.decorateEntries_([entry]); - assert.strictEqual(decoratedEntries[0], toJSONResponse); - }); - - it('should get JSON format from Entry object', function() { - log.entry = function() { - throw new Error('should not be called'); - }; - - var entry = new Entry(); - entry.toJSON = function() { - return toJSONResponse; - }; - - var decoratedEntries = log.decorateEntries_([entry]); - assert.strictEqual(decoratedEntries[0], toJSONResponse); - }); - - it('should pass log.removeCircular to toJSON', function(done) { - log.removeCircular_ = true; - - var entry = new Entry(); - entry.toJSON = function(options_) { - assert.deepStrictEqual(options_, { removeCircular: true }); - setImmediate(done); - return {}; - }; - - log.decorateEntries_([entry]); - }); - - it('should throw error from serialization', function() { - var error = new Error('Error.'); - - var entry = new Entry(); - entry.toJSON = function() { - throw error; - }; - - try { - log.decorateEntries_([entry]); - } catch (err) { - assert.strictEqual(err, error); - } - }); - }); -}); diff --git a/packages/logging/test/metadata.js b/packages/logging/test/metadata.js deleted file mode 100644 index 7297b63743e..00000000000 --- a/packages/logging/test/metadata.js +++ /dev/null @@ -1,331 +0,0 @@ -/** - * Copyright 2016 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var assert = require('assert'); -var extend = require('extend'); -var proxyquire = require('proxyquire'); - -var instanceOverride; -var fakeGcpMetadata = { - instance: function(path, cb) { - setImmediate(function() { - if (instanceOverride && instanceOverride.path) { - assert.strictEqual(path, instanceOverride.path); - } - var args = (instanceOverride && instanceOverride.args) || - [null, null, 'fake-instance-value']; - cb.apply(fakeGcpMetadata, args); - }); - } -}; - -describe('metadata', function() { - var MetadataCached; - var Metadata; - var metadata; - - var LOGGING; - - var ENV_CACHED = extend({}, process.env); - - before(function() { - Metadata = proxyquire('../src/metadata.js', { - 'gcp-metadata': fakeGcpMetadata - }); - - MetadataCached = extend({}, Metadata); - }); - - beforeEach(function() { - LOGGING = { - auth: {} - }; - extend(Metadata, MetadataCached); - metadata = new Metadata(LOGGING); - instanceOverride = null; - }); - - afterEach(function() { - extend(process.env, ENV_CACHED); - }); - - describe('instantiation', function() { - it('should localize Logging instance', function() { - assert.strictEqual(metadata.logging, LOGGING); - }); - }); - - describe('getCloudFunctionDescriptor', function() { - var FUNCTION_NAME = 'function-name'; - var SUPERVISOR_REGION = 'supervisor-region'; - - beforeEach(function() { - process.env.FUNCTION_NAME = FUNCTION_NAME; - process.env.SUPERVISOR_REGION = SUPERVISOR_REGION; - }); - - it('should return the correct descriptor', function() { - assert.deepEqual(Metadata.getCloudFunctionDescriptor(), { - type: 'cloud_function', - labels: { - function_name: FUNCTION_NAME, - region: SUPERVISOR_REGION - } - }); - }); - }); - - describe('getCloudFunctionDescriptor', function() { - var GAE_MODULE_NAME = 'gae-module-name'; - var GAE_SERVICE = 'gae-service'; - var GAE_VERSION = 'gae-version'; - - beforeEach(function() { - process.env.GAE_MODULE_NAME = GAE_MODULE_NAME; - process.env.GAE_SERVICE = GAE_SERVICE; - process.env.GAE_VERSION = GAE_VERSION; - }); - - it('should return the correct descriptor', function() { - assert.deepEqual(Metadata.getGAEDescriptor(), { - type: 'gae_app', - labels: { - module_id: GAE_SERVICE, - version_id: GAE_VERSION - } - }); - }); - - it('should use GAE_MODULE_NAME for module_id', function() { - delete process.env.GAE_SERVICE; - - var moduleId = Metadata.getGAEDescriptor().labels.module_id; - assert.strictEqual(moduleId, GAE_MODULE_NAME); - }); - }); - - describe('getGKEDescriptor', function() { - var CLUSTER_NAME = 'gke-cluster-name'; - - it('should return the correct descriptor', function(done) { - instanceOverride = { - path: 'attributes/cluster-name', - args: [null, null, CLUSTER_NAME] - }; - - Metadata.getGKEDescriptor(function(err, descriptor) { - assert.ifError(err); - assert.deepEqual(descriptor, { - type: 'container', - labels: { - cluster_name: CLUSTER_NAME - } - }); - done(); - }); - }); - - it('should return error on failure to acquire metadata', function(done) { - var FAKE_ERROR = new Error(); - instanceOverride = { args: [ FAKE_ERROR ] }; - - Metadata.getGKEDescriptor(function(err) { - assert.strictEqual(err, FAKE_ERROR); - done(); - }); - }); - }); - - describe('getGCEDescriptor', function() { - var INSTANCE_ID = 'fake-instance-id'; - - it('should return the correct descriptor', function(done) { - instanceOverride = { - path: 'id', - args: [null, null, INSTANCE_ID] - }; - - Metadata.getGCEDescriptor(function(err, descriptor) { - assert.ifError(err); - assert.deepEqual(descriptor, { - type: 'gce_instance', - labels: { - instance_id: INSTANCE_ID - } - }); - done(); - }); - }); - - it('should return error on failure to acquire metadata', function(done) { - var FAKE_ERROR = new Error(); - instanceOverride = { args: [ FAKE_ERROR ] }; - - Metadata.getGCEDescriptor(function(err) { - assert.strictEqual(err, FAKE_ERROR); - done(); - }); - }); - }); - - describe('getGlobalDescriptor', function() { - it('should return the correct descriptor', function() { - assert.deepEqual(Metadata.getGlobalDescriptor(), { - type: 'global' - }); - }); - }); - - describe('getDefaultResource', function() { - it('should get the environment from auth client', function(done) { - metadata.logging.auth.getEnvironment = function() { - done(); - }; - - metadata.getDefaultResource(assert.ifError); - }); - - describe('environments', function() { - describe('app engine', function() { - it('should return correct descriptor', function(done) { - var DESCRIPTOR = {}; - - Metadata.getGAEDescriptor = function() { - return DESCRIPTOR; - }; - - metadata.logging.auth.getEnvironment = function(callback) { - callback(null, { - IS_APP_ENGINE: true, - IS_COMPUTE_ENGINE: true - }); - }; - - metadata.getDefaultResource(function(err, defaultResource) { - assert.ifError(err); - assert.strictEqual(defaultResource, DESCRIPTOR); - done(); - }); - }); - }); - - describe('cloud function', function() { - it('should return correct descriptor', function(done) { - var DESCRIPTOR = {}; - - Metadata.getCloudFunctionDescriptor = function() { - return DESCRIPTOR; - }; - - metadata.logging.auth.getEnvironment = function(callback) { - callback(null, { - IS_CLOUD_FUNCTION: true, - IS_COMPUTE_ENGINE: true - }); - }; - - metadata.getDefaultResource(function(err, defaultResource) { - assert.ifError(err); - assert.strictEqual(defaultResource, DESCRIPTOR); - done(); - }); - }); - }); - - describe('compute engine', function() { - it('should return correct descriptor', function(done) { - var INSTANCE_ID = 'overridden-value'; - instanceOverride = { - path: 'id', - args: [null, null, INSTANCE_ID] - }; - - metadata.logging.auth.getEnvironment = function(callback) { - callback(null, { - IS_COMPUTE_ENGINE: true - }); - }; - - metadata.getDefaultResource(function(err, defaultResource) { - assert.ifError(err); - assert.deepStrictEqual(defaultResource, { - type: 'gce_instance', - labels: { - instance_id: INSTANCE_ID - } - }); - done(); - }); - }); - }); - - describe('container engine', function() { - it('should return correct descriptor', function(done) { - var CLUSTER_NAME = 'overridden-value'; - instanceOverride = { - path: 'attributes/cluster-name', - args: [null, null, CLUSTER_NAME] - }; - - metadata.logging.auth.getEnvironment = function(callback) { - callback(null, { - IS_COMPUTE_ENGINE: true, - IS_CONTAINER_ENGINE: true - }); - }; - - metadata.getDefaultResource(function(err, defaultResource) { - assert.ifError(err); - assert.deepStrictEqual(defaultResource, { - type: 'container', - labels: { - cluster_name: CLUSTER_NAME - } - }); - done(); - }); - }); - }); - - describe('global', function() { - it('should return correct descriptor', function(done) { - var DESCRIPTOR = {}; - - Metadata.getGlobalDescriptor = function() { - return DESCRIPTOR; - }; - - metadata.logging.auth.getEnvironment = function(callback) { - callback(null, { - IS_APP_ENGINE: false, - IS_CLOUD_FUNCTION: false, - IS_COMPUTE_ENGINE: false, - IS_CONTAINER_ENGINE: false - }); - }; - - metadata.getDefaultResource(function(err, defaultResource) { - assert.ifError(err); - assert.strictEqual(defaultResource, DESCRIPTOR); - done(); - }); - }); - }); - }); - }); -}); diff --git a/packages/logging/test/sink.js b/packages/logging/test/sink.js deleted file mode 100644 index 8821192aee6..00000000000 --- a/packages/logging/test/sink.js +++ /dev/null @@ -1,285 +0,0 @@ -/** - * Copyright 2015 Google Inc. All Rights Reserved. - * - * 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 - * - * http://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. - */ - -'use strict'; - -var assert = require('assert'); -var extend = require('extend'); -var proxyquire = require('proxyquire'); -var util = require('@google-cloud/common').util; - -var promisifed = false; -var fakeUtil = extend({}, util, { - promisifyAll: function(Class) { - if (Class.name === 'Sink') { - promisifed = true; - } - } -}); - -describe('Sink', function() { - var Sink; - var sink; - - var LOGGING = { - createSink: util.noop, - projectId: 'project-id' - }; - var SINK_NAME = 'sink-name'; - - before(function() { - Sink = proxyquire('../src/sink.js', { - '@google-cloud/common': { - util: fakeUtil - } - }); - }); - - beforeEach(function() { - sink = new Sink(LOGGING, SINK_NAME); - }); - - describe('instantiation', function() { - it('should promisify all the things', function() { - assert(promisifed); - }); - - it('should localize Logging instance', function() { - assert.strictEqual(sink.logging, LOGGING); - }); - - it('should localize the name', function() { - assert.strictEqual(sink.name, SINK_NAME); - }); - - it('should localize the formatted name', function() { - assert.strictEqual( - sink.formattedName_, - 'projects/' + LOGGING.projectId + '/sinks/' + SINK_NAME - ); - }); - }); - - describe('create', function() { - it('should call parent createSink', function(done) { - var config = {}; - - sink.logging.createSink = function(name, config_, callback) { - assert.strictEqual(name, sink.name); - assert.strictEqual(config_, config); - callback(); // done() - }; - - sink.create(config, done); - }); - }); - - describe('delete', function() { - it('should accept gaxOptions', function(done) { - sink.logging.request = function(config, callback) { - assert.strictEqual(config.client, 'configServiceV2Client'); - assert.strictEqual(config.method, 'deleteSink'); - - assert.deepEqual(config.reqOpts, { - sinkName: sink.formattedName_ - }); - - assert.deepEqual(config.gaxOpts, {}); - - callback(); // done() - }; - - sink.delete(done); - }); - - it('should accept gaxOptions', function(done) { - var gaxOptions = {}; - - sink.logging.request = function(config) { - assert.strictEqual(config.gaxOpts, gaxOptions); - done(); - }; - - sink.delete(gaxOptions, assert.ifError); - }); - }); - - describe('getMetadata', function() { - it('should make correct request', function(done) { - sink.logging.request = function(config) { - assert.strictEqual(config.client, 'configServiceV2Client'); - assert.strictEqual(config.method, 'getSink'); - - assert.deepEqual(config.reqOpts, { - sinkName: sink.formattedName_ - }); - - assert.deepEqual(config.gaxOpts, {}); - - done(); - }; - - sink.getMetadata(assert.ifError); - }); - - it('should accept gaxOptions', function(done) { - var gaxOptions = {}; - - sink.logging.request = function(config) { - assert.strictEqual(config.gaxOpts, gaxOptions); - done(); - }; - - sink.delete(gaxOptions, assert.ifError); - }); - - it('should update metadata', function(done) { - var metadata = {}; - - sink.logging.request = function(config, callback) { - callback(null, metadata); - }; - - sink.getMetadata(function() { - assert.strictEqual(sink.metadata, metadata); - done(); - }); - }); - - it('should execute callback with original arguments', function(done) { - var args = [{}, {}, {}]; - - sink.logging.request = function(config, callback) { - callback.apply(null, args); - }; - - sink.getMetadata(function() { - assert.deepStrictEqual([].slice.call(arguments), args); - done(); - }); - }); - }); - - describe('setFilter', function() { - var FILTER = 'filter'; - - it('should call set metadata', function(done) { - sink.setMetadata = function(metadata, callback) { - assert.strictEqual(metadata.filter, FILTER); - callback(); // done() - }; - - sink.setFilter(FILTER, done); - }); - }); - - describe('setMetadata', function() { - var METADATA = { a: 'b', c: 'd' }; - - beforeEach(function() { - sink.getMetadata = function(callback) { - callback(null, METADATA); - }; - }); - - it('should refresh the metadata', function(done) { - sink.getMetadata = function() { - done(); - }; - - sink.setMetadata(METADATA, assert.ifError); - }); - - it('should exec callback with error from refresh', function(done) { - var error = new Error('Error.'); - var apiResponse = {}; - - sink.getMetadata = function(callback) { - callback(error, null, apiResponse); - }; - - sink.setMetadata(METADATA, function(err, apiResponse_) { - assert.strictEqual(err, error); - assert.strictEqual(apiResponse_, apiResponse); - done(); - }); - }); - - it('should make the correct request', function(done) { - var currentMetadata = { a: 'a', e: 'e' }; - - sink.getMetadata = function(callback) { - callback(null, currentMetadata); - }; - - sink.logging.request = function(config) { - assert.strictEqual(config.client, 'configServiceV2Client'); - assert.strictEqual(config.method, 'updateSink'); - - assert.deepEqual(config.reqOpts, { - sinkName: sink.formattedName_, - sink: extend({}, currentMetadata, METADATA) - }); - - assert.strictEqual(config.gaxOpts, undefined); - - done(); - }; - - sink.setMetadata(METADATA, assert.ifError); - }); - - it('should accept gaxOptions', function(done) { - var metadata = extend({}, METADATA, { - gaxOptions: {} - }); - - sink.logging.request = function(config) { - assert.strictEqual(config.reqOpts.sink.gaxOptions, undefined); - assert.strictEqual(config.gaxOpts, metadata.gaxOptions); - done(); - }; - - sink.setMetadata(metadata, assert.ifError); - }); - - it('should update metadata', function(done) { - var metadata = {}; - - sink.logging.request = function(config, callback) { - callback(null, metadata); - }; - - sink.setMetadata(metadata, function() { - assert.strictEqual(sink.metadata, metadata); - done(); - }); - }); - - it('should execute callback with original arguments', function(done) { - var args = [{}, {}, {}]; - - sink.logging.request = function(config, callback) { - callback.apply(null, args); - }; - - sink.setMetadata(METADATA, function() { - assert.deepStrictEqual([].slice.call(arguments), args); - done(); - }); - }); - }); -}); diff --git a/packages/monitoring/README.md b/packages/monitoring/README.md deleted file mode 100644 index 97d1438bd9a..00000000000 --- a/packages/monitoring/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# Node.js Clients for Stackdriver Monitoring API ([Beta](https://github.com/GoogleCloudPlatform/google-cloud-node#versioning)) - -[Stackdriver Monitoring API][Product Documentation]: Manages your Stackdriver Monitoring data and configurations. Most projects must be associated with a Stackdriver account, with a few exceptions as noted on the individual method pages. - -- [Client Library Documentation][] -- [Product Documentation][] - -## Quick Start -In order to use this library, you first need to go through the following steps: - -1. [Select or create a Cloud Platform project.](https://console.cloud.google.com/project) -2. [Enable the Stackdriver Monitoring API.](https://console.cloud.google.com/apis/api/monitoring) -3. [Setup Authentication.](https://googlecloudplatform.github.io/google-cloud-node/#/docs/google-cloud/master/guides/authentication) - -### Installation -``` -$ npm install --save @google-cloud/monitoring -``` - -### Preview -#### MetricServiceClient -```js - var monitoring = require('@google-cloud/monitoring'); - - var client = monitoring.metric({ - // optional auth parameters. - }); - - // Iterate over all elements. - var formattedName = client.projectPath(projectId); - - client.listMonitoredResourceDescriptors({name: formattedName}).then(function(responses) { - var resources = responses[0]; - for (var i = 0; i < resources.length; ++i) { - // doThingsWith(resources[i]) - } - }) - .catch(function(err) { - console.error(err); - }); - - // Or obtain the paged response. - var formattedName = client.projectPath(projectId); - - - var options = {autoPaginate: false}; - function callback(responses) { - // The actual resources in a response. - var resources = responses[0]; - // The next request if the response shows there's more responses. - var nextRequest = responses[1]; - // The actual response object, if necessary. - // var rawResponse = responses[2]; - for (var i = 0; i < resources.length; ++i) { - // doThingsWith(resources[i]); - } - if (nextRequest) { - // Fetch the next page. - return client.listMonitoredResourceDescriptors(nextRequest, options).then(callback); - } - } - client.listMonitoredResourceDescriptors({name: formattedName}, options) - .then(callback) - .catch(function(err) { - console.error(err); - }); -``` - -### Next Steps -- Read the [Client Library Documentation][] for Stackdriver Monitoring API to see other available methods on the client. -- Read the [Stackdriver Monitoring API Product documentation][Product Documentation] to learn more about the product and see How-to Guides. -- View this [repository's main README](https://github.com/GoogleCloudPlatform/google-cloud-node/blob/master/README.md) to see the full list of Cloud APIs that we cover. - -[Client Library Documentation]: https://googlecloudplatform.github.io/google-cloud-node/#/docs/monitoring -[Product Documentation]: https://cloud.google.com/monitoring \ No newline at end of file diff --git a/packages/monitoring/package.json b/packages/monitoring/package.json deleted file mode 100644 index e965ff1ac4e..00000000000 --- a/packages/monitoring/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "repository": "GoogleCloudPlatform/google-cloud-node", - "name": "@google-cloud/monitoring", - "version": "0.3.0", - "author": "Google Inc", - "description": "Stackdriver Monitoring API client for Node.js", - "main": "src/index.js", - "files": [ - "src", - "AUTHORS", - "LICENSE" - ], - "keywords": [ - "google apis client", - "google api client", - "google apis", - "google api", - "google", - "google cloud platform", - "google cloud", - "cloud", - "google monitoring", - "monitoring", - "Stackdriver Monitoring API" - ], - "dependencies": { - "extend": "^3.0", - "google-gax": "^0.13.2", - "google-proto-files": "^0.12.0" - }, - "devDependencies": { - "mocha": "^3.2.0" - }, - "scripts": { - "publish-module": "node ../../scripts/publish.js monitoring", - "smoke-test": "mocha smoke-test/*.js --timeout 5000", - "test": "mocha test/*.js" - }, - "license": "Apache-2.0", - "engines": { - "node": ">=4.0.0" - } -} diff --git a/packages/monitoring/smoke-test/metric_service_smoke_test.js b/packages/monitoring/smoke-test/metric_service_smoke_test.js deleted file mode 100644 index 546683030bc..00000000000 --- a/packages/monitoring/smoke-test/metric_service_smoke_test.js +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ -'use strict'; - -describe('MetricServiceSmokeTest', function() { - if (!process.env.SMOKE_TEST_PROJECT) { - throw new Error("Usage: SMOKE_TEST_PROJECT= node #{$0}"); - } - var projectId = process.env.SMOKE_TEST_PROJECT; - - it('successfully makes a call to the service using promises', function(done) { - var monitoring = require('../src'); - - var client = monitoring.v3.metric({ - // optional auth parameters. - }); - - // Iterate over all elements. - var formattedName = client.projectPath(projectId); - - client.listMonitoredResourceDescriptors({name: formattedName}).then(function(responses) { - var resources = responses[0]; - for (var i = 0; i < resources.length; ++i) { - console.log(resources[i]); - } - }) - .then(done) - .catch(done); - }); - - it('successfully makes a call to the service using callbacks', function(done) { - var monitoring = require('../src'); - - var client = monitoring.v3.metric({ - // optional auth parameters. - }); - - // Or obtain the paged response. - var formattedName = client.projectPath(projectId); - - - var options = {autoPaginate: false}; - function callback(responses) { - // The actual resources in a response. - var resources = responses[0]; - // The next request if the response shows there's more responses. - var nextRequest = responses[1]; - // The actual response object, if necessary. - // var rawResponse = responses[2]; - for (var i = 0; i < resources.length; ++i) { - console.log(resources[i]) - } - if (nextRequest) { - // Fetch the next page. - return client.listMonitoredResourceDescriptors(nextRequest, options).then(callback); - } - } - client.listMonitoredResourceDescriptors({name: formattedName}, options) - .then(callback) - .then(done) - .catch(done); - }); - - it('successfully makes a call to the service using streaming', function(done) { - var monitoring = require('../src'); - - var client = monitoring.v3.metric({ - // optional auth parameters. - }); - - var formattedName = client.projectPath(projectId); - client.listMonitoredResourceDescriptorsStream({name: formattedName}) - .on('data', function(element) { - console.log(element); - }) - .on('error', done) - .on('end', done); - }); -}); \ No newline at end of file diff --git a/packages/monitoring/src/index.js b/packages/monitoring/src/index.js deleted file mode 100644 index b8978b9457b..00000000000 --- a/packages/monitoring/src/index.js +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/*! - * @module monitoring - * @name Monitoring - */ - -'use strict'; - -var extend = require('extend'); -var gapic = { - v3: require('./v3') -}; -var gaxGrpc = require('google-gax').grpc(); - -const VERSION = require('../package.json').version; - -/** - * Create a groupServiceClient with additional helpers for common - * tasks. - * - * The Group API lets you inspect and manage your - * [groups](https://cloud.google.comgoogle.monitoring.v3.Group). - * - * A group is a named filter that is used to identify - * a collection of monitored resources. Groups are typically used to - * mirror the physical and/or logical topology of the environment. - * Because group membership is computed dynamically, monitored - * resources that are started in the future are automatically placed - * in matching groups. By using a group to name monitored resources in, - * for example, an alert policy, the target of that alert policy is - * updated automatically as monitored resources are added and removed - * from the infrastructure. - * - * @param {object=} options - [Configuration object](#/docs). - * @param {number=} options.port - The port on which to connect to - * the remote host. - * @param {string=} options.servicePath - The domain name of the - * API remote host. - */ -function groupV3(options) { - // Define the header options. - options = extend({}, options, { - libName: 'gccl', - libVersion: VERSION - }); - - // Create the client with the provided options. - var client = gapic.v3(options).groupServiceClient(options); - return client; -} - -/** - * Create a metricServiceClient with additional helpers for common - * tasks. - * - * Manages metric descriptors, monitored resource descriptors, and - * time series data. - * - * @param {object=} options - [Configuration object](#/docs). - * @param {number=} options.port - The port on which to connect to - * the remote host. - * @param {string=} options.servicePath - The domain name of the - * API remote host. - */ -function metricV3(options) { - // Define the header options. - options = extend({}, options, { - libName: 'gccl', - libVersion: VERSION - }); - - // Create the client with the provided options. - var client = gapic.v3(options).metricServiceClient(options); - return client; -} - -var v3Protos = {}; - -extend(v3Protos, gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/monitoring/v3/group_service.proto' -}]).google.monitoring.v3); - -extend(v3Protos, gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/monitoring/v3/metric_service.proto' -}]).google.monitoring.v3); - -module.exports.group = groupV3; -module.exports.metric = metricV3; -module.exports.types = v3Protos; - -module.exports.v3 = {}; -module.exports.v3.group = groupV3; -module.exports.v3.metric = metricV3; -module.exports.v3.types = v3Protos; \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_common.js b/packages/monitoring/src/v3/doc/doc_common.js deleted file mode 100644 index aa8010c30a3..00000000000 --- a/packages/monitoring/src/v3/doc/doc_common.js +++ /dev/null @@ -1,415 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A single strongly-typed value. - * - * @property {boolean} boolValue - * A Boolean value: `true` or `false`. - * - * @property {number} int64Value - * A 64-bit integer. Its range is approximately ±9.2x1018. - * - * @property {number} doubleValue - * A 64-bit double-precision floating-point number. Its magnitude - * is approximately ±10±300 and it has 16 - * significant digits of precision. - * - * @property {string} stringValue - * A variable-length string value. - * - * @property {Object} distributionValue - * A distribution value. - * - * This object should have the same structure as [google.api.Distribution]{@link external:"google.api.Distribution"} - * - * @class - * @see [google.monitoring.v3.TypedValue definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/monitoring/v3/common.proto} - */ -var TypedValue = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * A time interval extending just after a start time through an end time. - * If the start time is the same as the end time, then the interval - * represents a single point in time. - * - * @property {Object} endTime - * Required. The end of the time interval. - * - * This object should have the same structure as [google.protobuf.Timestamp]{@link external:"google.protobuf.Timestamp"} - * - * @property {Object} startTime - * Optional. The beginning of the time interval. The default value - * for the start time is the end time. The start time must not be - * later than the end time. - * - * This object should have the same structure as [google.protobuf.Timestamp]{@link external:"google.protobuf.Timestamp"} - * - * @class - * @see [google.monitoring.v3.TimeInterval definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/monitoring/v3/common.proto} - */ -var TimeInterval = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * Describes how to combine multiple time series to provide different views of - * the data. Aggregation consists of an alignment step on individual time - * series (`per_series_aligner`) followed by an optional reduction of the data - * across different time series (`cross_series_reducer`). For more details, see - * [Aggregation](https://cloud.google.com/monitoring/api/learn_more#aggregation). - * - * @property {Object} alignmentPeriod - * The alignment period for per-{@link time series} - * alignment. If present, `alignmentPeriod` must be at least 60 - * seconds. After per-time series alignment, each time series will - * contain data points only on the period boundaries. If - * `perSeriesAligner` is not specified or equals `ALIGN_NONE`, then - * this field is ignored. If `perSeriesAligner` is specified and - * does not equal `ALIGN_NONE`, then this field must be defined; - * otherwise an error is returned. - * - * This object should have the same structure as [google.protobuf.Duration]{@link external:"google.protobuf.Duration"} - * - * @property {number} perSeriesAligner - * The approach to be used to align individual time series. Not all - * alignment functions may be applied to all time series, depending - * on the metric type and value type of the original time - * series. Alignment may change the metric type or the value type of - * the time series. - * - * Time series data must be aligned in order to perform cross-time - * series reduction. If `crossSeriesReducer` is specified, then - * `perSeriesAligner` must be specified and not equal `ALIGN_NONE` - * and `alignmentPeriod` must be specified; otherwise, an error is - * returned. - * - * The number should be among the values of [Aligner]{@link Aligner} - * - * @property {number} crossSeriesReducer - * The approach to be used to combine time series. Not all reducer - * functions may be applied to all time series, depending on the - * metric type and the value type of the original time - * series. Reduction may change the metric type of value type of the - * time series. - * - * Time series data must be aligned in order to perform cross-time - * series reduction. If `crossSeriesReducer` is specified, then - * `perSeriesAligner` must be specified and not equal `ALIGN_NONE` - * and `alignmentPeriod` must be specified; otherwise, an error is - * returned. - * - * The number should be among the values of [Reducer]{@link Reducer} - * - * @property {string[]} groupByFields - * The set of fields to preserve when `crossSeriesReducer` is - * specified. The `groupByFields` determine how the time series are - * partitioned into subsets prior to applying the aggregation - * function. Each subset contains time series that have the same - * value for each of the grouping fields. Each individual time - * series is a member of exactly one subset. The - * `crossSeriesReducer` is applied to each subset of time series. - * It is not possible to reduce across different resource types, so - * this field implicitly contains `resource.type`. Fields not - * specified in `groupByFields` are aggregated away. If - * `groupByFields` is not specified and all the time series have - * the same resource type, then the time series are aggregated into - * a single output time series. If `crossSeriesReducer` is not - * defined, this field is ignored. - * - * @class - * @see [google.monitoring.v3.Aggregation definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/monitoring/v3/common.proto} - */ -var Aggregation = { - // This is for documentation. Actual contents will be loaded by gRPC. - - /** - * The Aligner describes how to bring the data points in a single - * time series into temporal alignment. - * - * @enum {number} - */ - Aligner: { - - /** - * No alignment. Raw data is returned. Not valid if cross-time - * series reduction is requested. The value type of the result is - * the same as the value type of the input. - */ - ALIGN_NONE: 0, - - /** - * Align and convert to delta metric type. This alignment is valid - * for cumulative metrics and delta metrics. Aligning an existing - * delta metric to a delta metric requires that the alignment - * period be increased. The value type of the result is the same - * as the value type of the input. - */ - ALIGN_DELTA: 1, - - /** - * Align and convert to a rate. This alignment is valid for - * cumulative metrics and delta metrics with numeric values. The output is a - * gauge metric with value type - * {@link DOUBLE}. - */ - ALIGN_RATE: 2, - - /** - * Align by interpolating between adjacent points around the - * period boundary. This alignment is valid for gauge - * metrics with numeric values. The value type of the result is the same - * as the value type of the input. - */ - ALIGN_INTERPOLATE: 3, - - /** - * Align by shifting the oldest data point before the period - * boundary to the boundary. This alignment is valid for gauge - * metrics. The value type of the result is the same as the - * value type of the input. - */ - ALIGN_NEXT_OLDER: 4, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the minimum of all data points in the - * period. This alignment is valid for gauge and delta metrics with numeric - * values. The value type of the result is the same as the value - * type of the input. - */ - ALIGN_MIN: 10, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the maximum of all data points in the - * period. This alignment is valid for gauge and delta metrics with numeric - * values. The value type of the result is the same as the value - * type of the input. - */ - ALIGN_MAX: 11, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the average or arithmetic mean of all - * data points in the period. This alignment is valid for gauge and delta - * metrics with numeric values. The value type of the output is - * {@link DOUBLE}. - */ - ALIGN_MEAN: 12, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the count of all data points in the - * period. This alignment is valid for gauge and delta metrics with numeric - * or Boolean values. The value type of the output is - * {@link INT64}. - */ - ALIGN_COUNT: 13, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the sum of all data points in the - * period. This alignment is valid for gauge and delta metrics with numeric - * and distribution values. The value type of the output is the - * same as the value type of the input. - */ - ALIGN_SUM: 14, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the standard deviation of all data - * points in the period. This alignment is valid for gauge and delta metrics - * with numeric values. The value type of the output is - * {@link DOUBLE}. - */ - ALIGN_STDDEV: 15, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the count of True-valued data points in the - * period. This alignment is valid for gauge metrics with - * Boolean values. The value type of the output is - * {@link INT64}. - */ - ALIGN_COUNT_TRUE: 16, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the fraction of True-valued data points in the - * period. This alignment is valid for gauge metrics with Boolean values. - * The output value is in the range [0, 1] and has value type - * {@link DOUBLE}. - */ - ALIGN_FRACTION_TRUE: 17, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the 99th percentile of all data - * points in the period. This alignment is valid for gauge and delta metrics - * with distribution values. The output is a gauge metric with value type - * {@link DOUBLE}. - */ - ALIGN_PERCENTILE_99: 18, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the 95th percentile of all data - * points in the period. This alignment is valid for gauge and delta metrics - * with distribution values. The output is a gauge metric with value type - * {@link DOUBLE}. - */ - ALIGN_PERCENTILE_95: 19, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the 50th percentile of all data - * points in the period. This alignment is valid for gauge and delta metrics - * with distribution values. The output is a gauge metric with value type - * {@link DOUBLE}. - */ - ALIGN_PERCENTILE_50: 20, - - /** - * Align time series via aggregation. The resulting data point in - * the alignment period is the 5th percentile of all data - * points in the period. This alignment is valid for gauge and delta metrics - * with distribution values. The output is a gauge metric with value type - * {@link DOUBLE}. - */ - ALIGN_PERCENTILE_05: 21 - }, - - /** - * A Reducer describes how to aggregate data points from multiple - * time series into a single time series. - * - * @enum {number} - */ - Reducer: { - - /** - * No cross-time series reduction. The output of the aligner is - * returned. - */ - REDUCE_NONE: 0, - - /** - * Reduce by computing the mean across time series for each - * alignment period. This reducer is valid for delta and - * gauge metrics with numeric or distribution values. The value type of the - * output is {@link DOUBLE}. - */ - REDUCE_MEAN: 1, - - /** - * Reduce by computing the minimum across time series for each - * alignment period. This reducer is valid for delta and - * gauge metrics with numeric values. The value type of the output - * is the same as the value type of the input. - */ - REDUCE_MIN: 2, - - /** - * Reduce by computing the maximum across time series for each - * alignment period. This reducer is valid for delta and - * gauge metrics with numeric values. The value type of the output - * is the same as the value type of the input. - */ - REDUCE_MAX: 3, - - /** - * Reduce by computing the sum across time series for each - * alignment period. This reducer is valid for delta and - * gauge metrics with numeric and distribution values. The value type of - * the output is the same as the value type of the input. - */ - REDUCE_SUM: 4, - - /** - * Reduce by computing the standard deviation across time series - * for each alignment period. This reducer is valid for delta - * and gauge metrics with numeric or distribution values. The value type of - * the output is {@link DOUBLE}. - */ - REDUCE_STDDEV: 5, - - /** - * Reduce by computing the count of data points across time series - * for each alignment period. This reducer is valid for delta - * and gauge metrics of numeric, Boolean, distribution, and string value - * type. The value type of the output is - * {@link INT64}. - */ - REDUCE_COUNT: 6, - - /** - * Reduce by computing the count of True-valued data points across time - * series for each alignment period. This reducer is valid for delta - * and gauge metrics of Boolean value type. The value type of - * the output is {@link INT64}. - */ - REDUCE_COUNT_TRUE: 7, - - /** - * Reduce by computing the fraction of True-valued data points across time - * series for each alignment period. This reducer is valid for delta - * and gauge metrics of Boolean value type. The output value is in the - * range [0, 1] and has value type - * {@link DOUBLE}. - */ - REDUCE_FRACTION_TRUE: 8, - - /** - * Reduce by computing 99th percentile of data points across time series - * for each alignment period. This reducer is valid for gauge and delta - * metrics of numeric and distribution type. The value of the output is - * {@link DOUBLE} - */ - REDUCE_PERCENTILE_99: 9, - - /** - * Reduce by computing 95th percentile of data points across time series - * for each alignment period. This reducer is valid for gauge and delta - * metrics of numeric and distribution type. The value of the output is - * {@link DOUBLE} - */ - REDUCE_PERCENTILE_95: 10, - - /** - * Reduce by computing 50th percentile of data points across time series - * for each alignment period. This reducer is valid for gauge and delta - * metrics of numeric and distribution type. The value of the output is - * {@link DOUBLE} - */ - REDUCE_PERCENTILE_50: 11, - - /** - * Reduce by computing 5th percentile of data points across time series - * for each alignment period. This reducer is valid for gauge and delta - * metrics of numeric and distribution type. The value of the output is - * {@link DOUBLE} - */ - REDUCE_PERCENTILE_05: 12 - } -}; \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_google_api_distribution.js b/packages/monitoring/src/v3/doc/doc_google_api_distribution.js deleted file mode 100644 index b2e14518ae4..00000000000 --- a/packages/monitoring/src/v3/doc/doc_google_api_distribution.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * Distribution contains summary statistics for a population of values and, - * optionally, a histogram representing the distribution of those values across - * a specified set of histogram buckets. - * - * The summary statistics are the count, mean, sum of the squared deviation from - * the mean, the minimum, and the maximum of the set of population of values. - * - * The histogram is based on a sequence of buckets and gives a count of values - * that fall into each bucket. The boundaries of the buckets are given either - * explicitly or by specifying parameters for a method of computing them - * (buckets of fixed width or buckets of exponentially increasing width). - * - * Although it is not forbidden, it is generally a bad idea to include - * non-finite values (infinities or NaNs) in the population of values, as this - * will render the `mean` and `sum_of_squared_deviation` fields meaningless. - * - * @external "google.api.Distribution" - * @property {number} count - * The number of values in the population. Must be non-negative. - * - * @property {number} mean - * The arithmetic mean of the values in the population. If `count` is zero - * then this field must be zero. - * - * @property {number} sumOfSquaredDeviation - * The sum of squared deviations from the mean of the values in the - * population. For values x_i this is: - * - * Sum[i=1..n](https://cloud.google.com(x_i - mean)^2) - * - * Knuth, "The Art of Computer Programming", Vol. 2, page 323, 3rd edition - * describes Welford's method for accumulating this sum in one pass. - * - * If `count` is zero then this field must be zero. - * - * @property {Object} range - * If specified, contains the range of the population values. The field - * must not be present if the `count` is zero. - * - * This object should have the same structure as [google.api.Distribution.Range]{@link external:"google.api.Distribution.Range"} - * - * @property {Object} bucketOptions - * Defines the histogram bucket boundaries. - * - * This object should have the same structure as [google.api.Distribution.BucketOptions]{@link external:"google.api.Distribution.BucketOptions"} - * - * @property {number[]} bucketCounts - * If `bucket_options` is given, then the sum of the values in `bucket_counts` - * must equal the value in `count`. If `bucket_options` is not given, no - * `bucket_counts` fields may be given. - * - * Bucket counts are given in order under the numbering scheme described - * above (the underflow bucket has number 0; the finite buckets, if any, - * have numbers 1 through N-2; the overflow bucket has number N-1). - * - * The size of `bucket_counts` must be no greater than N as defined in - * `bucket_options`. - * - * Any suffix of trailing zero bucket_count fields may be omitted. - * - * @see [google.api.Distribution definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/distribution.proto} - */ \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_google_api_label.js b/packages/monitoring/src/v3/doc/doc_google_api_label.js deleted file mode 100644 index 64701d613ac..00000000000 --- a/packages/monitoring/src/v3/doc/doc_google_api_label.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A description of a label. - * - * @external "google.api.LabelDescriptor" - * @property {string} key - * The label key. - * - * @property {number} valueType - * The type of data that can be assigned to the label. - * - * The number should be among the values of [google.api.LabelDescriptor.ValueType]{@link external:"google.api.LabelDescriptor.ValueType"} - * - * @property {string} description - * A human-readable description for the label. - * - * @see [google.api.LabelDescriptor definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/label.proto} - */ \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_google_api_metric.js b/packages/monitoring/src/v3/doc/doc_google_api_metric.js deleted file mode 100644 index ea7d0f941eb..00000000000 --- a/packages/monitoring/src/v3/doc/doc_google_api_metric.js +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * Defines a metric type and its schema. Once a metric descriptor is created, - * deleting or altering it stops data collection and makes the metric type's - * existing data unusable. - * - * @external "google.api.MetricDescriptor" - * @property {string} name - * The resource name of the metric descriptor. Depending on the - * implementation, the name typically includes: (1) the parent resource name - * that defines the scope of the metric type or of its data; and (2) the - * metric's URL-encoded type, which also appears in the `type` field of this - * descriptor. For example, following is the resource name of a custom - * metric within the GCP project `my-project-id`: - * - * "projects/my-project-id/metricDescriptors/custom.googleapis.com%2Finvoice%2Fpaid%2Famount" - * - * @property {string} type - * The metric type, including its DNS name prefix. The type is not - * URL-encoded. All user-defined custom metric types have the DNS name - * `custom.googleapis.com`. Metric types should use a natural hierarchical - * grouping. For example: - * - * "custom.googleapis.com/invoice/paid/amount" - * "appengine.googleapis.com/http/server/response_latencies" - * - * @property {Object[]} labels - * The set of labels that can be used to describe a specific - * instance of this metric type. For example, the - * `appengine.googleapis.com/http/server/response_latencies` metric - * type has a label for the HTTP response code, `response_code`, so - * you can look at latencies for successful responses or just - * for responses that failed. - * - * This object should have the same structure as [google.api.LabelDescriptor]{@link external:"google.api.LabelDescriptor"} - * - * @property {number} metricKind - * Whether the metric records instantaneous values, changes to a value, etc. - * Some combinations of `metric_kind` and `value_type` might not be supported. - * - * The number should be among the values of [google.api.MetricDescriptor.MetricKind]{@link external:"google.api.MetricDescriptor.MetricKind"} - * - * @property {number} valueType - * Whether the measurement is an integer, a floating-point number, etc. - * Some combinations of `metric_kind` and `value_type` might not be supported. - * - * The number should be among the values of [google.api.MetricDescriptor.ValueType]{@link external:"google.api.MetricDescriptor.ValueType"} - * - * @property {string} unit - * The unit in which the metric value is reported. It is only applicable - * if the `value_type` is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The - * supported units are a subset of [The Unified Code for Units of - * Measure](http://unitsofmeasure.org/ucum.html) standard: - * - * **Basic units (UNIT)** - * - * * `bit` bit - * * `By` byte - * * `s` second - * * `min` minute - * * `h` hour - * * `d` day - * - * **Prefixes (PREFIX)** - * - * * `k` kilo (10**3) - * * `M` mega (10**6) - * * `G` giga (10**9) - * * `T` tera (10**12) - * * `P` peta (10**15) - * * `E` exa (10**18) - * * `Z` zetta (10**21) - * * `Y` yotta (10**24) - * * `m` milli (10**-3) - * * `u` micro (10**-6) - * * `n` nano (10**-9) - * * `p` pico (10**-12) - * * `f` femto (10**-15) - * * `a` atto (10**-18) - * * `z` zepto (10**-21) - * * `y` yocto (10**-24) - * * `Ki` kibi (2**10) - * * `Mi` mebi (2**20) - * * `Gi` gibi (2**30) - * * `Ti` tebi (2**40) - * - * **Grammar** - * - * The grammar includes the dimensionless unit `1`, such as `1/s`. - * - * The grammar also includes these connectors: - * - * * `/` division (as an infix operator, e.g. `1/s`). - * * `.` multiplication (as an infix operator, e.g. `GBy.d`) - * - * The grammar for a unit is as follows: - * - * Expression = Component { "." Component } { "/" Component } ; - * - * Component = [ PREFIX ] UNIT [ Annotation ] - * | Annotation - * | "1" - * ; - * - * Annotation = "{" NAME "}" ; - * - * Notes: - * - * * `Annotation` is just a comment if it follows a `UNIT` and is - * equivalent to `1` if it is used alone. For examples, - * `{requests}/s == 1/s`, `By{transmitted}/s == By/s`. - * * `NAME` is a sequence of non-blank printable ASCII characters not - * containing '{' or '}'. - * - * @property {string} description - * A detailed description of the metric, which can be used in documentation. - * - * @property {string} displayName - * A concise name for the metric, which can be displayed in user interfaces. - * Use sentence case without an ending period, for example "Request count". - * - * @see [google.api.MetricDescriptor definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/metric.proto} - */ - -/** - * A specific metric, identified by specifying values for all of the - * labels of a {@link `MetricDescriptor`}. - * - * @external "google.api.Metric" - * @property {string} type - * An existing metric type, see {@link google.api.MetricDescriptor}. - * For example, `custom.googleapis.com/invoice/paid/amount`. - * - * @property {Object.} labels - * The set of label values that uniquely identify this metric. All - * labels listed in the `MetricDescriptor` must be assigned values. - * - * @see [google.api.Metric definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/metric.proto} - */ \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_google_api_monitored_resource.js b/packages/monitoring/src/v3/doc/doc_google_api_monitored_resource.js deleted file mode 100644 index bb2c3107f8f..00000000000 --- a/packages/monitoring/src/v3/doc/doc_google_api_monitored_resource.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * An object that describes the schema of a {@link MonitoredResource} object using a - * type name and a set of labels. For example, the monitored resource - * descriptor for Google Compute Engine VM instances has a type of - * `"gce_instance"` and specifies the use of the labels `"instance_id"` and - * `"zone"` to identify particular VM instances. - * - * Different APIs can support different monitored resource types. APIs generally - * provide a `list` method that returns the monitored resource descriptors used - * by the API. - * - * @external "google.api.MonitoredResourceDescriptor" - * @property {string} name - * Optional. The resource name of the monitored resource descriptor: - * `"projects/{project_id}/monitoredResourceDescriptors/{type}"` where - * {type} is the value of the `type` field in this object and - * {project_id} is a project ID that provides API-specific context for - * accessing the type. APIs that do not use project information can use the - * resource name format `"monitoredResourceDescriptors/{type}"`. - * - * @property {string} type - * Required. The monitored resource type. For example, the type - * `"cloudsql_database"` represents databases in Google Cloud SQL. - * The maximum length of this value is 256 characters. - * - * @property {string} displayName - * Optional. A concise name for the monitored resource type that might be - * displayed in user interfaces. It should be a Title Cased Noun Phrase, - * without any article or other determiners. For example, - * `"Google Cloud SQL Database"`. - * - * @property {string} description - * Optional. A detailed description of the monitored resource type that might - * be used in documentation. - * - * @property {Object[]} labels - * Required. A set of labels used to describe instances of this monitored - * resource type. For example, an individual Google Cloud SQL database is - * identified by values for the labels `"database_id"` and `"zone"`. - * - * This object should have the same structure as [google.api.LabelDescriptor]{@link external:"google.api.LabelDescriptor"} - * - * @see [google.api.MonitoredResourceDescriptor definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/monitored_resource.proto} - */ - -/** - * An object representing a resource that can be used for monitoring, logging, - * billing, or other purposes. Examples include virtual machine instances, - * databases, and storage devices such as disks. The `type` field identifies a - * {@link MonitoredResourceDescriptor} object that describes the resource's - * schema. Information in the `labels` field identifies the actual resource and - * its attributes according to the schema. For example, a particular Compute - * Engine VM instance could be represented by the following object, because the - * {@link MonitoredResourceDescriptor} for `"gce_instance"` has labels - * `"instance_id"` and `"zone"`: - * - * { "type": "gce_instance", - * "labels": { "instance_id": "12345678901234", - * "zone": "us-central1-a" }} - * - * @external "google.api.MonitoredResource" - * @property {string} type - * Required. The monitored resource type. This field must match - * the `type` field of a {@link MonitoredResourceDescriptor} object. For - * example, the type of a Cloud SQL database is `"cloudsql_database"`. - * - * @property {Object.} labels - * Required. Values for all of the labels listed in the associated monitored - * resource descriptor. For example, Cloud SQL databases use the labels - * `"database_id"` and `"zone"`. - * - * @see [google.api.MonitoredResource definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/api/monitored_resource.proto} - */ \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_google_protobuf_duration.js b/packages/monitoring/src/v3/doc/doc_google_protobuf_duration.js deleted file mode 100644 index b81fd71f130..00000000000 --- a/packages/monitoring/src/v3/doc/doc_google_protobuf_duration.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A Duration represents a signed, fixed-length span of time represented - * as a count of seconds and fractions of seconds at nanosecond - * resolution. It is independent of any calendar and concepts like "day" - * or "month". It is related to Timestamp in that the difference between - * two Timestamp values is a Duration and it can be added or subtracted - * from a Timestamp. Range is approximately +-10,000 years. - * - * Example 1: Compute Duration from two Timestamps in pseudo code. - * - * Timestamp start = ...; - * Timestamp end = ...; - * Duration duration = ...; - * - * duration.seconds = end.seconds - start.seconds; - * duration.nanos = end.nanos - start.nanos; - * - * if (duration.seconds < 0 && duration.nanos > 0) { - * duration.seconds += 1; - * duration.nanos -= 1000000000; - * } else if (durations.seconds > 0 && duration.nanos < 0) { - * duration.seconds -= 1; - * duration.nanos += 1000000000; - * } - * - * Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. - * - * Timestamp start = ...; - * Duration duration = ...; - * Timestamp end = ...; - * - * end.seconds = start.seconds + duration.seconds; - * end.nanos = start.nanos + duration.nanos; - * - * if (end.nanos < 0) { - * end.seconds -= 1; - * end.nanos += 1000000000; - * } else if (end.nanos >= 1000000000) { - * end.seconds += 1; - * end.nanos -= 1000000000; - * } - * - * Example 3: Compute Duration from datetime.timedelta in Python. - * - * td = datetime.timedelta(days=3, minutes=10) - * duration = Duration() - * duration.FromTimedelta(td) - * - * @external "google.protobuf.Duration" - * @property {number} seconds - * Signed seconds of the span of time. Must be from -315,576,000,000 - * to +315,576,000,000 inclusive. - * - * @property {number} nanos - * Signed fractions of a second at nanosecond resolution of the span - * of time. Durations less than one second are represented with a 0 - * `seconds` field and a positive or negative `nanos` field. For durations - * of one second or more, a non-zero value for the `nanos` field must be - * of the same sign as the `seconds` field. Must be from -999,999,999 - * to +999,999,999 inclusive. - * - * @see [google.protobuf.Duration definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/duration.proto} - */ \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_google_protobuf_timestamp.js b/packages/monitoring/src/v3/doc/doc_google_protobuf_timestamp.js deleted file mode 100644 index ed8fc627b92..00000000000 --- a/packages/monitoring/src/v3/doc/doc_google_protobuf_timestamp.js +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A Timestamp represents a point in time independent of any time zone - * or calendar, represented as seconds and fractions of seconds at - * nanosecond resolution in UTC Epoch time. It is encoded using the - * Proleptic Gregorian Calendar which extends the Gregorian calendar - * backwards to year one. It is encoded assuming all minutes are 60 - * seconds long, i.e. leap seconds are "smeared" so that no leap second - * table is needed for interpretation. Range is from - * 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. - * By restricting to that range, we ensure that we can convert to - * and from RFC 3339 date strings. - * See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt). - * - * Example 1: Compute Timestamp from POSIX `time()`. - * - * Timestamp timestamp; - * timestamp.set_seconds(time(NULL)); - * timestamp.set_nanos(0); - * - * Example 2: Compute Timestamp from POSIX `gettimeofday()`. - * - * struct timeval tv; - * gettimeofday(&tv, NULL); - * - * Timestamp timestamp; - * timestamp.set_seconds(tv.tv_sec); - * timestamp.set_nanos(tv.tv_usec * 1000); - * - * Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. - * - * FILETIME ft; - * GetSystemTimeAsFileTime(&ft); - * UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; - * - * // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z - * // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. - * Timestamp timestamp; - * timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); - * timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); - * - * Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. - * - * long millis = System.currentTimeMillis(); - * - * Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) - * .setNanos((int) ((millis % 1000) * 1000000)).build(); - * - * - * Example 5: Compute Timestamp from current time in Python. - * - * timestamp = Timestamp() - * timestamp.GetCurrentTime() - * - * @external "google.protobuf.Timestamp" - * @property {number} seconds - * Represents seconds of UTC time since Unix epoch - * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - * 9999-12-31T23:59:59Z inclusive. - * - * @property {number} nanos - * Non-negative fractions of a second at nanosecond resolution. Negative - * second values with fractions must still have non-negative nanos values - * that count forward in time. Must be from 0 to 999,999,999 - * inclusive. - * - * @see [google.protobuf.Timestamp definition in proto format]{@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto} - */ \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_group.js b/packages/monitoring/src/v3/doc/doc_group.js deleted file mode 100644 index 2d03ff78472..00000000000 --- a/packages/monitoring/src/v3/doc/doc_group.js +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * The description of a dynamic collection of monitored resources. Each group - * has a filter that is matched against monitored resources and their associated - * metadata. If a group's filter matches an available monitored resource, then - * that resource is a member of that group. Groups can contain any number of - * monitored resources, and each monitored resource can be a member of any - * number of groups. - * - * Groups can be nested in parent-child hierarchies. The `parentName` field - * identifies an optional parent for each group. If a group has a parent, then - * the only monitored resources available to be matched by the group's filter - * are the resources contained in the parent group. In other words, a group - * contains the monitored resources that match its filter and the filters of all - * the group's ancestors. A group without a parent can contain any monitored - * resource. - * - * For example, consider an infrastructure running a set of instances with two - * user-defined tags: `"environment"` and `"role"`. A parent group has a filter, - * `environment="production"`. A child of that parent group has a filter, - * `role="transcoder"`. The parent group contains all instances in the - * production environment, regardless of their roles. The child group contains - * instances that have the transcoder role *and* are in the production - * environment. - * - * The monitored resources contained in a group can change at any moment, - * depending on what resources exist and what filters are associated with the - * group and its ancestors. - * - * @property {string} name - * Output only. The name of this group. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * When creating a group, this field is ignored and a new name is created - * consisting of the project specified in the call to `CreateGroup` - * and a unique `{group_id}` that is generated automatically. - * - * @property {string} displayName - * A user-assigned name for this group, used only for display purposes. - * - * @property {string} parentName - * The name of the group's parent, if it has one. - * The format is `"projects/{project_id_or_number}/groups/{group_id}"`. - * For groups with no parent, `parentName` is the empty string, `""`. - * - * @property {string} filter - * The filter used to determine which monitored resources belong to this group. - * - * @property {boolean} isCluster - * If true, the members of this group are considered to be a cluster. - * The system can perform additional analysis on groups that are clusters. - * - * @class - * @see [google.monitoring.v3.Group definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/monitoring/v3/group.proto} - */ -var Group = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/packages/monitoring/src/v3/doc/doc_metric.js b/packages/monitoring/src/v3/doc/doc_metric.js deleted file mode 100644 index 0f4a2ef51e0..00000000000 --- a/packages/monitoring/src/v3/doc/doc_metric.js +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ - -/* - * Note: this file is purely for documentation. Any contents are not expected - * to be loaded as the JS file. - */ - -/** - * A single data point in a time series. - * - * @property {Object} interval - * The time interval to which the data point applies. For GAUGE metrics, only - * the end time of the interval is used. For DELTA metrics, the start and end - * time should specify a non-zero interval, with subsequent points specifying - * contiguous and non-overlapping intervals. For CUMULATIVE metrics, the - * start and end time should specify a non-zero interval, with subsequent - * points specifying the same start time and increasing end times, until an - * event resets the cumulative value to zero and sets a new start time for the - * following points. - * - * This object should have the same structure as [TimeInterval]{@link TimeInterval} - * - * @property {Object} value - * The value of the data point. - * - * This object should have the same structure as [TypedValue]{@link TypedValue} - * - * @class - * @see [google.monitoring.v3.Point definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/monitoring/v3/metric.proto} - */ -var Point = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; - -/** - * A collection of data points that describes the time-varying values - * of a metric. A time series is identified by a combination of a - * fully-specified monitored resource and a fully-specified metric. - * This type is used for both listing and creating time series. - * - * @property {Object} metric - * The associated metric. A fully-specified metric used to identify the time - * series. - * - * This object should have the same structure as [google.api.Metric]{@link external:"google.api.Metric"} - * - * @property {Object} resource - * The associated resource. A fully-specified monitored resource used to - * identify the time series. - * - * This object should have the same structure as [google.api.MonitoredResource]{@link external:"google.api.MonitoredResource"} - * - * @property {number} metricKind - * The metric kind of the time series. When listing time series, this metric - * kind might be different from the metric kind of the associated metric if - * this time series is an alignment or reduction of other time series. - * - * When creating a time series, this field is optional. If present, it must be - * the same as the metric kind of the associated metric. If the associated - * metric's descriptor must be auto-created, then this field specifies the - * metric kind of the new descriptor and must be either `GAUGE` (the default) - * or `CUMULATIVE`. - * - * The number should be among the values of [google.api.MetricDescriptor.MetricKind]{@link external:"google.api.MetricDescriptor.MetricKind"} - * - * @property {number} valueType - * The value type of the time series. When listing time series, this value - * type might be different from the value type of the associated metric if - * this time series is an alignment or reduction of other time series. - * - * When creating a time series, this field is optional. If present, it must be - * the same as the type of the data in the `points` field. - * - * The number should be among the values of [google.api.MetricDescriptor.ValueType]{@link external:"google.api.MetricDescriptor.ValueType"} - * - * @property {Object[]} points - * The data points of this time series. When listing time series, the order of - * the points is specified by the list method. - * - * When creating a time series, this field must contain exactly one point and - * the point's type must be the same as the value type of the associated - * metric. If the associated metric's descriptor must be auto-created, then - * the value type of the descriptor is determined by the point's type, which - * must be `BOOL`, `INT64`, `DOUBLE`, or `DISTRIBUTION`. - * - * This object should have the same structure as [Point]{@link Point} - * - * @class - * @see [google.monitoring.v3.TimeSeries definition in proto format]{@link https://github.com/googleapis/googleapis/blob/master/google/monitoring/v3/metric.proto} - */ -var TimeSeries = { - // This is for documentation. Actual contents will be loaded by gRPC. -}; \ No newline at end of file diff --git a/packages/monitoring/src/v3/group_service_client.js b/packages/monitoring/src/v3/group_service_client.js deleted file mode 100644 index 4f11033ae72..00000000000 --- a/packages/monitoring/src/v3/group_service_client.js +++ /dev/null @@ -1,799 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - * - * EDITING INSTRUCTIONS - * This file was generated from the file - * https://github.com/googleapis/googleapis/blob/master/google/monitoring/v3/group_service.proto, - * and updates to that file get reflected here through a refresh process. - * For the short term, the refresh process will only be runnable by Google - * engineers. - * - * The only allowed edits are to method and file documentation. A 3-way - * merge preserves those additions if the generated source changes. - */ -/* TODO: introduce line-wrapping so that it never exceeds the limit. */ -/* jscs: disable maximumLineLength */ -'use strict'; - -var configData = require('./group_service_client_config'); -var extend = require('extend'); -var gax = require('google-gax'); - -var SERVICE_ADDRESS = 'monitoring.googleapis.com'; - -var DEFAULT_SERVICE_PORT = 443; - -var CODE_GEN_NAME_VERSION = 'gapic/0.0.5'; - -var PAGE_DESCRIPTORS = { - listGroups: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'group'), - listGroupMembers: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'members') -}; - -/** - * The scopes needed to make gRPC calls to all of the methods defined in - * this service. - */ -var ALL_SCOPES = [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write' -]; - -/** - * The Group API lets you inspect and manage your - * [groups](https://cloud.google.comgoogle.monitoring.v3.Group). - * - * A group is a named filter that is used to identify - * a collection of monitored resources. Groups are typically used to - * mirror the physical and/or logical topology of the environment. - * Because group membership is computed dynamically, monitored - * resources that are started in the future are automatically placed - * in matching groups. By using a group to name monitored resources in, - * for example, an alert policy, the target of that alert policy is - * updated automatically as monitored resources are added and removed - * from the infrastructure. - * - * - * @class - */ -function GroupServiceClient(gaxGrpc, grpcClients, opts) { - opts = extend({ - servicePath: SERVICE_ADDRESS, - port: DEFAULT_SERVICE_PORT, - clientConfig: {} - }, opts); - - var googleApiClient = [ - 'gl-node/' + process.versions.node - ]; - if (opts.libName && opts.libVersion) { - googleApiClient.push(opts.libName + '/' + opts.libVersion); - } - googleApiClient.push( - CODE_GEN_NAME_VERSION, - 'gax/' + gax.version, - 'grpc/' + gaxGrpc.grpcVersion - ); - - var defaults = gaxGrpc.constructSettings( - 'google.monitoring.v3.GroupService', - configData, - opts.clientConfig, - {'x-goog-api-client': googleApiClient.join(' ')}); - - var self = this; - - this.auth = gaxGrpc.auth; - var groupServiceStub = gaxGrpc.createStub( - grpcClients.google.monitoring.v3.GroupService, - opts); - var groupServiceStubMethods = [ - 'listGroups', - 'getGroup', - 'createGroup', - 'updateGroup', - 'deleteGroup', - 'listGroupMembers' - ]; - groupServiceStubMethods.forEach(function(methodName) { - self['_' + methodName] = gax.createApiCall( - groupServiceStub.then(function(groupServiceStub) { - return function() { - var args = Array.prototype.slice.call(arguments, 0); - return groupServiceStub[methodName].apply(groupServiceStub, args); - }; - }), - defaults[methodName], - PAGE_DESCRIPTORS[methodName]); - }); -} - -// Path templates - -var PROJECT_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}'); - -var GROUP_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}/groups/{group}'); - -/** - * Returns a fully-qualified project resource name string. - * @param {String} project - * @returns {String} - */ -GroupServiceClient.prototype.projectPath = function(project) { - return PROJECT_PATH_TEMPLATE.render({ - project: project - }); -}; - -/** - * Returns a fully-qualified group resource name string. - * @param {String} project - * @param {String} group - * @returns {String} - */ -GroupServiceClient.prototype.groupPath = function(project, group) { - return GROUP_PATH_TEMPLATE.render({ - project: project, - group: group - }); -}; - -/** - * Parses the projectName from a project resource. - * @param {String} projectName - * A fully-qualified path representing a project resources. - * @returns {String} - A string representing the project. - */ -GroupServiceClient.prototype.matchProjectFromProjectName = function(projectName) { - return PROJECT_PATH_TEMPLATE.match(projectName).project; -}; - -/** - * Parses the groupName from a group resource. - * @param {String} groupName - * A fully-qualified path representing a group resources. - * @returns {String} - A string representing the project. - */ -GroupServiceClient.prototype.matchProjectFromGroupName = function(groupName) { - return GROUP_PATH_TEMPLATE.match(groupName).project; -}; - -/** - * Parses the groupName from a group resource. - * @param {String} groupName - * A fully-qualified path representing a group resources. - * @returns {String} - A string representing the group. - */ -GroupServiceClient.prototype.matchGroupFromGroupName = function(groupName) { - return GROUP_PATH_TEMPLATE.match(groupName).group; -}; - -/** - * Get the project ID used by this class. - * @param {function(Error, string)} callback - the callback to be called with - * the current project Id. - */ -GroupServiceClient.prototype.getProjectId = function(callback) { - return this.auth.getProjectId(callback); -}; - -// Service calls - -/** - * Lists the existing groups. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param {string=} request.childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @param {string=} request.ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @param {string=} request.descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [Group]{@link Group}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListGroupsResponse]{@link ListGroupsResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [Group]{@link Group}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [Group]{@link Group} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListGroupsResponse]{@link ListGroupsResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.group({ - * // optional auth parameters. - * }); - * - * // Iterate over all elements. - * var formattedName = client.projectPath("[PROJECT]"); - * - * client.listGroups({name: formattedName}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }) - * .catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var formattedName = client.projectPath("[PROJECT]"); - * - * - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listGroups(nextRequest, options).then(callback); - * } - * } - * client.listGroups({name: formattedName}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -GroupServiceClient.prototype.listGroups = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listGroups(request, options, callback); -}; - -/** - * Equivalent to {@link listGroups}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listGroups} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project whose groups are to be listed. The format is - * `"projects/{project_id_or_number}"`. - * @param {string=} request.childrenOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups whose `parentName` field contains the group - * name. If no groups have this parent, the results are empty. - * @param {string=} request.ancestorsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns groups that are ancestors of the specified group. - * The groups are returned in order, starting with the immediate parent and - * ending with the most distant ancestor. If the specified group has no - * immediate parent, the results are empty. - * @param {string=} request.descendantsOfGroup - * A group name: `"projects/{project_id_or_number}/groups/{group_id}"`. - * Returns the descendants of the specified group. This is a superset of - * the results returned by the `childrenOfGroup` filter, and includes - * children-of-children, and so forth. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [Group]{@link Group} on 'data' event. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.group({ - * // optional auth parameters. - * }); - * - * var formattedName = client.projectPath("[PROJECT]"); - * client.listGroupsStream({name: formattedName}) - * .on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.log(err); - * }); - */ -GroupServiceClient.prototype.listGroupsStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listGroups.createStream(this._listGroups, request, options); -}; - -/** - * Gets a single group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The group to retrieve. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [Group]{@link Group}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Group]{@link Group}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.group({ - * // optional auth parameters. - * }); - * - * var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - * client.getGroup({name: formattedName}).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(function(err) { - * console.error(err); - * }); - */ -GroupServiceClient.prototype.getGroup = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._getGroup(request, options, callback); -}; - -/** - * Creates a new group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project in which to create the group. The format is - * `"projects/{project_id_or_number}"`. - * @param {Object} request.group - * A group definition. It is an error to define the `name` field because - * the system assigns the name. - * - * This object should have the same structure as [Group]{@link Group} - * @param {boolean=} request.validateOnly - * If true, validate this request but do not create the group. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [Group]{@link Group}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Group]{@link Group}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.group({ - * // optional auth parameters. - * }); - * - * var formattedName = client.projectPath("[PROJECT]"); - * var group = {}; - * var request = { - * name: formattedName, - * group: group - * }; - * client.createGroup(request).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(function(err) { - * console.error(err); - * }); - */ -GroupServiceClient.prototype.createGroup = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._createGroup(request, options, callback); -}; - -/** - * Updates an existing group. - * You can change any group attributes except `name`. - * - * @param {Object} request - * The request object that will be sent. - * @param {Object} request.group - * The new definition of the group. All fields of the existing group, - * excepting `name`, are replaced with the corresponding fields of this group. - * - * This object should have the same structure as [Group]{@link Group} - * @param {boolean=} request.validateOnly - * If true, validate this request but do not update the existing group. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [Group]{@link Group}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [Group]{@link Group}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.group({ - * // optional auth parameters. - * }); - * - * var group = {}; - * client.updateGroup({group: group}).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(function(err) { - * console.error(err); - * }); - */ -GroupServiceClient.prototype.updateGroup = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._updateGroup(request, options, callback); -}; - -/** - * Deletes an existing group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The group to delete. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error)=} callback - * The function which will be called with the result of the API call. - * @return {Promise} - The promise which resolves when API call finishes. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.group({ - * // optional auth parameters. - * }); - * - * var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - * client.deleteGroup({name: formattedName}).catch(function(err) { - * console.error(err); - * }); - */ -GroupServiceClient.prototype.deleteGroup = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._deleteGroup(request, options, callback); -}; - -/** - * Lists the monitored resources that are members of a group. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {string=} request.filter - * An optional [list filter](https://cloud.google.com/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param {Object=} request.interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * - * This object should have the same structure as [TimeInterval]{@link TimeInterval} - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [google.api.MonitoredResource]{@link external:"google.api.MonitoredResource"}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListGroupMembersResponse]{@link ListGroupMembersResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [google.api.MonitoredResource]{@link external:"google.api.MonitoredResource"}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [google.api.MonitoredResource]{@link external:"google.api.MonitoredResource"} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListGroupMembersResponse]{@link ListGroupMembersResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.group({ - * // optional auth parameters. - * }); - * - * // Iterate over all elements. - * var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - * - * client.listGroupMembers({name: formattedName}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }) - * .catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - * - * - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listGroupMembers(nextRequest, options).then(callback); - * } - * } - * client.listGroupMembers({name: formattedName}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -GroupServiceClient.prototype.listGroupMembers = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listGroupMembers(request, options, callback); -}; - -/** - * Equivalent to {@link listGroupMembers}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listGroupMembers} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {string=} request.filter - * An optional [list filter](https://cloud.google.com/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param {Object=} request.interval - * An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. - * - * This object should have the same structure as [TimeInterval]{@link TimeInterval} - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [google.api.MonitoredResource]{@link external:"google.api.MonitoredResource"} on 'data' event. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.group({ - * // optional auth parameters. - * }); - * - * var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - * client.listGroupMembersStream({name: formattedName}) - * .on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.log(err); - * }); - */ -GroupServiceClient.prototype.listGroupMembersStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listGroupMembers.createStream(this._listGroupMembers, request, options); -}; - -function GroupServiceClientBuilder(gaxGrpc) { - if (!(this instanceof GroupServiceClientBuilder)) { - return new GroupServiceClientBuilder(gaxGrpc); - } - - var groupServiceClient = gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/monitoring/v3/group_service.proto' - }]); - extend(this, groupServiceClient.google.monitoring.v3); - - - /** - * Build a new instance of {@link GroupServiceClient}. - * - * @param {Object=} opts - The optional parameters. - * @param {String=} opts.servicePath - * The domain name of the API remote host. - * @param {number=} opts.port - * The port on which to connect to the remote host. - * @param {grpc.ClientCredentials=} opts.sslCreds - * A ClientCredentials for use with an SSL-enabled channel. - * @param {Object=} opts.clientConfig - * The customized config to build the call settings. See - * {@link gax.constructSettings} for the format. - */ - this.groupServiceClient = function(opts) { - return new GroupServiceClient(gaxGrpc, groupServiceClient, opts); - }; - extend(this.groupServiceClient, GroupServiceClient); -} -module.exports = GroupServiceClientBuilder; -module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS; -module.exports.ALL_SCOPES = ALL_SCOPES; \ No newline at end of file diff --git a/packages/monitoring/src/v3/group_service_client_config.json b/packages/monitoring/src/v3/group_service_client_config.json deleted file mode 100644 index a57878c2ece..00000000000 --- a/packages/monitoring/src/v3/group_service_client_config.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "interfaces": { - "google.monitoring.v3.GroupService": { - "retry_codes": { - "idempotent": [ - "DEADLINE_EXCEEDED", - "UNAVAILABLE" - ], - "non_idempotent": [] - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000 - } - }, - "methods": { - "ListGroups": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "GetGroup": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "CreateGroup": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "UpdateGroup": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "DeleteGroup": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ListGroupMembers": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - } - } - } - } -} diff --git a/packages/monitoring/src/v3/index.js b/packages/monitoring/src/v3/index.js deleted file mode 100644 index c639c388578..00000000000 --- a/packages/monitoring/src/v3/index.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ -'use strict'; - -var groupServiceClient = require('./group_service_client'); -var metricServiceClient = require('./metric_service_client'); -var gax = require('google-gax'); -var extend = require('extend'); - -function v3(options) { - options = extend({ - scopes: v3.ALL_SCOPES - }, options); - var gaxGrpc = gax.grpc(options); - var result = {}; - extend(result, groupServiceClient(gaxGrpc)); - extend(result, metricServiceClient(gaxGrpc)); - return result; -} - -v3.GAPIC_VERSION = '0.0.5'; -v3.SERVICE_ADDRESS = groupServiceClient.SERVICE_ADDRESS; -v3.ALL_SCOPES = groupServiceClient.ALL_SCOPES; - -module.exports = v3; \ No newline at end of file diff --git a/packages/monitoring/src/v3/metric_service_client.js b/packages/monitoring/src/v3/metric_service_client.js deleted file mode 100644 index 59d0eb01631..00000000000 --- a/packages/monitoring/src/v3/metric_service_client.js +++ /dev/null @@ -1,1097 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - * - * EDITING INSTRUCTIONS - * This file was generated from the file - * https://github.com/googleapis/googleapis/blob/master/google/monitoring/v3/metric_service.proto, - * and updates to that file get reflected here through a refresh process. - * For the short term, the refresh process will only be runnable by Google - * engineers. - * - * The only allowed edits are to method and file documentation. A 3-way - * merge preserves those additions if the generated source changes. - */ -/* TODO: introduce line-wrapping so that it never exceeds the limit. */ -/* jscs: disable maximumLineLength */ -'use strict'; - -var configData = require('./metric_service_client_config'); -var extend = require('extend'); -var gax = require('google-gax'); - -var SERVICE_ADDRESS = 'monitoring.googleapis.com'; - -var DEFAULT_SERVICE_PORT = 443; - -var CODE_GEN_NAME_VERSION = 'gapic/0.0.5'; - -var PAGE_DESCRIPTORS = { - listMonitoredResourceDescriptors: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'resourceDescriptors'), - listMetricDescriptors: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'metricDescriptors'), - listTimeSeries: new gax.PageDescriptor( - 'pageToken', - 'nextPageToken', - 'timeSeries') -}; - -/** - * The scopes needed to make gRPC calls to all of the methods defined in - * this service. - */ -var ALL_SCOPES = [ - 'https://www.googleapis.com/auth/cloud-platform', - 'https://www.googleapis.com/auth/monitoring', - 'https://www.googleapis.com/auth/monitoring.read', - 'https://www.googleapis.com/auth/monitoring.write' -]; - -/** - * Manages metric descriptors, monitored resource descriptors, and - * time series data. - * - * - * @class - */ -function MetricServiceClient(gaxGrpc, grpcClients, opts) { - opts = extend({ - servicePath: SERVICE_ADDRESS, - port: DEFAULT_SERVICE_PORT, - clientConfig: {} - }, opts); - - var googleApiClient = [ - 'gl-node/' + process.versions.node - ]; - if (opts.libName && opts.libVersion) { - googleApiClient.push(opts.libName + '/' + opts.libVersion); - } - googleApiClient.push( - CODE_GEN_NAME_VERSION, - 'gax/' + gax.version, - 'grpc/' + gaxGrpc.grpcVersion - ); - - var defaults = gaxGrpc.constructSettings( - 'google.monitoring.v3.MetricService', - configData, - opts.clientConfig, - {'x-goog-api-client': googleApiClient.join(' ')}); - - var self = this; - - this.auth = gaxGrpc.auth; - var metricServiceStub = gaxGrpc.createStub( - grpcClients.google.monitoring.v3.MetricService, - opts); - var metricServiceStubMethods = [ - 'listMonitoredResourceDescriptors', - 'getMonitoredResourceDescriptor', - 'listMetricDescriptors', - 'getMetricDescriptor', - 'createMetricDescriptor', - 'deleteMetricDescriptor', - 'listTimeSeries', - 'createTimeSeries' - ]; - metricServiceStubMethods.forEach(function(methodName) { - self['_' + methodName] = gax.createApiCall( - metricServiceStub.then(function(metricServiceStub) { - return function() { - var args = Array.prototype.slice.call(arguments, 0); - return metricServiceStub[methodName].apply(metricServiceStub, args); - }; - }), - defaults[methodName], - PAGE_DESCRIPTORS[methodName]); - }); -} - -// Path templates - -var PROJECT_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}'); - -var METRIC_DESCRIPTOR_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}/metricDescriptors/{metric_descriptor=**}'); - -var MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE = new gax.PathTemplate( - 'projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}'); - -/** - * Returns a fully-qualified project resource name string. - * @param {String} project - * @returns {String} - */ -MetricServiceClient.prototype.projectPath = function(project) { - return PROJECT_PATH_TEMPLATE.render({ - project: project - }); -}; - -/** - * Returns a fully-qualified metric_descriptor resource name string. - * @param {String} project - * @param {String} metricDescriptor - * @returns {String} - */ -MetricServiceClient.prototype.metricDescriptorPath = function(project, metricDescriptor) { - return METRIC_DESCRIPTOR_PATH_TEMPLATE.render({ - project: project, - metric_descriptor: metricDescriptor - }); -}; - -/** - * Returns a fully-qualified monitored_resource_descriptor resource name string. - * @param {String} project - * @param {String} monitoredResourceDescriptor - * @returns {String} - */ -MetricServiceClient.prototype.monitoredResourceDescriptorPath = function(project, monitoredResourceDescriptor) { - return MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.render({ - project: project, - monitored_resource_descriptor: monitoredResourceDescriptor - }); -}; - -/** - * Parses the projectName from a project resource. - * @param {String} projectName - * A fully-qualified path representing a project resources. - * @returns {String} - A string representing the project. - */ -MetricServiceClient.prototype.matchProjectFromProjectName = function(projectName) { - return PROJECT_PATH_TEMPLATE.match(projectName).project; -}; - -/** - * Parses the metricDescriptorName from a metric_descriptor resource. - * @param {String} metricDescriptorName - * A fully-qualified path representing a metric_descriptor resources. - * @returns {String} - A string representing the project. - */ -MetricServiceClient.prototype.matchProjectFromMetricDescriptorName = function(metricDescriptorName) { - return METRIC_DESCRIPTOR_PATH_TEMPLATE.match(metricDescriptorName).project; -}; - -/** - * Parses the metricDescriptorName from a metric_descriptor resource. - * @param {String} metricDescriptorName - * A fully-qualified path representing a metric_descriptor resources. - * @returns {String} - A string representing the metric_descriptor. - */ -MetricServiceClient.prototype.matchMetricDescriptorFromMetricDescriptorName = function(metricDescriptorName) { - return METRIC_DESCRIPTOR_PATH_TEMPLATE.match(metricDescriptorName).metric_descriptor; -}; - -/** - * Parses the monitoredResourceDescriptorName from a monitored_resource_descriptor resource. - * @param {String} monitoredResourceDescriptorName - * A fully-qualified path representing a monitored_resource_descriptor resources. - * @returns {String} - A string representing the project. - */ -MetricServiceClient.prototype.matchProjectFromMonitoredResourceDescriptorName = function(monitoredResourceDescriptorName) { - return MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.match(monitoredResourceDescriptorName).project; -}; - -/** - * Parses the monitoredResourceDescriptorName from a monitored_resource_descriptor resource. - * @param {String} monitoredResourceDescriptorName - * A fully-qualified path representing a monitored_resource_descriptor resources. - * @returns {String} - A string representing the monitored_resource_descriptor. - */ -MetricServiceClient.prototype.matchMonitoredResourceDescriptorFromMonitoredResourceDescriptorName = function(monitoredResourceDescriptorName) { - return MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE.match(monitoredResourceDescriptorName).monitored_resource_descriptor; -}; - -/** - * Get the project ID used by this class. - * @param {function(Error, string)} callback - the callback to be called with - * the current project Id. - */ -MetricServiceClient.prototype.getProjectId = function(callback) { - return this.auth.getProjectId(callback); -}; - -// Service calls - -/** - * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string=} request.filter - * An optional [filter](https://cloud.google.com/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListMonitoredResourceDescriptorsResponse]{@link ListMonitoredResourceDescriptorsResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListMonitoredResourceDescriptorsResponse]{@link ListMonitoredResourceDescriptorsResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * // Iterate over all elements. - * var formattedName = client.projectPath("[PROJECT]"); - * - * client.listMonitoredResourceDescriptors({name: formattedName}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }) - * .catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var formattedName = client.projectPath("[PROJECT]"); - * - * - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listMonitoredResourceDescriptors(nextRequest, options).then(callback); - * } - * } - * client.listMonitoredResourceDescriptors({name: formattedName}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -MetricServiceClient.prototype.listMonitoredResourceDescriptors = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listMonitoredResourceDescriptors(request, options, callback); -}; - -/** - * Equivalent to {@link listMonitoredResourceDescriptors}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listMonitoredResourceDescriptors} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string=} request.filter - * An optional [filter](https://cloud.google.com/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"} on 'data' event. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * var formattedName = client.projectPath("[PROJECT]"); - * client.listMonitoredResourceDescriptorsStream({name: formattedName}) - * .on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.log(err); - * }); - */ -MetricServiceClient.prototype.listMonitoredResourceDescriptorsStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listMonitoredResourceDescriptors.createStream(this._listMonitoredResourceDescriptors, request, options); -}; - -/** - * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The monitored resource descriptor to get. The format is - * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. - * The `{resource_type}` is a predefined type, such as - * `cloudsql_database`. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * var formattedName = client.monitoredResourceDescriptorPath("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); - * client.getMonitoredResourceDescriptor({name: formattedName}).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(function(err) { - * console.error(err); - * }); - */ -MetricServiceClient.prototype.getMonitoredResourceDescriptor = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._getMonitoredResourceDescriptor(request, options, callback); -}; - -/** - * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string=} request.filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](https://cloud.google.com/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListMetricDescriptorsResponse]{@link ListMetricDescriptorsResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListMetricDescriptorsResponse]{@link ListMetricDescriptorsResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * // Iterate over all elements. - * var formattedName = client.projectPath("[PROJECT]"); - * - * client.listMetricDescriptors({name: formattedName}).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }) - * .catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var formattedName = client.projectPath("[PROJECT]"); - * - * - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listMetricDescriptors(nextRequest, options).then(callback); - * } - * } - * client.listMetricDescriptors({name: formattedName}, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -MetricServiceClient.prototype.listMetricDescriptors = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listMetricDescriptors(request, options, callback); -}; - -/** - * Equivalent to {@link listMetricDescriptors}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listMetricDescriptors} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {string=} request.filter - * If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](https://cloud.google.com/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"} on 'data' event. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * var formattedName = client.projectPath("[PROJECT]"); - * client.listMetricDescriptorsStream({name: formattedName}) - * .on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.log(err); - * }); - */ -MetricServiceClient.prototype.listMetricDescriptorsStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listMetricDescriptors.createStream(this._listMetricDescriptors, request, options); -}; - -/** - * Gets a single metric descriptor. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example value of `{metric_id}` is - * `"compute.googleapis.com/instance/disk/read_bytes_count"`. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * var formattedName = client.metricDescriptorPath("[PROJECT]", "[METRIC_DESCRIPTOR]"); - * client.getMetricDescriptor({name: formattedName}).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(function(err) { - * console.error(err); - * }); - */ -MetricServiceClient.prototype.getMetricDescriptor = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._getMetricDescriptor(request, options, callback); -}; - -/** - * Creates a new metric descriptor. - * User-created metric descriptors define - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics). - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {Object} request.metricDescriptor - * The new [custom metric](https://cloud.google.com/monitoring/custom-metrics) - * descriptor. - * - * This object should have the same structure as [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"} - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is an object representing [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is an object representing [google.api.MetricDescriptor]{@link external:"google.api.MetricDescriptor"}. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * var formattedName = client.projectPath("[PROJECT]"); - * var metricDescriptor = {}; - * var request = { - * name: formattedName, - * metricDescriptor: metricDescriptor - * }; - * client.createMetricDescriptor(request).then(function(responses) { - * var response = responses[0]; - * // doThingsWith(response) - * }) - * .catch(function(err) { - * console.error(err); - * }); - */ -MetricServiceClient.prototype.createMetricDescriptor = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._createMetricDescriptor(request, options, callback); -}; - -/** - * Deletes a metric descriptor. Only user-created - * [custom metrics](https://cloud.google.com/monitoring/custom-metrics) can be deleted. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example of `{metric_id}` is: - * `"custom.googleapis.com/my_test_metric"`. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error)=} callback - * The function which will be called with the result of the API call. - * @return {Promise} - The promise which resolves when API call finishes. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * var formattedName = client.metricDescriptorPath("[PROJECT]", "[METRIC_DESCRIPTOR]"); - * client.deleteMetricDescriptor({name: formattedName}).catch(function(err) { - * console.error(err); - * }); - */ -MetricServiceClient.prototype.deleteMetricDescriptor = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._deleteMetricDescriptor(request, options, callback); -}; - -/** - * Lists time series that match a filter. This method does not require a Stackdriver account. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param {string} request.filter - * A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.label.instance_name = "my-instance-name" - * @param {Object} request.interval - * The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * - * This object should have the same structure as [TimeInterval]{@link TimeInterval} - * @param {number} request.view - * Specifies which information is returned about the time series. - * - * The number should be among the values of [TimeSeriesView]{@link TimeSeriesView} - * @param {Object=} request.aggregation - * By default, the raw time series data is returned. - * Use this field to combine multiple time series for different - * views of the data. - * - * This object should have the same structure as [Aggregation]{@link Aggregation} - * @param {string=} request.orderBy - * Specifies the order in which the points of the time series should - * be returned. By default, results are not ordered. Currently, - * this field must be left blank. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error, ?Array, ?Object, ?Object)=} callback - * The function which will be called with the result of the API call. - * - * The second parameter to the callback is Array of [TimeSeries]{@link TimeSeries}. - * - * When autoPaginate: false is specified through options, it contains the result - * in a single response. If the response indicates the next page exists, the third - * parameter is set to be used for the next request object. The fourth parameter keeps - * the raw response object of an object representing [ListTimeSeriesResponse]{@link ListTimeSeriesResponse}. - * @return {Promise} - The promise which resolves to an array. - * The first element of the array is Array of [TimeSeries]{@link TimeSeries}. - * - * When autoPaginate: false is specified through options, the array has three elements. - * The first element is Array of [TimeSeries]{@link TimeSeries} in a single response. - * The second element is the next request object if the response - * indicates the next page exists, or null. The third element is - * an object representing [ListTimeSeriesResponse]{@link ListTimeSeriesResponse}. - * - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * // Iterate over all elements. - * var formattedName = client.projectPath("[PROJECT]"); - * var filter = ''; - * var interval = {}; - * var view = monitoring.v3.types.ListTimeSeriesRequest.TimeSeriesView.FULL; - * var request = { - * name: formattedName, - * filter: filter, - * interval: interval, - * view: view - * }; - * - * client.listTimeSeries(request).then(function(responses) { - * var resources = responses[0]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]) - * } - * }) - * .catch(function(err) { - * console.error(err); - * }); - * - * // Or obtain the paged response. - * var formattedName = client.projectPath("[PROJECT]"); - * var filter = ''; - * var interval = {}; - * var view = monitoring.v3.types.ListTimeSeriesRequest.TimeSeriesView.FULL; - * var request = { - * name: formattedName, - * filter: filter, - * interval: interval, - * view: view - * }; - * - * - * var options = {autoPaginate: false}; - * function callback(responses) { - * // The actual resources in a response. - * var resources = responses[0]; - * // The next request if the response shows there's more responses. - * var nextRequest = responses[1]; - * // The actual response object, if necessary. - * // var rawResponse = responses[2]; - * for (var i = 0; i < resources.length; ++i) { - * // doThingsWith(resources[i]); - * } - * if (nextRequest) { - * // Fetch the next page. - * return client.listTimeSeries(nextRequest, options).then(callback); - * } - * } - * client.listTimeSeries(request, options) - * .then(callback) - * .catch(function(err) { - * console.error(err); - * }); - */ -MetricServiceClient.prototype.listTimeSeries = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._listTimeSeries(request, options, callback); -}; - -/** - * Equivalent to {@link listTimeSeries}, but returns a NodeJS Stream object. - * - * This fetches the paged responses for {@link listTimeSeries} continuously - * and invokes the callback registered for 'data' event for each element in the - * responses. - * - * The returned object has 'end' method when no more elements are required. - * - * autoPaginate option will be ignored. - * - * @see {@link https://nodejs.org/api/stream.html} - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project on which to execute the request. The format is - * "projects/{project_id_or_number}". - * @param {string} request.filter - * A [monitoring filter](https://cloud.google.com/monitoring/api/v3/filters) that specifies which time - * series should be returned. The filter must specify a single metric type, - * and can additionally specify metric labels and other information. For - * example: - * - * metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND - * metric.label.instance_name = "my-instance-name" - * @param {Object} request.interval - * The time interval for which results should be returned. Only time series - * that contain data points in the specified interval are included - * in the response. - * - * This object should have the same structure as [TimeInterval]{@link TimeInterval} - * @param {number} request.view - * Specifies which information is returned about the time series. - * - * The number should be among the values of [TimeSeriesView]{@link TimeSeriesView} - * @param {Object=} request.aggregation - * By default, the raw time series data is returned. - * Use this field to combine multiple time series for different - * views of the data. - * - * This object should have the same structure as [Aggregation]{@link Aggregation} - * @param {string=} request.orderBy - * Specifies the order in which the points of the time series should - * be returned. By default, results are not ordered. Currently, - * this field must be left blank. - * @param {number=} request.pageSize - * The maximum number of resources contained in the underlying API - * response. If page streaming is performed per-resource, this - * parameter does not affect the return value. If page streaming is - * performed per-page, this determines the maximum number of - * resources in a page. - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @return {Stream} - * An object stream which emits an object representing [TimeSeries]{@link TimeSeries} on 'data' event. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * var formattedName = client.projectPath("[PROJECT]"); - * var filter = ''; - * var interval = {}; - * var view = monitoring.v3.types.ListTimeSeriesRequest.TimeSeriesView.FULL; - * var request = { - * name: formattedName, - * filter: filter, - * interval: interval, - * view: view - * }; - * client.listTimeSeriesStream(request) - * .on('data', function(element) { - * // doThingsWith(element) - * }).on('error', function(err) { - * console.log(err); - * }); - */ -MetricServiceClient.prototype.listTimeSeriesStream = function(request, options) { - if (options === undefined) { - options = {}; - } - - return PAGE_DESCRIPTORS.listTimeSeries.createStream(this._listTimeSeries, request, options); -}; - -/** - * Creates or adds data to one or more time series. - * The response is empty if all time series in the request were written. - * If any time series could not be written, a corresponding failure message is - * included in the error response. - * - * @param {Object} request - * The request object that will be sent. - * @param {string} request.name - * The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param {Object[]} request.timeSeries - * The new data to be added to a list of time series. - * Adds at most one data point to each of several time series. The new data - * point must be more recent than any other point in its time series. Each - * `TimeSeries` value must fully specify a unique time series by supplying - * all label values for the metric and the monitored resource. - * - * This object should have the same structure as [TimeSeries]{@link TimeSeries} - * @param {Object=} options - * Optional parameters. You can override the default settings for this call, e.g, timeout, - * retries, paginations, etc. See [gax.CallOptions]{@link https://googleapis.github.io/gax-nodejs/global.html#CallOptions} for the details. - * @param {function(?Error)=} callback - * The function which will be called with the result of the API call. - * @return {Promise} - The promise which resolves when API call finishes. - * The promise has a method named "cancel" which cancels the ongoing API call. - * - * @example - * - * var monitoring = require('@google-cloud/monitoring'); - * - * var client = monitoring.v3.metric({ - * // optional auth parameters. - * }); - * - * var formattedName = client.projectPath("[PROJECT]"); - * var timeSeries = []; - * var request = { - * name: formattedName, - * timeSeries: timeSeries - * }; - * client.createTimeSeries(request).catch(function(err) { - * console.error(err); - * }); - */ -MetricServiceClient.prototype.createTimeSeries = function(request, options, callback) { - if (options instanceof Function && callback === undefined) { - callback = options; - options = {}; - } - if (options === undefined) { - options = {}; - } - - return this._createTimeSeries(request, options, callback); -}; - -function MetricServiceClientBuilder(gaxGrpc) { - if (!(this instanceof MetricServiceClientBuilder)) { - return new MetricServiceClientBuilder(gaxGrpc); - } - - var metricServiceClient = gaxGrpc.load([{ - root: require('google-proto-files')('..'), - file: 'google/monitoring/v3/metric_service.proto' - }]); - extend(this, metricServiceClient.google.monitoring.v3); - - - /** - * Build a new instance of {@link MetricServiceClient}. - * - * @param {Object=} opts - The optional parameters. - * @param {String=} opts.servicePath - * The domain name of the API remote host. - * @param {number=} opts.port - * The port on which to connect to the remote host. - * @param {grpc.ClientCredentials=} opts.sslCreds - * A ClientCredentials for use with an SSL-enabled channel. - * @param {Object=} opts.clientConfig - * The customized config to build the call settings. See - * {@link gax.constructSettings} for the format. - */ - this.metricServiceClient = function(opts) { - return new MetricServiceClient(gaxGrpc, metricServiceClient, opts); - }; - extend(this.metricServiceClient, MetricServiceClient); -} -module.exports = MetricServiceClientBuilder; -module.exports.SERVICE_ADDRESS = SERVICE_ADDRESS; -module.exports.ALL_SCOPES = ALL_SCOPES; \ No newline at end of file diff --git a/packages/monitoring/src/v3/metric_service_client_config.json b/packages/monitoring/src/v3/metric_service_client_config.json deleted file mode 100644 index 15f82ab1547..00000000000 --- a/packages/monitoring/src/v3/metric_service_client_config.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "interfaces": { - "google.monitoring.v3.MetricService": { - "retry_codes": { - "idempotent": [ - "DEADLINE_EXCEEDED", - "UNAVAILABLE" - ], - "non_idempotent": [] - }, - "retry_params": { - "default": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000 - } - }, - "methods": { - "ListMonitoredResourceDescriptors": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "GetMonitoredResourceDescriptor": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ListMetricDescriptors": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "GetMetricDescriptor": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "CreateMetricDescriptor": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - }, - "DeleteMetricDescriptor": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "ListTimeSeries": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default" - }, - "CreateTimeSeries": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default" - } - } - } - } -} diff --git a/packages/monitoring/test/gapic-v3.js b/packages/monitoring/test/gapic-v3.js deleted file mode 100644 index 838498b3bc8..00000000000 --- a/packages/monitoring/test/gapic-v3.js +++ /dev/null @@ -1,766 +0,0 @@ -/* - * Copyright 2017, Google Inc. All rights reserved. - * - * 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 - * - * http://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. - */ -'use strict'; - -var assert = require('assert'); -var monitoring = require('../src'); - -var FAKE_STATUS_CODE = 1; -var error = new Error(); -error.code = FAKE_STATUS_CODE; - -describe('GroupServiceClient', function() { - describe('listGroups', function() { - it('invokes listGroups without error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var request = { - name : formattedName - }; - - // Mock response - var nextPageToken = ''; - var groupElement = {}; - var group = [groupElement]; - var expectedResponse = { - nextPageToken : nextPageToken, - group : group - }; - - // Mock Grpc layer - client._listGroups = function(actualRequest, options, callback) { - assert.deepStrictEqual(actualRequest, request); - callback(null, expectedResponse.group); - }; - - client.listGroups(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse.group); - done(); - }); - }); - - it('invokes listGroups with error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._listGroups = mockSimpleGrpcMethod(request, null, error); - - client.listGroups(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('getGroup', function() { - it('invokes getGroup without error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - var request = { - name : formattedName - }; - - // Mock response - var name2 = 'name2-1052831874'; - var displayName = 'displayName1615086568'; - var parentName = 'parentName1015022848'; - var filter = 'filter-1274492040'; - var isCluster = false; - var expectedResponse = { - name : name2, - displayName : displayName, - parentName : parentName, - filter : filter, - isCluster : isCluster - }; - - // Mock Grpc layer - client._getGroup = mockSimpleGrpcMethod(request, expectedResponse); - - client.getGroup(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes getGroup with error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._getGroup = mockSimpleGrpcMethod(request, null, error); - - client.getGroup(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('createGroup', function() { - it('invokes createGroup without error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var group = {}; - var request = { - name : formattedName, - group : group - }; - - // Mock response - var name2 = 'name2-1052831874'; - var displayName = 'displayName1615086568'; - var parentName = 'parentName1015022848'; - var filter = 'filter-1274492040'; - var isCluster = false; - var expectedResponse = { - name : name2, - displayName : displayName, - parentName : parentName, - filter : filter, - isCluster : isCluster - }; - - // Mock Grpc layer - client._createGroup = mockSimpleGrpcMethod(request, expectedResponse); - - client.createGroup(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes createGroup with error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var group = {}; - var request = { - name : formattedName, - group : group - }; - - // Mock Grpc layer - client._createGroup = mockSimpleGrpcMethod(request, null, error); - - client.createGroup(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('updateGroup', function() { - it('invokes updateGroup without error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var group = {}; - var request = { - group : group - }; - - // Mock response - var name = 'name3373707'; - var displayName = 'displayName1615086568'; - var parentName = 'parentName1015022848'; - var filter = 'filter-1274492040'; - var isCluster = false; - var expectedResponse = { - name : name, - displayName : displayName, - parentName : parentName, - filter : filter, - isCluster : isCluster - }; - - // Mock Grpc layer - client._updateGroup = mockSimpleGrpcMethod(request, expectedResponse); - - client.updateGroup(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes updateGroup with error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var group = {}; - var request = { - group : group - }; - - // Mock Grpc layer - client._updateGroup = mockSimpleGrpcMethod(request, null, error); - - client.updateGroup(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('deleteGroup', function() { - it('invokes deleteGroup without error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._deleteGroup = mockSimpleGrpcMethod(request); - - client.deleteGroup(request, function(err) { - assert.ifError(err); - done(); - }); - }); - - it('invokes deleteGroup with error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._deleteGroup = mockSimpleGrpcMethod(request, null, error); - - client.deleteGroup(request, function(err) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('listGroupMembers', function() { - it('invokes listGroupMembers without error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - var request = { - name : formattedName - }; - - // Mock response - var nextPageToken = ''; - var totalSize = -705419236; - var membersElement = {}; - var members = [membersElement]; - var expectedResponse = { - nextPageToken : nextPageToken, - totalSize : totalSize, - members : members - }; - - // Mock Grpc layer - client._listGroupMembers = function(actualRequest, options, callback) { - assert.deepStrictEqual(actualRequest, request); - callback(null, expectedResponse.members); - }; - - client.listGroupMembers(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse.members); - done(); - }); - }); - - it('invokes listGroupMembers with error', function(done) { - var client = monitoring.v3.group(); - - // Mock request - var formattedName = client.groupPath("[PROJECT]", "[GROUP]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._listGroupMembers = mockSimpleGrpcMethod(request, null, error); - - client.listGroupMembers(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - -}); -describe('MetricServiceClient', function() { - describe('listMonitoredResourceDescriptors', function() { - it('invokes listMonitoredResourceDescriptors without error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var request = { - name : formattedName - }; - - // Mock response - var nextPageToken = ''; - var resourceDescriptorsElement = {}; - var resourceDescriptors = [resourceDescriptorsElement]; - var expectedResponse = { - nextPageToken : nextPageToken, - resourceDescriptors : resourceDescriptors - }; - - // Mock Grpc layer - client._listMonitoredResourceDescriptors = function(actualRequest, options, callback) { - assert.deepStrictEqual(actualRequest, request); - callback(null, expectedResponse.resourceDescriptors); - }; - - client.listMonitoredResourceDescriptors(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse.resourceDescriptors); - done(); - }); - }); - - it('invokes listMonitoredResourceDescriptors with error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._listMonitoredResourceDescriptors = mockSimpleGrpcMethod(request, null, error); - - client.listMonitoredResourceDescriptors(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('getMonitoredResourceDescriptor', function() { - it('invokes getMonitoredResourceDescriptor without error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.monitoredResourceDescriptorPath("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); - var request = { - name : formattedName - }; - - // Mock response - var name2 = 'name2-1052831874'; - var type = 'type3575610'; - var displayName = 'displayName1615086568'; - var description = 'description-1724546052'; - var expectedResponse = { - name : name2, - type : type, - displayName : displayName, - description : description - }; - - // Mock Grpc layer - client._getMonitoredResourceDescriptor = mockSimpleGrpcMethod(request, expectedResponse); - - client.getMonitoredResourceDescriptor(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes getMonitoredResourceDescriptor with error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.monitoredResourceDescriptorPath("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._getMonitoredResourceDescriptor = mockSimpleGrpcMethod(request, null, error); - - client.getMonitoredResourceDescriptor(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('listMetricDescriptors', function() { - it('invokes listMetricDescriptors without error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var request = { - name : formattedName - }; - - // Mock response - var nextPageToken = ''; - var metricDescriptorsElement = {}; - var metricDescriptors = [metricDescriptorsElement]; - var expectedResponse = { - nextPageToken : nextPageToken, - metricDescriptors : metricDescriptors - }; - - // Mock Grpc layer - client._listMetricDescriptors = function(actualRequest, options, callback) { - assert.deepStrictEqual(actualRequest, request); - callback(null, expectedResponse.metricDescriptors); - }; - - client.listMetricDescriptors(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse.metricDescriptors); - done(); - }); - }); - - it('invokes listMetricDescriptors with error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._listMetricDescriptors = mockSimpleGrpcMethod(request, null, error); - - client.listMetricDescriptors(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('getMetricDescriptor', function() { - it('invokes getMetricDescriptor without error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.metricDescriptorPath("[PROJECT]", "[METRIC_DESCRIPTOR]"); - var request = { - name : formattedName - }; - - // Mock response - var name2 = 'name2-1052831874'; - var type = 'type3575610'; - var unit = 'unit3594628'; - var description = 'description-1724546052'; - var displayName = 'displayName1615086568'; - var expectedResponse = { - name : name2, - type : type, - unit : unit, - description : description, - displayName : displayName - }; - - // Mock Grpc layer - client._getMetricDescriptor = mockSimpleGrpcMethod(request, expectedResponse); - - client.getMetricDescriptor(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes getMetricDescriptor with error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.metricDescriptorPath("[PROJECT]", "[METRIC_DESCRIPTOR]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._getMetricDescriptor = mockSimpleGrpcMethod(request, null, error); - - client.getMetricDescriptor(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('createMetricDescriptor', function() { - it('invokes createMetricDescriptor without error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var metricDescriptor = {}; - var request = { - name : formattedName, - metricDescriptor : metricDescriptor - }; - - // Mock response - var name2 = 'name2-1052831874'; - var type = 'type3575610'; - var unit = 'unit3594628'; - var description = 'description-1724546052'; - var displayName = 'displayName1615086568'; - var expectedResponse = { - name : name2, - type : type, - unit : unit, - description : description, - displayName : displayName - }; - - // Mock Grpc layer - client._createMetricDescriptor = mockSimpleGrpcMethod(request, expectedResponse); - - client.createMetricDescriptor(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse); - done(); - }); - }); - - it('invokes createMetricDescriptor with error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var metricDescriptor = {}; - var request = { - name : formattedName, - metricDescriptor : metricDescriptor - }; - - // Mock Grpc layer - client._createMetricDescriptor = mockSimpleGrpcMethod(request, null, error); - - client.createMetricDescriptor(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('deleteMetricDescriptor', function() { - it('invokes deleteMetricDescriptor without error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.metricDescriptorPath("[PROJECT]", "[METRIC_DESCRIPTOR]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._deleteMetricDescriptor = mockSimpleGrpcMethod(request); - - client.deleteMetricDescriptor(request, function(err) { - assert.ifError(err); - done(); - }); - }); - - it('invokes deleteMetricDescriptor with error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.metricDescriptorPath("[PROJECT]", "[METRIC_DESCRIPTOR]"); - var request = { - name : formattedName - }; - - // Mock Grpc layer - client._deleteMetricDescriptor = mockSimpleGrpcMethod(request, null, error); - - client.deleteMetricDescriptor(request, function(err) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('listTimeSeries', function() { - it('invokes listTimeSeries without error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var filter = 'filter-1274492040'; - var interval = {}; - var view = monitoring.v3.types.ListTimeSeriesRequest.TimeSeriesView.FULL; - var request = { - name : formattedName, - filter : filter, - interval : interval, - view : view - }; - - // Mock response - var nextPageToken = ''; - var timeSeriesElement = {}; - var timeSeries = [timeSeriesElement]; - var expectedResponse = { - nextPageToken : nextPageToken, - timeSeries : timeSeries - }; - - // Mock Grpc layer - client._listTimeSeries = function(actualRequest, options, callback) { - assert.deepStrictEqual(actualRequest, request); - callback(null, expectedResponse.timeSeries); - }; - - client.listTimeSeries(request, function(err, response) { - assert.ifError(err); - assert.deepStrictEqual(response, expectedResponse.timeSeries); - done(); - }); - }); - - it('invokes listTimeSeries with error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var filter = 'filter-1274492040'; - var interval = {}; - var view = monitoring.v3.types.ListTimeSeriesRequest.TimeSeriesView.FULL; - var request = { - name : formattedName, - filter : filter, - interval : interval, - view : view - }; - - // Mock Grpc layer - client._listTimeSeries = mockSimpleGrpcMethod(request, null, error); - - client.listTimeSeries(request, function(err, response) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - - describe('createTimeSeries', function() { - it('invokes createTimeSeries without error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var timeSeries = []; - var request = { - name : formattedName, - timeSeries : timeSeries - }; - - // Mock Grpc layer - client._createTimeSeries = mockSimpleGrpcMethod(request); - - client.createTimeSeries(request, function(err) { - assert.ifError(err); - done(); - }); - }); - - it('invokes createTimeSeries with error', function(done) { - var client = monitoring.v3.metric(); - - // Mock request - var formattedName = client.projectPath("[PROJECT]"); - var timeSeries = []; - var request = { - name : formattedName, - timeSeries : timeSeries - }; - - // Mock Grpc layer - client._createTimeSeries = mockSimpleGrpcMethod(request, null, error); - - client.createTimeSeries(request, function(err) { - assert(err instanceof Error); - assert.equal(err.code, FAKE_STATUS_CODE); - done(); - }); - }); - }); - -}); - -function mockSimpleGrpcMethod(expectedRequest, response, error) { - return function(actualRequest, options, callback) { - assert.deepStrictEqual(actualRequest, expectedRequest); - if (error) { - callback(error); - } else if (response) { - callback(null, response); - } else { - callback(null); - } - }; -}