docker.go 1.9 KB

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