os_unix.go (2696B)
1 // Copyright The OpenTelemetry Authors 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 // http://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 //go:build aix || darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris || zos 16 // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris zos 17 18 package resource // import "go.opentelemetry.io/otel/sdk/resource" 19 20 import ( 21 "fmt" 22 "os" 23 24 "golang.org/x/sys/unix" 25 ) 26 27 type unameProvider func(buf *unix.Utsname) (err error) 28 29 var defaultUnameProvider unameProvider = unix.Uname 30 31 var currentUnameProvider = defaultUnameProvider 32 33 func setDefaultUnameProvider() { 34 setUnameProvider(defaultUnameProvider) 35 } 36 37 func setUnameProvider(unameProvider unameProvider) { 38 currentUnameProvider = unameProvider 39 } 40 41 // platformOSDescription returns a human readable OS version information string. 42 // The final string combines OS release information (where available) and the 43 // result of the `uname` system call. 44 func platformOSDescription() (string, error) { 45 uname, err := uname() 46 if err != nil { 47 return "", err 48 } 49 50 osRelease := osRelease() 51 if osRelease != "" { 52 return fmt.Sprintf("%s (%s)", osRelease, uname), nil 53 } 54 55 return uname, nil 56 } 57 58 // uname issues a uname(2) system call (or equivalent on systems which doesn't 59 // have one) and formats the output in a single string, similar to the output 60 // of the `uname` commandline program. The final string resembles the one 61 // obtained with a call to `uname -snrvm`. 62 func uname() (string, error) { 63 var utsName unix.Utsname 64 65 err := currentUnameProvider(&utsName) 66 if err != nil { 67 return "", err 68 } 69 70 return fmt.Sprintf("%s %s %s %s %s", 71 unix.ByteSliceToString(utsName.Sysname[:]), 72 unix.ByteSliceToString(utsName.Nodename[:]), 73 unix.ByteSliceToString(utsName.Release[:]), 74 unix.ByteSliceToString(utsName.Version[:]), 75 unix.ByteSliceToString(utsName.Machine[:]), 76 ), nil 77 } 78 79 // getFirstAvailableFile returns an *os.File of the first available 80 // file from a list of candidate file paths. 81 func getFirstAvailableFile(candidates []string) (*os.File, error) { 82 for _, c := range candidates { 83 file, err := os.Open(c) 84 if err == nil { 85 return file, nil 86 } 87 } 88 89 return nil, fmt.Errorf("no candidate file available: %v", candidates) 90 }