linux_parser.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. package mounts // import "github.com/docker/docker/volume/mounts"
  2. import (
  3. "errors"
  4. "fmt"
  5. "path"
  6. "path/filepath"
  7. "strings"
  8. "github.com/docker/docker/api/types/mount"
  9. "github.com/docker/docker/pkg/stringid"
  10. "github.com/docker/docker/volume"
  11. )
  12. type linuxParser struct {
  13. }
  14. func linuxSplitRawSpec(raw string) ([]string, error) {
  15. if strings.Count(raw, ":") > 2 {
  16. return nil, errInvalidSpec(raw)
  17. }
  18. arr := strings.SplitN(raw, ":", 3)
  19. if arr[0] == "" {
  20. return nil, errInvalidSpec(raw)
  21. }
  22. return arr, nil
  23. }
  24. func linuxValidateNotRoot(p string) error {
  25. p = path.Clean(strings.Replace(p, `\`, `/`, -1))
  26. if p == "/" {
  27. return ErrVolumeTargetIsRoot
  28. }
  29. return nil
  30. }
  31. func linuxValidateAbsolute(p string) error {
  32. p = strings.Replace(p, `\`, `/`, -1)
  33. if path.IsAbs(p) {
  34. return nil
  35. }
  36. return fmt.Errorf("invalid mount path: '%s' mount path must be absolute", p)
  37. }
  38. func (p *linuxParser) ValidateMountConfig(mnt *mount.Mount) error {
  39. // there was something looking like a bug in existing codebase:
  40. // - validateMountConfig on linux was called with options skipping bind source existence when calling ParseMountRaw
  41. // - but not when calling ParseMountSpec directly... nor when the unit test called it directly
  42. return p.validateMountConfigImpl(mnt, true)
  43. }
  44. func (p *linuxParser) validateMountConfigImpl(mnt *mount.Mount, validateBindSourceExists bool) error {
  45. if len(mnt.Target) == 0 {
  46. return &errMountConfig{mnt, errMissingField("Target")}
  47. }
  48. if err := linuxValidateNotRoot(mnt.Target); err != nil {
  49. return &errMountConfig{mnt, err}
  50. }
  51. if err := linuxValidateAbsolute(mnt.Target); err != nil {
  52. return &errMountConfig{mnt, err}
  53. }
  54. switch mnt.Type {
  55. case mount.TypeBind:
  56. if len(mnt.Source) == 0 {
  57. return &errMountConfig{mnt, errMissingField("Source")}
  58. }
  59. // Don't error out just because the propagation mode is not supported on the platform
  60. if opts := mnt.BindOptions; opts != nil {
  61. if len(opts.Propagation) > 0 && len(linuxPropagationModes) > 0 {
  62. if _, ok := linuxPropagationModes[opts.Propagation]; !ok {
  63. return &errMountConfig{mnt, fmt.Errorf("invalid propagation mode: %s", opts.Propagation)}
  64. }
  65. }
  66. }
  67. if mnt.VolumeOptions != nil {
  68. return &errMountConfig{mnt, errExtraField("VolumeOptions")}
  69. }
  70. if err := linuxValidateAbsolute(mnt.Source); err != nil {
  71. return &errMountConfig{mnt, err}
  72. }
  73. if validateBindSourceExists {
  74. exists, _, _ := currentFileInfoProvider.fileInfo(mnt.Source)
  75. if !exists {
  76. return &errMountConfig{mnt, errBindSourceDoesNotExist(mnt.Source)}
  77. }
  78. }
  79. case mount.TypeVolume:
  80. if mnt.BindOptions != nil {
  81. return &errMountConfig{mnt, errExtraField("BindOptions")}
  82. }
  83. if len(mnt.Source) == 0 && mnt.ReadOnly {
  84. return &errMountConfig{mnt, fmt.Errorf("must not set ReadOnly mode when using anonymous volumes")}
  85. }
  86. case mount.TypeTmpfs:
  87. if mnt.BindOptions != nil {
  88. return &errMountConfig{mnt, errExtraField("BindOptions")}
  89. }
  90. if len(mnt.Source) != 0 {
  91. return &errMountConfig{mnt, errExtraField("Source")}
  92. }
  93. if _, err := p.ConvertTmpfsOptions(mnt.TmpfsOptions, mnt.ReadOnly); err != nil {
  94. return &errMountConfig{mnt, err}
  95. }
  96. default:
  97. return &errMountConfig{mnt, errors.New("mount type unknown")}
  98. }
  99. return nil
  100. }
  101. // read-write modes
  102. var rwModes = map[string]bool{
  103. "rw": true,
  104. "ro": true,
  105. }
  106. // label modes
  107. var linuxLabelModes = map[string]bool{
  108. "Z": true,
  109. "z": true,
  110. }
  111. // consistency modes
  112. var linuxConsistencyModes = map[mount.Consistency]bool{
  113. mount.ConsistencyFull: true,
  114. mount.ConsistencyCached: true,
  115. mount.ConsistencyDelegated: true,
  116. }
  117. var linuxPropagationModes = map[mount.Propagation]bool{
  118. mount.PropagationPrivate: true,
  119. mount.PropagationRPrivate: true,
  120. mount.PropagationSlave: true,
  121. mount.PropagationRSlave: true,
  122. mount.PropagationShared: true,
  123. mount.PropagationRShared: true,
  124. }
  125. const linuxDefaultPropagationMode = mount.PropagationRPrivate
  126. func linuxGetPropagation(mode string) mount.Propagation {
  127. for _, o := range strings.Split(mode, ",") {
  128. prop := mount.Propagation(o)
  129. if linuxPropagationModes[prop] {
  130. return prop
  131. }
  132. }
  133. return linuxDefaultPropagationMode
  134. }
  135. func linuxHasPropagation(mode string) bool {
  136. for _, o := range strings.Split(mode, ",") {
  137. if linuxPropagationModes[mount.Propagation(o)] {
  138. return true
  139. }
  140. }
  141. return false
  142. }
  143. func linuxValidMountMode(mode string) bool {
  144. if mode == "" {
  145. return true
  146. }
  147. rwModeCount := 0
  148. labelModeCount := 0
  149. propagationModeCount := 0
  150. copyModeCount := 0
  151. consistencyModeCount := 0
  152. for _, o := range strings.Split(mode, ",") {
  153. switch {
  154. case rwModes[o]:
  155. rwModeCount++
  156. case linuxLabelModes[o]:
  157. labelModeCount++
  158. case linuxPropagationModes[mount.Propagation(o)]:
  159. propagationModeCount++
  160. case copyModeExists(o):
  161. copyModeCount++
  162. case linuxConsistencyModes[mount.Consistency(o)]:
  163. consistencyModeCount++
  164. default:
  165. return false
  166. }
  167. }
  168. // Only one string for each mode is allowed.
  169. if rwModeCount > 1 || labelModeCount > 1 || propagationModeCount > 1 || copyModeCount > 1 || consistencyModeCount > 1 {
  170. return false
  171. }
  172. return true
  173. }
  174. func (p *linuxParser) ReadWrite(mode string) bool {
  175. if !linuxValidMountMode(mode) {
  176. return false
  177. }
  178. for _, o := range strings.Split(mode, ",") {
  179. if o == "ro" {
  180. return false
  181. }
  182. }
  183. return true
  184. }
  185. func (p *linuxParser) ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) {
  186. arr, err := linuxSplitRawSpec(raw)
  187. if err != nil {
  188. return nil, err
  189. }
  190. var spec mount.Mount
  191. var mode string
  192. switch len(arr) {
  193. case 1:
  194. // Just a destination path in the container
  195. spec.Target = arr[0]
  196. case 2:
  197. if linuxValidMountMode(arr[1]) {
  198. // Destination + Mode is not a valid volume - volumes
  199. // cannot include a mode. e.g. /foo:rw
  200. return nil, errInvalidSpec(raw)
  201. }
  202. // Host Source Path or Name + Destination
  203. spec.Source = arr[0]
  204. spec.Target = arr[1]
  205. case 3:
  206. // HostSourcePath+DestinationPath+Mode
  207. spec.Source = arr[0]
  208. spec.Target = arr[1]
  209. mode = arr[2]
  210. default:
  211. return nil, errInvalidSpec(raw)
  212. }
  213. if !linuxValidMountMode(mode) {
  214. return nil, errInvalidMode(mode)
  215. }
  216. if path.IsAbs(spec.Source) {
  217. spec.Type = mount.TypeBind
  218. } else {
  219. spec.Type = mount.TypeVolume
  220. }
  221. spec.ReadOnly = !p.ReadWrite(mode)
  222. // cannot assume that if a volume driver is passed in that we should set it
  223. if volumeDriver != "" && spec.Type == mount.TypeVolume {
  224. spec.VolumeOptions = &mount.VolumeOptions{
  225. DriverConfig: &mount.Driver{Name: volumeDriver},
  226. }
  227. }
  228. if copyData, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  229. if spec.VolumeOptions == nil {
  230. spec.VolumeOptions = &mount.VolumeOptions{}
  231. }
  232. spec.VolumeOptions.NoCopy = !copyData
  233. }
  234. if linuxHasPropagation(mode) {
  235. spec.BindOptions = &mount.BindOptions{
  236. Propagation: linuxGetPropagation(mode),
  237. }
  238. }
  239. mp, err := p.parseMountSpec(spec, false)
  240. if mp != nil {
  241. mp.Mode = mode
  242. }
  243. if err != nil {
  244. err = fmt.Errorf("%v: %v", errInvalidSpec(raw), err)
  245. }
  246. return mp, err
  247. }
  248. func (p *linuxParser) ParseMountSpec(cfg mount.Mount) (*MountPoint, error) {
  249. return p.parseMountSpec(cfg, true)
  250. }
  251. func (p *linuxParser) parseMountSpec(cfg mount.Mount, validateBindSourceExists bool) (*MountPoint, error) {
  252. if err := p.validateMountConfigImpl(&cfg, validateBindSourceExists); err != nil {
  253. return nil, err
  254. }
  255. mp := &MountPoint{
  256. RW: !cfg.ReadOnly,
  257. Destination: path.Clean(filepath.ToSlash(cfg.Target)),
  258. Type: cfg.Type,
  259. Spec: cfg,
  260. }
  261. switch cfg.Type {
  262. case mount.TypeVolume:
  263. if cfg.Source == "" {
  264. mp.Name = stringid.GenerateNonCryptoID()
  265. } else {
  266. mp.Name = cfg.Source
  267. }
  268. mp.CopyData = p.DefaultCopyMode()
  269. if cfg.VolumeOptions != nil {
  270. if cfg.VolumeOptions.DriverConfig != nil {
  271. mp.Driver = cfg.VolumeOptions.DriverConfig.Name
  272. }
  273. if cfg.VolumeOptions.NoCopy {
  274. mp.CopyData = false
  275. }
  276. }
  277. case mount.TypeBind:
  278. mp.Source = path.Clean(filepath.ToSlash(cfg.Source))
  279. if cfg.BindOptions != nil && len(cfg.BindOptions.Propagation) > 0 {
  280. mp.Propagation = cfg.BindOptions.Propagation
  281. } else {
  282. // If user did not specify a propagation mode, get
  283. // default propagation mode.
  284. mp.Propagation = linuxDefaultPropagationMode
  285. }
  286. case mount.TypeTmpfs:
  287. // NOP
  288. }
  289. return mp, nil
  290. }
  291. func (p *linuxParser) ParseVolumesFrom(spec string) (string, string, error) {
  292. if len(spec) == 0 {
  293. return "", "", fmt.Errorf("volumes-from specification cannot be an empty string")
  294. }
  295. specParts := strings.SplitN(spec, ":", 2)
  296. id := specParts[0]
  297. mode := "rw"
  298. if len(specParts) == 2 {
  299. mode = specParts[1]
  300. if !linuxValidMountMode(mode) {
  301. return "", "", errInvalidMode(mode)
  302. }
  303. // For now don't allow propagation properties while importing
  304. // volumes from data container. These volumes will inherit
  305. // the same propagation property as of the original volume
  306. // in data container. This probably can be relaxed in future.
  307. if linuxHasPropagation(mode) {
  308. return "", "", errInvalidMode(mode)
  309. }
  310. // Do not allow copy modes on volumes-from
  311. if _, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  312. return "", "", errInvalidMode(mode)
  313. }
  314. }
  315. return id, mode, nil
  316. }
  317. func (p *linuxParser) DefaultPropagationMode() mount.Propagation {
  318. return linuxDefaultPropagationMode
  319. }
  320. func (p *linuxParser) ConvertTmpfsOptions(opt *mount.TmpfsOptions, readOnly bool) (string, error) {
  321. var rawOpts []string
  322. if readOnly {
  323. rawOpts = append(rawOpts, "ro")
  324. }
  325. if opt != nil && opt.Mode != 0 {
  326. rawOpts = append(rawOpts, fmt.Sprintf("mode=%o", opt.Mode))
  327. }
  328. if opt != nil && opt.SizeBytes != 0 {
  329. // calculate suffix here, making this linux specific, but that is
  330. // okay, since API is that way anyways.
  331. // we do this by finding the suffix that divides evenly into the
  332. // value, returning the value itself, with no suffix, if it fails.
  333. //
  334. // For the most part, we don't enforce any semantic to this values.
  335. // The operating system will usually align this and enforce minimum
  336. // and maximums.
  337. var (
  338. size = opt.SizeBytes
  339. suffix string
  340. )
  341. for _, r := range []struct {
  342. suffix string
  343. divisor int64
  344. }{
  345. {"g", 1 << 30},
  346. {"m", 1 << 20},
  347. {"k", 1 << 10},
  348. } {
  349. if size%r.divisor == 0 {
  350. size = size / r.divisor
  351. suffix = r.suffix
  352. break
  353. }
  354. }
  355. rawOpts = append(rawOpts, fmt.Sprintf("size=%d%s", size, suffix))
  356. }
  357. return strings.Join(rawOpts, ","), nil
  358. }
  359. func (p *linuxParser) DefaultCopyMode() bool {
  360. return true
  361. }
  362. func (p *linuxParser) ValidateVolumeName(name string) error {
  363. return nil
  364. }
  365. func (p *linuxParser) IsBackwardCompatible(m *MountPoint) bool {
  366. return len(m.Source) > 0 || m.Driver == volume.DefaultDriverName
  367. }
  368. func (p *linuxParser) ValidateTmpfsMountDestination(dest string) error {
  369. if err := linuxValidateNotRoot(dest); err != nil {
  370. return err
  371. }
  372. return linuxValidateAbsolute(dest)
  373. }