github.com/zchee/zap-cloudlogging@v0.0.0-20220819025602-19b026d3900e/pkg/detector/attr.go (about) 1 // Copyright 2022 The zap-cloudlogging Authors 2 // SPDX-License-Identifier: BSD-3-Clause 3 4 package detector 5 6 import ( 7 "net" 8 "net/http" 9 "os" 10 "strings" 11 "time" 12 "unsafe" 13 14 "cloud.google.com/go/compute/metadata" 15 ) 16 17 // ResourceAttributesFetcher abstracts environment lookup methods to query for environment variables, metadata attributes and file content. 18 type ResourceAttributesFetcher interface { 19 EnvVar(name string) string 20 Metadata(path string) string 21 ReadAll(path string) string 22 } 23 24 type resourceFetcher struct { 25 mdClient *metadata.Client 26 } 27 28 var _ ResourceAttributesFetcher = (*resourceFetcher)(nil) 29 30 // EnvVar uses os.Getenv() to gets for environment variable by name. 31 func (g *resourceFetcher) EnvVar(name string) string { 32 return os.Getenv(name) 33 } 34 35 // Metadata uses metadata package Client.Get() to lookup for metadata attributes by path. 36 func (g *resourceFetcher) Metadata(path string) string { 37 val, err := g.mdClient.Get(path) 38 if err != nil { 39 return "" 40 } 41 42 return strings.TrimSpace(val) 43 } 44 45 // ReadAll reads all content of the file as a string. 46 func (g *resourceFetcher) ReadAll(path string) string { 47 data, err := os.ReadFile(path) 48 if err != nil { 49 return "" 50 } 51 52 return *(*string)(unsafe.Pointer(&data)) 53 } 54 55 var fetcher = &resourceFetcher{ 56 mdClient: metadata.NewClient(&http.Client{ 57 Transport: &http.Transport{ 58 Dial: (&net.Dialer{ 59 Timeout: 1 * time.Second, 60 KeepAlive: 10 * time.Second, 61 }).Dial, 62 }, 63 }), 64 } 65 66 // ResourceAttributes provides read-only access to the ResourceAttributesFetcher interface implementation. 67 func ResourceAttributes() ResourceAttributesFetcher { 68 return fetcher 69 }