common.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. package common
  2. //
  3. // gopsutil is a port of psutil(http://pythonhosted.org/psutil/).
  4. // This covers these architectures.
  5. // - linux (amd64, arm)
  6. // - freebsd (amd64)
  7. // - windows (amd64)
  8. import (
  9. "bufio"
  10. "bytes"
  11. "context"
  12. "errors"
  13. "fmt"
  14. "log"
  15. "net/url"
  16. "os"
  17. "os/exec"
  18. "path"
  19. "path/filepath"
  20. "reflect"
  21. "runtime"
  22. "strconv"
  23. "strings"
  24. "time"
  25. )
  26. var (
  27. Timeout = 3 * time.Second
  28. ErrTimeout = errors.New("command timed out")
  29. )
  30. type Invoker interface {
  31. Command(string, ...string) ([]byte, error)
  32. CommandWithContext(context.Context, string, ...string) ([]byte, error)
  33. }
  34. type Invoke struct{}
  35. func (i Invoke) Command(name string, arg ...string) ([]byte, error) {
  36. ctx, cancel := context.WithTimeout(context.Background(), Timeout)
  37. defer cancel()
  38. return i.CommandWithContext(ctx, name, arg...)
  39. }
  40. func (i Invoke) CommandWithContext(ctx context.Context, name string, arg ...string) ([]byte, error) {
  41. cmd := exec.CommandContext(ctx, name, arg...)
  42. var buf bytes.Buffer
  43. cmd.Stdout = &buf
  44. cmd.Stderr = &buf
  45. if err := cmd.Start(); err != nil {
  46. return buf.Bytes(), err
  47. }
  48. if err := cmd.Wait(); err != nil {
  49. return buf.Bytes(), err
  50. }
  51. return buf.Bytes(), nil
  52. }
  53. type FakeInvoke struct {
  54. Suffix string // Suffix species expected file name suffix such as "fail"
  55. Error error // If Error specfied, return the error.
  56. }
  57. // Command in FakeInvoke returns from expected file if exists.
  58. func (i FakeInvoke) Command(name string, arg ...string) ([]byte, error) {
  59. if i.Error != nil {
  60. return []byte{}, i.Error
  61. }
  62. arch := runtime.GOOS
  63. commandName := filepath.Base(name)
  64. fname := strings.Join(append([]string{commandName}, arg...), "")
  65. fname = url.QueryEscape(fname)
  66. fpath := path.Join("testdata", arch, fname)
  67. if i.Suffix != "" {
  68. fpath += "_" + i.Suffix
  69. }
  70. if PathExists(fpath) {
  71. return os.ReadFile(fpath)
  72. }
  73. return []byte{}, fmt.Errorf("could not find testdata: %s", fpath)
  74. }
  75. func (i FakeInvoke) CommandWithContext(ctx context.Context, name string, arg ...string) ([]byte, error) {
  76. return i.Command(name, arg...)
  77. }
  78. var ErrNotImplementedError = errors.New("not implemented yet")
  79. // ReadFile reads contents from a file
  80. func ReadFile(filename string) (string, error) {
  81. content, err := os.ReadFile(filename)
  82. if err != nil {
  83. return "", err
  84. }
  85. return string(content), nil
  86. }
  87. // ReadLines reads contents from a file and splits them by new lines.
  88. // A convenience wrapper to ReadLinesOffsetN(filename, 0, -1).
  89. func ReadLines(filename string) ([]string, error) {
  90. return ReadLinesOffsetN(filename, 0, -1)
  91. }
  92. // ReadLines reads contents from file and splits them by new line.
  93. // The offset tells at which line number to start.
  94. // The count determines the number of lines to read (starting from offset):
  95. //
  96. // n >= 0: at most n lines
  97. // n < 0: whole file
  98. func ReadLinesOffsetN(filename string, offset uint, n int) ([]string, error) {
  99. f, err := os.Open(filename)
  100. if err != nil {
  101. return []string{""}, err
  102. }
  103. defer func(f *os.File) {
  104. err := f.Close()
  105. if err != nil {
  106. log.Fatalln(err)
  107. }
  108. }(f)
  109. var ret []string
  110. r := bufio.NewReader(f)
  111. for i := 0; i < n+int(offset) || n < 0; i++ {
  112. line, err := r.ReadString('\n')
  113. if err != nil {
  114. break
  115. }
  116. if i < int(offset) {
  117. continue
  118. }
  119. ret = append(ret, strings.Trim(line, "\n"))
  120. }
  121. return ret, nil
  122. }
  123. func IntToString(orig []int8) string {
  124. ret := make([]byte, len(orig))
  125. size := -1
  126. for i, o := range orig {
  127. if o == 0 {
  128. size = i
  129. break
  130. }
  131. ret[i] = byte(o)
  132. }
  133. if size == -1 {
  134. size = len(orig)
  135. }
  136. return string(ret[0:size])
  137. }
  138. func UintToString(orig []uint8) string {
  139. ret := make([]byte, len(orig))
  140. size := -1
  141. for i, o := range orig {
  142. if o == 0 {
  143. size = i
  144. break
  145. }
  146. ret[i] = byte(o)
  147. }
  148. if size == -1 {
  149. size = len(orig)
  150. }
  151. return string(ret[0:size])
  152. }
  153. func ByteToString(orig []byte) string {
  154. n := -1
  155. l := -1
  156. for i, b := range orig {
  157. // skip left side null
  158. if l == -1 && b == 0 {
  159. continue
  160. }
  161. if l == -1 {
  162. l = i
  163. }
  164. if b == 0 {
  165. break
  166. }
  167. n = i + 1
  168. }
  169. if n == -1 {
  170. return string(orig)
  171. }
  172. return string(orig[l:n])
  173. }
  174. // ReadInts reads contents from single line file and returns them as []int32.
  175. func ReadInts(filename string) ([]int64, error) {
  176. f, err := os.Open(filename)
  177. if err != nil {
  178. return []int64{}, err
  179. }
  180. defer func(f *os.File) {
  181. err := f.Close()
  182. if err != nil {
  183. log.Fatalln(err)
  184. }
  185. }(f)
  186. var ret []int64
  187. r := bufio.NewReader(f)
  188. // The int files that this is concerned with should only be one liners.
  189. line, err := r.ReadString('\n')
  190. if err != nil {
  191. return []int64{}, err
  192. }
  193. i, err := strconv.ParseInt(strings.Trim(line, "\n"), 10, 32)
  194. if err != nil {
  195. return []int64{}, err
  196. }
  197. ret = append(ret, i)
  198. return ret, nil
  199. }
  200. // Parse Hex to uint32 without error
  201. func HexToUint32(hex string) uint32 {
  202. vv, _ := strconv.ParseUint(hex, 16, 32)
  203. return uint32(vv)
  204. }
  205. // Parse to int32 without error
  206. func mustParseInt32(val string) int32 {
  207. vv, _ := strconv.ParseInt(val, 10, 32)
  208. return int32(vv)
  209. }
  210. // Parse to uint64 without error
  211. func mustParseUint64(val string) uint64 {
  212. vv, _ := strconv.ParseInt(val, 10, 64)
  213. return uint64(vv)
  214. }
  215. // Parse to Float64 without error
  216. func mustParseFloat64(val string) float64 {
  217. vv, _ := strconv.ParseFloat(val, 64)
  218. return vv
  219. }
  220. // StringsHas checks the target string slice contains src or not
  221. func StringsHas(target []string, src string) bool {
  222. for _, t := range target {
  223. if strings.TrimSpace(t) == src {
  224. return true
  225. }
  226. }
  227. return false
  228. }
  229. // StringsContains checks the src in any string of the target string slice
  230. func StringsContains(target []string, src string) bool {
  231. for _, t := range target {
  232. if strings.Contains(t, src) {
  233. return true
  234. }
  235. }
  236. return false
  237. }
  238. // IntContains checks the src in any int of the target int slice.
  239. func IntContains(target []int, src int) bool {
  240. for _, t := range target {
  241. if src == t {
  242. return true
  243. }
  244. }
  245. return false
  246. }
  247. // get struct attributes.
  248. // This method is used only for debugging platform dependent code.
  249. func attributes(m interface{}) map[string]reflect.Type {
  250. typ := reflect.TypeOf(m)
  251. if typ.Kind() == reflect.Ptr {
  252. typ = typ.Elem()
  253. }
  254. attrs := make(map[string]reflect.Type)
  255. if typ.Kind() != reflect.Struct {
  256. return nil
  257. }
  258. for i := 0; i < typ.NumField(); i++ {
  259. p := typ.Field(i)
  260. if !p.Anonymous {
  261. attrs[p.Name] = p.Type
  262. }
  263. }
  264. return attrs
  265. }
  266. func PathExists(filename string) bool {
  267. if _, err := os.Stat(filename); err == nil {
  268. return true
  269. }
  270. return false
  271. }
  272. // GetEnv retrieves the environment variable key. If it does not exist it returns the default.
  273. func GetEnv(key, dfault string, combineWith ...string) string {
  274. value := os.Getenv(key)
  275. if value == "" {
  276. value = dfault
  277. }
  278. switch len(combineWith) {
  279. case 0:
  280. return value
  281. case 1:
  282. return filepath.Join(value, combineWith[0])
  283. default:
  284. all := make([]string, len(combineWith)+1)
  285. all[0] = value
  286. copy(all[1:], combineWith)
  287. return filepath.Join(all...)
  288. }
  289. }
  290. func HostProc(combineWith ...string) string {
  291. return GetEnv("HOST_PROC", "/proc", combineWith...)
  292. }
  293. func HostSys(combineWith ...string) string {
  294. return GetEnv("HOST_SYS", "/sys", combineWith...)
  295. }
  296. func HostEtc(combineWith ...string) string {
  297. return GetEnv("HOST_ETC", "/etc", combineWith...)
  298. }
  299. func HostVar(combineWith ...string) string {
  300. return GetEnv("HOST_VAR", "/var", combineWith...)
  301. }
  302. func HostRun(combineWith ...string) string {
  303. return GetEnv("HOST_RUN", "/run", combineWith...)
  304. }
  305. func HostDev(combineWith ...string) string {
  306. return GetEnv("HOST_DEV", "/dev", combineWith...)
  307. }
  308. // getSysctrlEnv sets LC_ALL=C in a list of env vars for use when running
  309. // sysctl commands (see DoSysctrl).
  310. func getSysctrlEnv(env []string) []string {
  311. foundLC := false
  312. for i, line := range env {
  313. if strings.HasPrefix(line, "LC_ALL") {
  314. env[i] = "LC_ALL=C"
  315. foundLC = true
  316. }
  317. }
  318. if !foundLC {
  319. env = append(env, "LC_ALL=C")
  320. }
  321. return env
  322. }