docker.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package worker
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. type dockerHook struct {
  7. emptyHook
  8. provider mirrorProvider
  9. image string
  10. volumes []string
  11. options []string
  12. }
  13. func newDockerHook(p mirrorProvider, gCfg dockerConfig, mCfg mirrorConfig) *dockerHook {
  14. volumes := []string{}
  15. volumes = append(volumes, gCfg.Volumes...)
  16. volumes = append(volumes, mCfg.DockerVolumes...)
  17. options := []string{}
  18. options = append(options, gCfg.Options...)
  19. options = append(options, mCfg.DockerOptions...)
  20. return &dockerHook{
  21. provider: p,
  22. image: mCfg.DockerImage,
  23. volumes: volumes,
  24. options: options,
  25. }
  26. }
  27. func (d *dockerHook) preExec() error {
  28. p := d.provider
  29. logDir := p.LogDir()
  30. logFile := p.LogFile()
  31. workingDir := p.WorkingDir()
  32. if _, err := os.Stat(workingDir); os.IsNotExist(err) {
  33. logger.Debugf("Making dir %s", workingDir)
  34. if err = os.MkdirAll(workingDir, 0755); err != nil {
  35. return fmt.Errorf("Error making dir %s: %s", workingDir, err.Error())
  36. }
  37. }
  38. // Override workingDir
  39. ctx := p.EnterContext()
  40. ctx.Set(
  41. "volumes", []string{
  42. fmt.Sprintf("%s:%s", logDir, logDir),
  43. fmt.Sprintf("%s:%s", logFile, logFile),
  44. fmt.Sprintf("%s:%s", workingDir, workingDir),
  45. },
  46. )
  47. return nil
  48. }
  49. func (d *dockerHook) postExec() error {
  50. // sh.Command(
  51. // "docker", "rm", "-f", d.Name(),
  52. // ).Run()
  53. d.provider.ExitContext()
  54. return nil
  55. }
  56. // Volumes returns the configured volumes and
  57. // runtime-needed volumes, including mirror dirs
  58. // and log files
  59. func (d *dockerHook) Volumes() []string {
  60. vols := make([]string, len(d.volumes))
  61. copy(vols, d.volumes)
  62. p := d.provider
  63. ctx := p.Context()
  64. if ivs, ok := ctx.Get("volumes"); ok {
  65. vs := ivs.([]string)
  66. vols = append(vols, vs...)
  67. }
  68. return vols
  69. }
  70. func (d *dockerHook) LogFile() string {
  71. p := d.provider
  72. ctx := p.Context()
  73. if iv, ok := ctx.Get(_LogFileKey + ":docker"); ok {
  74. v := iv.(string)
  75. return v
  76. }
  77. return p.LogFile()
  78. }
  79. func (d *dockerHook) Name() string {
  80. p := d.provider
  81. return "tunasync-job-" + p.Name()
  82. }