util.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. if err := decoder.Decode(to); err != nil {
  74. return err
  75. }
  76. return nil
  77. }
  78. func Copy(d interface{}) interface{} {
  79. switch d := d.(type) {
  80. case map[interface{}]interface{}:
  81. return MapCopy(d)
  82. case []interface{}:
  83. return SliceCopy(d)
  84. default:
  85. return d
  86. }
  87. }
  88. func Merge(left, right map[interface{}]interface{}) map[interface{}]interface{} {
  89. result := MapCopy(left)
  90. for k, r := range right {
  91. if l, ok := left[k]; ok {
  92. switch l := l.(type) {
  93. case map[interface{}]interface{}:
  94. switch r := r.(type) {
  95. case map[interface{}]interface{}:
  96. result[k] = Merge(l, r)
  97. default:
  98. result[k] = r
  99. }
  100. default:
  101. result[k] = r
  102. }
  103. } else {
  104. result[k] = Copy(r)
  105. }
  106. }
  107. return result
  108. }
  109. func MapCopy(data map[interface{}]interface{}) map[interface{}]interface{} {
  110. result := map[interface{}]interface{}{}
  111. for k, v := range data {
  112. result[k] = Copy(v)
  113. }
  114. return result
  115. }
  116. func SliceCopy(data []interface{}) []interface{} {
  117. result := make([]interface{}, len(data), len(data))
  118. for k, v := range data {
  119. result[k] = Copy(v)
  120. }
  121. return result
  122. }
  123. func RemoveString(slice []string, s string) []string {
  124. result := []string{}
  125. for _, elem := range slice {
  126. if elem != s {
  127. result = append(result, elem)
  128. }
  129. }
  130. return result
  131. }
  132. func ToStrings(data []interface{}) []string {
  133. result := make([]string, len(data), len(data))
  134. for k, v := range data {
  135. result[k] = v.(string)
  136. }
  137. return result
  138. }
  139. func Map2KVPairs(m map[string]string) []string {
  140. r := make([]string, 0, len(m))
  141. for k, v := range m {
  142. r = append(r, k+"="+v)
  143. }
  144. return r
  145. }
  146. func KVPairs2Map(kvs []string) map[string]string {
  147. r := make(map[string]string, len(kvs))
  148. for _, kv := range kvs {
  149. s := strings.SplitN(kv, "=", 2)
  150. r[s[0]] = s[1]
  151. }
  152. return r
  153. }
  154. func TrimSplitN(str, sep string, count int) []string {
  155. result := []string{}
  156. for _, part := range strings.SplitN(strings.TrimSpace(str), sep, count) {
  157. result = append(result, strings.TrimSpace(part))
  158. }
  159. return result
  160. }
  161. func TrimSplit(str, sep string) []string {
  162. return TrimSplitN(str, sep, -1)
  163. }
  164. func GetCurrentContainerID() (string, error) {
  165. file, err := os.Open(dockerCgroupsFile)
  166. if err != nil {
  167. return "", err
  168. }
  169. fileReader := bufio.NewScanner(file)
  170. if !fileReader.Scan() {
  171. return "", errors.New("Empty file /proc/self/cgroup")
  172. }
  173. line := fileReader.Text()
  174. parts := strings.Split(line, "/")
  175. for len(parts) != 3 {
  176. if !fileReader.Scan() {
  177. return "", errors.New("Found no docker cgroups")
  178. }
  179. line = fileReader.Text()
  180. parts = strings.Split(line, "/")
  181. if len(parts) == 3 {
  182. if strings.HasSuffix(parts[1], "docker") {
  183. break
  184. } else {
  185. parts = nil
  186. }
  187. }
  188. }
  189. return parts[len(parts)-1:][0], nil
  190. }
  191. func UnescapeKernelParams(s string) string {
  192. s = strings.Replace(s, `\"`, `"`, -1)
  193. s = strings.Replace(s, `\'`, `'`, -1)
  194. return s
  195. }
  196. func ExistsAndExecutable(path string) bool {
  197. info, err := os.Stat(path)
  198. if err != nil {
  199. return false
  200. }
  201. mode := info.Mode().Perm()
  202. return mode&os.ModePerm != 0
  203. }
  204. func RunScript(path string) error {
  205. if !ExistsAndExecutable(path) {
  206. return nil
  207. }
  208. script, err := os.Open(path)
  209. if err != nil {
  210. return err
  211. }
  212. magic := make([]byte, 2)
  213. if _, err = script.Read(magic); err != nil {
  214. return err
  215. }
  216. cmd := exec.Command("/bin/sh", path)
  217. if string(magic) == "#!" {
  218. cmd = exec.Command(path)
  219. }
  220. cmd.Stdout = os.Stdout
  221. cmd.Stderr = os.Stderr
  222. return cmd.Run()
  223. }
  224. func RunCommandSequence(commandSequence []osYaml.StringandSlice) {
  225. for _, command := range commandSequence {
  226. var cmd *exec.Cmd
  227. if command.StringValue != "" {
  228. cmd = exec.Command("sh", "-c", command.StringValue)
  229. } else if len(command.SliceValue) > 0 {
  230. cmd = exec.Command(command.SliceValue[0], command.SliceValue[1:]...)
  231. } else {
  232. continue
  233. }
  234. cmd.Stdout = os.Stdout
  235. cmd.Stderr = os.Stderr
  236. if err := cmd.Run(); err != nil {
  237. log.Errorf("Failed to run %s: %v", command, err)
  238. }
  239. }
  240. }