|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import {PushMetricExporter, ResourceMetrics} from '@opentelemetry/sdk-metrics'; |
| 16 | +import {ExportResult, ExportResultCode} from '@opentelemetry/core'; |
| 17 | +import {ExporterOptions} from './external-types'; |
| 18 | +import {MetricServiceClient} from '@google-cloud/monitoring'; |
| 19 | +import {transformResourceMetricToTimeSeriesArray} from './transform'; |
| 20 | +import {status} from '@grpc/grpc-js'; |
| 21 | + |
| 22 | +// Stackdriver Monitoring v3 only accepts up to 200 TimeSeries per |
| 23 | +// CreateTimeSeries call. |
| 24 | +export const MAX_BATCH_EXPORT_SIZE = 200; |
| 25 | + |
| 26 | +/** |
| 27 | + * Format and sends metrics information to Google Cloud Monitoring. |
| 28 | + */ |
| 29 | +export class CloudMonitoringMetricsExporter implements PushMetricExporter { |
| 30 | + private _projectId: string | void | Promise<string | void>; |
| 31 | + |
| 32 | + private readonly _client: MetricServiceClient; |
| 33 | + |
| 34 | + constructor({auth}: ExporterOptions) { |
| 35 | + this._client = new MetricServiceClient({auth: auth}); |
| 36 | + |
| 37 | + // Start this async process as early as possible. It will be |
| 38 | + // awaited on the first export because constructors are synchronous |
| 39 | + this._projectId = auth.getProjectId().catch(err => { |
| 40 | + console.error(err); |
| 41 | + }); |
| 42 | + } |
| 43 | + |
| 44 | + /** |
| 45 | + * Implementation for {@link PushMetricExporter.export}. |
| 46 | + * Calls the async wrapper method {@link _exportAsync} and |
| 47 | + * assures no rejected promises bubble up to the caller. |
| 48 | + * |
| 49 | + * @param metrics Metrics to be sent to the Google Cloud Monitoring backend |
| 50 | + * @param resultCallback result callback to be called on finish |
| 51 | + */ |
| 52 | + export( |
| 53 | + metrics: ResourceMetrics, |
| 54 | + resultCallback: (result: ExportResult) => void, |
| 55 | + ): void { |
| 56 | + this._exportAsync(metrics).then(resultCallback, err => { |
| 57 | + console.error(err.message); |
| 58 | + resultCallback({code: ExportResultCode.FAILED, error: err}); |
| 59 | + }); |
| 60 | + } |
| 61 | + |
| 62 | + async shutdown(): Promise<void> {} |
| 63 | + async forceFlush(): Promise<void> {} |
| 64 | + |
| 65 | + /** |
| 66 | + * Asnyc wrapper for the {@link export} implementation. |
| 67 | + * Writes the current values of all exported {@link MetricRecord}s |
| 68 | + * to the Google Cloud Monitoring backend. |
| 69 | + * |
| 70 | + * @param resourceMetrics Metrics to be sent to the Google Cloud Monitoring backend |
| 71 | + */ |
| 72 | + private async _exportAsync( |
| 73 | + resourceMetrics: ResourceMetrics, |
| 74 | + ): Promise<ExportResult> { |
| 75 | + if (this._projectId instanceof Promise) { |
| 76 | + this._projectId = await this._projectId; |
| 77 | + } |
| 78 | + |
| 79 | + if (!this._projectId) { |
| 80 | + const error = new Error('expecting a non-blank ProjectID'); |
| 81 | + console.error(error.message); |
| 82 | + return {code: ExportResultCode.FAILED, error}; |
| 83 | + } |
| 84 | + |
| 85 | + const timeSeriesList = |
| 86 | + transformResourceMetricToTimeSeriesArray(resourceMetrics); |
| 87 | + |
| 88 | + let failure: {sendFailed: false} | {sendFailed: true; error: Error} = { |
| 89 | + sendFailed: false, |
| 90 | + }; |
| 91 | + await Promise.all( |
| 92 | + this._partitionList(timeSeriesList, MAX_BATCH_EXPORT_SIZE).map( |
| 93 | + async batchedTimeSeries => this._sendTimeSeries(batchedTimeSeries), |
| 94 | + ), |
| 95 | + ).catch(e => { |
| 96 | + const error = e as {code: number}; |
| 97 | + if (error.code === status.PERMISSION_DENIED) { |
| 98 | + console.warn( |
| 99 | + `Need monitoring metric writer permission on project ${this._projectId}. Follow https://cloud.google.com/spanner/docs/view-manage-client-side-metrics#access-client-side-metrics to set up permissions`, |
| 100 | + ); |
| 101 | + } |
| 102 | + const err = asError(e); |
| 103 | + err.message = `Send TimeSeries failed: ${err.message}`; |
| 104 | + failure = {sendFailed: true, error: err}; |
| 105 | + console.error(`ERROR: ${err.message}`); |
| 106 | + }); |
| 107 | + |
| 108 | + return failure.sendFailed |
| 109 | + ? { |
| 110 | + code: ExportResultCode.FAILED, |
| 111 | + error: (failure as {sendFailed: boolean; error: Error}).error, |
| 112 | + } |
| 113 | + : {code: ExportResultCode.SUCCESS}; |
| 114 | + } |
| 115 | + |
| 116 | + private async _sendTimeSeries(timeSeries) { |
| 117 | + if (timeSeries.length === 0) { |
| 118 | + return Promise.resolve(); |
| 119 | + } |
| 120 | + |
| 121 | + // TODO: Use createServiceTimeSeries when it is available |
| 122 | + await this._client.createTimeSeries({ |
| 123 | + name: `projects/${this._projectId}`, |
| 124 | + timeSeries: timeSeries, |
| 125 | + }); |
| 126 | + } |
| 127 | + |
| 128 | + /** Returns the minimum number of arrays of max size chunkSize, partitioned from the given array. */ |
| 129 | + private _partitionList(list, chunkSize: number) { |
| 130 | + return Array.from({length: Math.ceil(list.length / chunkSize)}, (_, i) => |
| 131 | + list.slice(i * chunkSize, (i + 1) * chunkSize), |
| 132 | + ); |
| 133 | + } |
| 134 | +} |
| 135 | + |
| 136 | +function asError(error: unknown): Error { |
| 137 | + return error instanceof Error ? error : new Error(String(error)); |
| 138 | +} |
0 commit comments