in pkg/export/setup/setup.go [333:396]
func tryPopulateUnspecifiedFromMetadata(ctx context.Context, logger log.Logger, opts *export.ExporterOpts) {
const (
projectIDPath = "project/project-id"
clusterNamePath = "instance/attributes/cluster-name"
clusterLocationPath = "instance/attributes/cluster-location"
zonePath = "instance/zone"
)
env := UAEnvGCE // This also means GKE with metadata server disabled.
c := metadata.NewClient(nil)
// Mimick metadata.InstanceAttributeValue("cluster-name") but with context.
gkeClusterName, err := c.GetWithContext(ctx, clusterNamePath)
if err != nil {
_ = level.Debug(logger).Log("msg", "fetching entry from GCP metadata server failed; skipping", "key", clusterNamePath, "err", err)
} else if gkeClusterName != "" {
env = UAEnvGKE
if opts.Cluster == "" {
opts.Cluster = gkeClusterName
}
}
if opts.ProjectID == "" {
// Mimick metadata.ProjectID() but with context.
projectID, err := c.GetWithContext(ctx, projectIDPath)
if err != nil {
_ = level.Debug(logger).Log("msg", "fetching entry from GCP metadata server failed; skipping", "key", projectIDPath, "err", err)
} else {
opts.ProjectID = strings.TrimSpace(projectID)
}
}
if opts.Location == "" {
// These attributes are set for GKE nodes. For the location, we first check
// the cluster location, which may be a zone or a region. We must always use that value
// to avoid collisions with other clusters, as the same cluster name may be reused
// in different locations.
// In particular, we cannot set the location to the node's zone for a regional cluster,
// even though this would provide more accuracy, as there may also be a zonal cluster
// with the same name.
//
// We only fallback to the node zone as the location if no cluster location exists to
// default for deployments on GCE.
// Mimick metadata.InstanceAttributeValue("cluster-location") but with context.
loc, err := c.GetWithContext(ctx, clusterLocationPath)
if err != nil {
_ = level.Debug(logger).Log("msg", "fetching entry from GCP metadata server failed; falling back to zone", "key", clusterLocationPath, "err", err)
zone, err := c.GetWithContext(ctx, zonePath)
if err != nil {
_ = level.Debug(logger).Log("msg", "fetching entry from GCP metadata server failed; skipping", "key", zonePath, "err", err)
} else {
zone = strings.TrimSpace(zone)
// zone is of the form "projects/<projNum>/zones/<zoneName>".
opts.Location = zone[strings.LastIndex(zone, "/")+1:]
}
} else {
opts.Location = loc
}
}
if opts.UserAgentEnv == UAEnvUnspecified {
// We acknowledge that, if user set unspecified on purpose, this will override.
opts.UserAgentEnv = env
}
}