linux_parser.go 10 KB

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