Copyright 2020, OpenCensus 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 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.

package gcp

import (
	
	
	
	
	

	
	container 
	containerpb 
)
gcpMetadata represents metadata retrieved from GCP (GKE and GCE) environment.
type gcpMetadata struct {
projectID is the identifier of the GCP project associated with this resource, such as "my-project".
instanceID is the numeric VM instance identifier assigned by Compute Engine.
clusterName is the name for the cluster the container is running in.
containerName is the name of the container.
namespaceID is the identifier for the cluster namespace the container is running in
podID is the identifier for the pod the container is running in.
zone is the Compute Engine zone in which the VM is running.
retrieveGCPMetadata retrieves value of each Attribute from Metadata Server in GKE container and GCE instance environment. Some attributes are retrieved from the system environment. This is only executed detectOnce.
func () *gcpMetadata {
	 := gcpMetadata{}
	var  error
	.instanceID,  = metadata.InstanceID()
Not a GCP environment
		return &
	}

	.projectID,  = metadata.ProjectID()
	logError()

	.zone,  = metadata.Zone()
	logError()

	,  := metadata.InstanceAttributeValue("cluster-name")
	logError()
	.clusterName = strings.TrimSpace()

	,  := metadata.InstanceAttributeValue("cluster-location")
	logError()
Following attributes are derived from environment variables. They are configured via yaml file. For details refer to: https://cloud.google.com/kubernetes-engine/docs/tutorials/custom-metrics-autoscaling#exporting_metrics_from_the_application
	.namespaceID = os.Getenv("NAMESPACE")
	.containerName = os.Getenv("CONTAINER_NAME")
	.podID = os.Getenv("HOSTNAME")
Monitoring API version can be obtained from cluster info.q
	if .clusterName != "" {
		 := context.Background()
		,  := container.NewClusterManagerClient()
		logError()
		if  != nil {
			 := &containerpb.GetClusterRequest{
				Name: fmt.Sprintf("projects/%s/locations/%s/clusters/%s", .projectID, strings.TrimSpace(), .clusterName),
			}
			,  := .GetCluster(, )
			logError()
			if  != nil && .GetMonitoringService() == "monitoring.googleapis.com/kubernetes" &&
				.GetLoggingService() == "logging.googleapis.com/kubernetes" {
				.monitoringV2 = true
			}
		}
	}

	return &
}
logError logs error only if the error is present and it is not 'not defined'
func ( error) {
	if  != nil {
		if !strings.Contains(.Error(), "not defined") {
			log.Printf("Error retrieving gcp metadata: %v", )
		}
	}