util.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package util
  2. import (
  3. "bufio"
  4. "bytes"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "strings"
  12. yaml "github.com/cloudfoundry-incubator/candiedyaml"
  13. osYaml "github.com/rancher/os/config/yaml"
  14. )
  15. const (
  16. dockerCgroupsFile = "/proc/self/cgroup"
  17. )
  18. type AnyMap map[interface{}]interface{}
  19. func Contains(values []string, value string) bool {
  20. if len(value) == 0 {
  21. return false
  22. }
  23. for _, i := range values {
  24. if i == value {
  25. return true
  26. }
  27. }
  28. return false
  29. }
  30. type ReturnsErr func() error
  31. func FileCopy(src, dest string) error {
  32. data, err := ioutil.ReadFile(src)
  33. if err != nil {
  34. return err
  35. }
  36. return WriteFileAtomic(dest, data, 0666)
  37. }
  38. func WriteFileAtomic(filename string, data []byte, perm os.FileMode) error {
  39. dir, file := path.Split(filename)
  40. tempFile, err := ioutil.TempFile(dir, fmt.Sprintf(".%s", file))
  41. if err != nil {
  42. return err
  43. }
  44. defer os.Remove(tempFile.Name())
  45. if _, err := tempFile.Write(data); err != nil {
  46. return err
  47. }
  48. if err := tempFile.Close(); err != nil {
  49. return err
  50. }
  51. if err := os.Chmod(tempFile.Name(), perm); err != nil {
  52. return err
  53. }
  54. return os.Rename(tempFile.Name(), filename)
  55. }
  56. func Convert(from, to interface{}) error {
  57. bytes, err := yaml.Marshal(from)
  58. if err != nil {
  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. return decoder.Decode(to)
  72. }
  73. func Copy(d interface{}) interface{} {
  74. switch d := d.(type) {
  75. case map[interface{}]interface{}:
  76. return MapCopy(d)
  77. case []interface{}:
  78. return SliceCopy(d)
  79. default:
  80. return d
  81. }
  82. }
  83. func Merge(left, right map[interface{}]interface{}) map[interface{}]interface{} {
  84. result := MapCopy(left)
  85. for k, r := range right {
  86. if l, ok := left[k]; ok {
  87. switch l := l.(type) {
  88. case map[interface{}]interface{}:
  89. switch r := r.(type) {
  90. case map[interface{}]interface{}:
  91. result[k] = Merge(l, r)
  92. default:
  93. result[k] = r
  94. }
  95. default:
  96. result[k] = r
  97. }
  98. } else {
  99. result[k] = Copy(r)
  100. }
  101. }
  102. return result
  103. }
  104. func MapCopy(data map[interface{}]interface{}) map[interface{}]interface{} {
  105. result := map[interface{}]interface{}{}
  106. for k, v := range data {
  107. result[k] = Copy(v)
  108. }
  109. return result
  110. }
  111. func SliceCopy(data []interface{}) []interface{} {
  112. result := make([]interface{}, len(data), len(data))
  113. for k, v := range data {
  114. result[k] = Copy(v)
  115. }
  116. return result
  117. }
  118. func RemoveString(slice []string, s string) []string {
  119. result := []string{}
  120. for _, elem := range slice {
  121. if elem != s {
  122. result = append(result, elem)
  123. }
  124. }
  125. return result
  126. }
  127. func ToStrings(data []interface{}) []string {
  128. result := make([]string, len(data), len(data))
  129. for k, v := range data {
  130. result[k] = v.(string)
  131. }
  132. return result
  133. }
  134. func Map2KVPairs(m map[string]string) []string {
  135. r := make([]string, 0, len(m))
  136. for k, v := range m {
  137. r = append(r, k+"="+v)
  138. }
  139. return r
  140. }
  141. func KVPairs2Map(kvs []string) map[string]string {
  142. r := make(map[string]string, len(kvs))
  143. for _, kv := range kvs {
  144. s := strings.SplitN(kv, "=", 2)
  145. r[s[0]] = s[1]
  146. }
  147. return r
  148. }
  149. func TrimSplitN(str, sep string, count int) []string {
  150. result := []string{}
  151. for _, part := range strings.SplitN(strings.TrimSpace(str), sep, count) {
  152. result = append(result, strings.TrimSpace(part))
  153. }
  154. return result
  155. }
  156. func TrimSplit(str, sep string) []string {
  157. return TrimSplitN(str, sep, -1)
  158. }
  159. func GetCurrentContainerID() (string, error) {
  160. file, err := os.Open(dockerCgroupsFile)
  161. if err != nil {
  162. return "", err
  163. }
  164. fileReader := bufio.NewScanner(file)
  165. if !fileReader.Scan() {
  166. return "", errors.New("Empty file /proc/self/cgroup")
  167. }
  168. line := fileReader.Text()
  169. parts := strings.Split(line, "/")
  170. for len(parts) != 3 {
  171. if !fileReader.Scan() {
  172. return "", errors.New("Found no docker cgroups")
  173. }
  174. line = fileReader.Text()
  175. parts = strings.Split(line, "/")
  176. if len(parts) == 3 {
  177. if strings.HasSuffix(parts[1], "docker") {
  178. break
  179. } else {
  180. parts = nil
  181. }
  182. }
  183. }
  184. return parts[len(parts)-1:][0], nil
  185. }
  186. func UnescapeKernelParams(s string) string {
  187. s = strings.Replace(s, `\"`, `"`, -1)
  188. s = strings.Replace(s, `\'`, `'`, -1)
  189. return s
  190. }
  191. func ExistsAndExecutable(path string) bool {
  192. info, err := os.Stat(path)
  193. if err != nil {
  194. return false
  195. }
  196. mode := info.Mode().Perm()
  197. return mode&os.ModePerm != 0
  198. }
  199. func RunScript(path string) error {
  200. if !ExistsAndExecutable(path) {
  201. return nil
  202. }
  203. script, err := os.Open(path)
  204. if err != nil {
  205. return err
  206. }
  207. magic := make([]byte, 2)
  208. if _, err = script.Read(magic); err != nil {
  209. return err
  210. }
  211. cmd := exec.Command("/bin/sh", path)
  212. if string(magic) == "#!" {
  213. cmd = exec.Command(path)
  214. }
  215. cmd.Stdout = os.Stdout
  216. cmd.Stderr = os.Stderr
  217. return cmd.Run()
  218. }
  219. func RunCommandSequence(commandSequence []osYaml.StringandSlice) error {
  220. for _, command := range commandSequence {
  221. var cmd *exec.Cmd
  222. if command.StringValue != "" {
  223. cmd = exec.Command("sh", "-c", command.StringValue)
  224. } else if len(command.SliceValue) > 0 {
  225. cmd = exec.Command(command.SliceValue[0], command.SliceValue[1:]...)
  226. } else {
  227. continue
  228. }
  229. cmd.Stdout = os.Stdout
  230. cmd.Stderr = os.Stderr
  231. if err := cmd.Run(); err != nil {
  232. return fmt.Errorf("Failed to run %s: %v", command, err)
  233. }
  234. }
  235. return nil
  236. }