mount.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package mountutils
  15. import (
  16. "context"
  17. "fmt"
  18. "os"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "yunion.io/x/log"
  23. "yunion.io/x/pkg/errors"
  24. "yunion.io/x/pkg/util/sets"
  25. "yunion.io/x/onecloud/pkg/util/fileutils2"
  26. "yunion.io/x/onecloud/pkg/util/procutils"
  27. )
  28. var (
  29. mountTimeout = 30 * time.Second
  30. )
  31. func mountWrap(mountPoint string, action func() error) error {
  32. if !fileutils2.Exists(mountPoint) {
  33. output, err := procutils.NewCommand("mkdir", "-p", mountPoint).Output()
  34. if err != nil {
  35. return errors.Wrapf(err, "mkdir %s failed: %s", mountPoint, output)
  36. }
  37. }
  38. if err := procutils.NewRemoteCommandAsFarAsPossible("mountpoint", mountPoint).Run(); err == nil {
  39. log.Warningf("mountpoint %s is already mounted", mountPoint)
  40. return nil
  41. }
  42. return action()
  43. }
  44. func Mount(devPath string, mountPoint string, fsType string) error {
  45. return mountWrap(mountPoint, func() error {
  46. ctx, cancel := context.WithTimeout(context.Background(), mountTimeout)
  47. defer cancel()
  48. if out, err := procutils.NewRemoteCommandContextAsFarAsPossible(ctx, "mount", "-t", fsType, devPath, mountPoint).Output(); err != nil {
  49. return errors.Wrapf(err, "mount %s to %s with fs %s: %s", devPath, mountPoint, fsType, string(out))
  50. }
  51. return nil
  52. })
  53. }
  54. func MountWithParams(devPath string, mountPoint string, fsType string, opts []string) error {
  55. return mountWrap(mountPoint, func() error {
  56. ctx, cancel := context.WithTimeout(context.Background(), mountTimeout)
  57. defer cancel()
  58. args := []string{"-t", fsType, devPath, mountPoint}
  59. args = append(args, opts...)
  60. if out, err := procutils.NewRemoteCommandContextAsFarAsPossible(ctx, "mount", args...).Output(); err != nil {
  61. return errors.Wrapf(err, "mount %s to %s with fs %s: %s", devPath, mountPoint, fsType, string(out))
  62. }
  63. return nil
  64. })
  65. }
  66. func MountOverlay(lowerDir []string, upperDir string, workDir string, mergedDir string) error {
  67. return mountOverlay(lowerDir, upperDir, workDir, mergedDir, nil)
  68. }
  69. type MountOverlayFeatures struct {
  70. MetaCopy bool
  71. }
  72. func MountOverlayWithFeatures(lowerDir []string, upperDir string, workDir string, mergedDir string, features *MountOverlayFeatures) error {
  73. return mountOverlay(lowerDir, upperDir, workDir, mergedDir, features)
  74. }
  75. func mountOverlay(lowerDir []string, upperDir string, workDir string, mergedDir string, features *MountOverlayFeatures) error {
  76. return mountWrap(mergedDir, func() error {
  77. ctx, cancel := context.WithTimeout(context.Background(), mountTimeout)
  78. defer cancel()
  79. optStr := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", strings.Join(lowerDir, ":"), upperDir, workDir)
  80. if features != nil {
  81. if features.MetaCopy {
  82. optStr += ",metacopy=on"
  83. }
  84. }
  85. optStr += ",index=off"
  86. overlayArgs := []string{"-t", "overlay", "overlay", "-o", optStr, mergedDir}
  87. if out, err := procutils.NewRemoteCommandContextAsFarAsPossible(ctx, "mount", overlayArgs...).Output(); err != nil {
  88. return errors.Wrapf(err, "mount %v: %s", overlayArgs, out)
  89. }
  90. return nil
  91. })
  92. }
  93. func MountBind(src, target string) error {
  94. return mountWrap(target, func() error {
  95. ctx, cancel := context.WithTimeout(context.Background(), mountTimeout)
  96. defer cancel()
  97. bindArgs := []string{"--bind", src, target}
  98. if out, err := procutils.NewRemoteCommandContextAsFarAsPossible(ctx, "mount", bindArgs...).Output(); err != nil {
  99. return errors.Wrapf(err, "mount %v: %s", bindArgs, out)
  100. }
  101. return nil
  102. })
  103. }
  104. func Unmount(mountPoint string, useLazy bool) error {
  105. err := unmount(mountPoint, useLazy)
  106. errs := []error{}
  107. if err != nil {
  108. errs = append(errs, errors.Wrap(err, "umount firstly"))
  109. if strings.Contains(err.Error(), "target is busy") {
  110. // use lsof to find process using this mountpoint and kill it
  111. if err := cleanProcessUseMountPoint(mountPoint); err != nil {
  112. errs = append(errs, errors.Wrapf(err, "clean process use mountpoint: %s", mountPoint))
  113. }
  114. // umount again
  115. if err := unmount(mountPoint, useLazy); err != nil {
  116. errs = append(errs, errors.Wrapf(err, "unmount %s after clean process using it", mountPoint))
  117. return errors.NewAggregate(errs)
  118. }
  119. return nil
  120. } else {
  121. return errors.NewAggregate(errs)
  122. }
  123. }
  124. return nil
  125. }
  126. func unmount(mountPoint string, useLazy bool) error {
  127. mountOut, err := procutils.NewRemoteCommandAsFarAsPossible("mountpoint", mountPoint).Output()
  128. if err == nil {
  129. args := []string{mountPoint}
  130. if useLazy {
  131. args = append([]string{"-l"}, args...)
  132. }
  133. out, err := procutils.NewRemoteCommandAsFarAsPossible("umount", args...).Output()
  134. if err != nil {
  135. //if strings.Contains(err.Error(), fmt.Sprintf("umount: %s", mountPoint)) && strings.Contains(err.Error(), "not mounted") {
  136. if strings.Contains(string(out), "not mounted") {
  137. // handle error like: 'umount: /opt/cloud/workspace/servers/2bc8dabf-88c7-448a-8f9e-cbf557acfde2/volumes/6a7ccfcc-a591-4cdd-8d3f-40fde1110870/data/data/com.douban.frodo/: not mounted.'
  138. return nil
  139. }
  140. return errors.Wrapf(err, "umount %s failed %s", mountPoint, out)
  141. }
  142. }
  143. if strings.Contains(string(mountOut), "No such file or directory") {
  144. return nil
  145. }
  146. if strings.Contains(string(mountOut), "not a mountpoint") {
  147. return nil
  148. }
  149. return errors.Wrapf(err, "check mountpoint %s: %s", mountPoint, string(mountOut))
  150. }
  151. func cleanProcessUseMountPoint(mountPoint string) error {
  152. devs, err := getMountPointDevices(mountPoint)
  153. if err != nil {
  154. return errors.Wrapf(err, "get mount point devices: %s", mountPoint)
  155. }
  156. errs := []error{}
  157. for _, dev := range devs {
  158. pids, err := useLsofFindDevProcess(dev)
  159. if err != nil {
  160. errs = append(errs, errors.Wrapf(err, "use lsof find device %q process", dev))
  161. }
  162. if len(pids) > 0 {
  163. if err := killProcess(pids); err != nil {
  164. errs = append(errs, errors.Wrapf(err, "kill process %q", pids))
  165. return errors.NewAggregate(errs)
  166. }
  167. } else {
  168. if err != nil {
  169. return errors.NewAggregate(errs)
  170. }
  171. }
  172. }
  173. return nil
  174. }
  175. func killProcess(pids []int) error {
  176. for _, pid := range pids {
  177. out, err := procutils.NewRemoteCommandAsFarAsPossible("kill", "-9", fmt.Sprintf("%d", pid)).Output()
  178. if err != nil {
  179. if strings.Contains(err.Error(), "No such process") {
  180. continue
  181. }
  182. return errors.Wrapf(err, "kill -9 %d: %s", pid, out)
  183. }
  184. }
  185. return nil
  186. }
  187. func useLsofFindDevProcess(dev string) ([]int, error) {
  188. out, err := procutils.NewRemoteCommandAsFarAsPossible("lsof", "+f", "--", dev).Output()
  189. if err != nil {
  190. err = errors.Wrapf(err, "'lsof +f -- %s' failed: %s", dev, out)
  191. if len(out) == 0 {
  192. return nil, err
  193. }
  194. }
  195. pids := sets.NewInt()
  196. for _, line := range strings.Split(string(out), "\n") {
  197. if strings.HasPrefix(line, "COMMAND") {
  198. continue
  199. }
  200. parts := strings.Split(line, " ")
  201. newParts := []string{}
  202. for _, part := range parts {
  203. if part != "" {
  204. newParts = append(newParts, part)
  205. }
  206. }
  207. if len(newParts) < 2 {
  208. continue
  209. }
  210. pid, err := strconv.Atoi(newParts[1])
  211. if err != nil {
  212. return nil, errors.Wrapf(err, "parse pid: %s", newParts[1])
  213. }
  214. log.Infof("find process %q use device %q", line, dev)
  215. pids.Insert(pid)
  216. }
  217. return pids.List(), err
  218. }
  219. func getMountPointDevices(mountPoint string) ([]string, error) {
  220. mountFile := "/proc/mounts"
  221. data, err := os.ReadFile(mountFile)
  222. if err != nil {
  223. return nil, errors.Wrapf(err, "read file %s", mountFile)
  224. }
  225. lines := strings.Split(string(data), "\n")
  226. devs := sets.NewString()
  227. for _, line := range lines {
  228. parts := strings.Split(line, " ")
  229. if len(parts) < 2 {
  230. continue
  231. }
  232. point := parts[1]
  233. if point != mountPoint {
  234. continue
  235. }
  236. seg1 := parts[0]
  237. var dev string
  238. switch seg1 {
  239. case "sysfs", "proc", "tmpfs", "overlay":
  240. dev = point
  241. default:
  242. dev = seg1
  243. }
  244. devs.Insert(dev)
  245. }
  246. return devs.List(), nil
  247. }
  248. func MakeShared(mountPoint string) error {
  249. out, err := procutils.NewRemoteCommandAsFarAsPossible("mount", "--make-shared", mountPoint).Output()
  250. if err != nil {
  251. return errors.Wrapf(err, "'mount --make-shared %s' failed: %s", mountPoint, out)
  252. }
  253. return nil
  254. }