common.go 8.2 KB

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