UNPKG

@opentelemetry/resources

Version:
96 lines 3.44 kB
"use strict"; /*! * Copyright 2020, OpenTelemetry Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); const os = require("os"); const gcpMetadata = require("gcp-metadata"); const Resource_1 = require("../../../Resource"); const constants_1 = require("../../../constants"); /** * The GcpDetector can be used to detect if a process is running in the Google * Cloud Platofrm and return a {@link Resource} populated with metadata about * the instance. Returns an empty Resource if detection fails. */ class GcpDetector { async detect() { if (!(await gcpMetadata.isAvailable())) return Resource_1.Resource.empty(); const [projectId, instanceId, zoneId, clusterName] = await Promise.all([ this._getProjectId(), this._getInstanceId(), this._getZone(), this._getClusterName(), ]); const labels = {}; labels[constants_1.CLOUD_RESOURCE.ACCOUNT_ID] = projectId; labels[constants_1.HOST_RESOURCE.ID] = instanceId; labels[constants_1.CLOUD_RESOURCE.ZONE] = zoneId; labels[constants_1.CLOUD_RESOURCE.PROVIDER] = 'gcp'; if (process.env.KUBERNETES_SERVICE_HOST) this._addK8sLabels(labels, clusterName); return new Resource_1.Resource(labels); } /** Add resource labels for K8s */ _addK8sLabels(labels, clusterName) { labels[constants_1.K8S_RESOURCE.CLUSTER_NAME] = clusterName; labels[constants_1.K8S_RESOURCE.NAMESPACE_NAME] = process.env.NAMESPACE || ''; labels[constants_1.K8S_RESOURCE.POD_NAME] = process.env.HOSTNAME || os.hostname(); labels[constants_1.CONTAINER_RESOURCE.NAME] = process.env.CONTAINER_NAME || ''; } /** Gets project id from GCP project metadata. */ async _getProjectId() { try { return await gcpMetadata.project('project-id'); } catch (_a) { return ''; } } /** Gets instance id from GCP instance metadata. */ async _getInstanceId() { try { const id = await gcpMetadata.instance('id'); return id.toString(); } catch (_a) { return ''; } } /** Gets zone from GCP instance metadata. */ async _getZone() { try { const zoneId = await gcpMetadata.instance('zone'); if (zoneId) { return zoneId.split('/').pop(); } return ''; } catch (_a) { return ''; } } /** Gets cluster name from GCP instance metadata. */ async _getClusterName() { try { return await gcpMetadata.instance('attributes/cluster-name'); } catch (_a) { return ''; } } } exports.gcpDetector = new GcpDetector(); //# sourceMappingURL=GcpDetector.js.map