...

Source file src/cloud.google.com/go/logging/internal/environment.go

Documentation: cloud.google.com/go/logging/internal

     1  // Copyright 2022 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  //      https://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  package internal
    16  
    17  import (
    18  	"io/ioutil"
    19  	"net"
    20  	"net/http"
    21  	"os"
    22  	"strings"
    23  	"time"
    24  
    25  	"cloud.google.com/go/compute/metadata"
    26  )
    27  
    28  // ResourceAttributesGetter abstracts environment lookup methods to query for environment variables, metadata attributes and file content.
    29  type ResourceAttributesGetter interface {
    30  	EnvVar(name string) string
    31  	Metadata(path string) string
    32  	ReadAll(path string) string
    33  }
    34  
    35  var getter ResourceAttributesGetter = &defaultResourceGetter{
    36  	metaClient: metadata.NewClient(&http.Client{
    37  		Transport: &http.Transport{
    38  			Dial: (&net.Dialer{
    39  				Timeout:   1 * time.Second,
    40  				KeepAlive: 10 * time.Second,
    41  			}).Dial,
    42  		},
    43  	})}
    44  
    45  // ResourceAttributes provides read-only access to the ResourceAtttributesGetter interface implementation.
    46  func ResourceAttributes() ResourceAttributesGetter {
    47  	return getter
    48  }
    49  
    50  type defaultResourceGetter struct {
    51  	metaClient *metadata.Client
    52  }
    53  
    54  // EnvVar uses os.LookupEnv() to lookup for environment variable by name.
    55  func (g *defaultResourceGetter) EnvVar(name string) string {
    56  	return os.Getenv(name)
    57  }
    58  
    59  // Metadata uses metadata package Client.Get() to lookup for metadata attributes by path.
    60  func (g *defaultResourceGetter) Metadata(path string) string {
    61  	val, err := g.metaClient.Get(path)
    62  	if err != nil {
    63  		return ""
    64  	}
    65  	return strings.TrimSpace(val)
    66  }
    67  
    68  // ReadAll reads all content of the file as a string.
    69  func (g *defaultResourceGetter) ReadAll(path string) string {
    70  	bytes, err := ioutil.ReadFile(path)
    71  	if err != nil {
    72  		return ""
    73  	}
    74  	return string(bytes)
    75  }
    76  

View as plain text