util.go 5.4 KB

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