util.go 5.6 KB

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