util.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package util
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "strings"
  11. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  12. log "github.com/Sirupsen/logrus"
  13. )
  14. const (
  15. DOCKER_CGROUPS_FILE = "/proc/self/cgroup"
  16. )
  17. type AnyMap map[interface{}]interface{}
  18. func Contains(values []string, value string) bool {
  19. if len(value) == 0 {
  20. return false
  21. }
  22. for _, i := range values {
  23. if i == value {
  24. return true
  25. }
  26. }
  27. return false
  28. }
  29. type ReturnsErr func() error
  30. func FileCopy(src, dest string) error {
  31. data, err := ioutil.ReadFile(src)
  32. if err != nil {
  33. return err
  34. }
  35. return WriteFileAtomic(dest, data, 0666)
  36. }
  37. func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error {
  38. dir, file := path.Split(filename)
  39. tempFile, err := ioutil.TempFile(dir, fmt.Sprintf(".%s", file))
  40. if err != nil {
  41. return err
  42. }
  43. defer os.Remove(tempFile.Name())
  44. if _, err := tempFile.Write(data); err != nil {
  45. return err
  46. }
  47. if err := tempFile.Close(); err != nil {
  48. return err
  49. }
  50. if err := os.Chmod(tempFile.Name(), perm); err != nil {
  51. return err
  52. }
  53. return os.Rename(tempFile.Name(), filename)
  54. }
  55. func Convert(from, to interface{}) error {
  56. bytes, err := yaml.Marshal(from)
  57. if err != nil {
  58. log.WithFields(log.Fields{"from": from, "err": err}).Warn("Error serializing to YML")
  59. return err
  60. }
  61. return yaml.Unmarshal(bytes, to)
  62. }
  63. func ConvertIgnoreOmitEmpty(from, to interface{}) error {
  64. var buffer bytes.Buffer
  65. encoder := yaml.NewEncoder(&buffer)
  66. encoder.IgnoreOmitEmpty = true
  67. if err := encoder.Encode(from); err != nil {
  68. return err
  69. }
  70. decoder := yaml.NewDecoder(&buffer)
  71. if err := decoder.Decode(to); err != nil {
  72. return err
  73. }
  74. return nil
  75. }
  76. func Copy(d interface{}) interface{} {
  77. switch d := d.(type) {
  78. case map[interface{}]interface{}:
  79. return MapCopy(d)
  80. case []interface{}:
  81. return SliceCopy(d)
  82. default:
  83. return d
  84. }
  85. }
  86. func Merge(left, right map[interface{}]interface{}) map[interface{}]interface{} {
  87. result := MapCopy(left)
  88. for k, r := range right {
  89. if l, ok := left[k]; ok {
  90. switch l := l.(type) {
  91. case map[interface{}]interface{}:
  92. switch r := r.(type) {
  93. case map[interface{}]interface{}:
  94. result[k] = Merge(l, r)
  95. default:
  96. result[k] = r
  97. }
  98. default:
  99. result[k] = r
  100. }
  101. } else {
  102. result[k] = Copy(r)
  103. }
  104. }
  105. return result
  106. }
  107. func MapCopy(data map[interface{}]interface{}) map[interface{}]interface{} {
  108. result := map[interface{}]interface{}{}
  109. for k, v := range data {
  110. result[k] = Copy(v)
  111. }
  112. return result
  113. }
  114. func SliceCopy(data []interface{}) []interface{} {
  115. result := make([]interface{}, len(data), len(data))
  116. for k, v := range data {
  117. result[k] = Copy(v)
  118. }
  119. return result
  120. }
  121. func RemoveString(slice []string, s string) []string {
  122. result := []string{}
  123. for _, elem := range slice {
  124. if elem != s {
  125. result = append(result, elem)
  126. }
  127. }
  128. return result
  129. }
  130. func ToStrings(data []interface{}) []string {
  131. result := make([]string, len(data), len(data))
  132. for k, v := range data {
  133. result[k] = v.(string)
  134. }
  135. return result
  136. }
  137. func Map2KVPairs(m map[string]string) []string {
  138. r := make([]string, 0, len(m))
  139. for k, v := range m {
  140. r = append(r, k+"="+v)
  141. }
  142. return r
  143. }
  144. func KVPairs2Map(kvs []string) map[string]string {
  145. r := make(map[string]string, len(kvs))
  146. for _, kv := range kvs {
  147. s := strings.SplitN(kv, "=", 2)
  148. r[s[0]] = s[1]
  149. }
  150. return r
  151. }
  152. func TrimSplitN(str, sep string, count int) []string {
  153. result := []string{}
  154. for _, part := range strings.SplitN(strings.TrimSpace(str), sep, count) {
  155. result = append(result, strings.TrimSpace(part))
  156. }
  157. return result
  158. }
  159. func TrimSplit(str, sep string) []string {
  160. return TrimSplitN(str, sep, -1)
  161. }
  162. func GetCurrentContainerId() (string, error) {
  163. file, err := os.Open(DOCKER_CGROUPS_FILE)
  164. if err != nil {
  165. return "", err
  166. }
  167. fileReader := bufio.NewScanner(file)
  168. if !fileReader.Scan() {
  169. return "", errors.New("Empty file /proc/self/cgroup")
  170. }
  171. line := fileReader.Text()
  172. parts := strings.Split(line, "/")
  173. for len(parts) != 3 {
  174. if !fileReader.Scan() {
  175. return "", errors.New("Found no docker cgroups")
  176. }
  177. line = fileReader.Text()
  178. parts = strings.Split(line, "/")
  179. if len(parts) == 3 {
  180. if strings.HasSuffix(parts[1], "docker") {
  181. break
  182. } else {
  183. parts = nil
  184. }
  185. }
  186. }
  187. return parts[len(parts)-1:][0], nil
  188. }
  189. func UnescapeKernelParams(s string) string {
  190. s = strings.Replace(s, `\"`, `"`, -1)
  191. s = strings.Replace(s, `\'`, `'`, -1)
  192. return s
  193. }
  194. func ExistsAndExecutable(path string) bool {
  195. info, err := os.Stat(path)
  196. if err != nil {
  197. return false
  198. }
  199. mode := info.Mode().Perm()
  200. return mode&os.ModePerm != 0
  201. }