plugin.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package logger
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/docker/docker/api/types/plugins/logdriver"
  9. getter "github.com/docker/docker/pkg/plugingetter"
  10. "github.com/docker/docker/pkg/stringid"
  11. "github.com/pkg/errors"
  12. )
  13. var pluginGetter getter.PluginGetter
  14. const extName = "LogDriver"
  15. // logPlugin defines the available functions that logging plugins must implement.
  16. type logPlugin interface {
  17. StartLogging(streamPath string, info Info) (err error)
  18. StopLogging(streamPath string) (err error)
  19. Capabilities() (cap Capability, err error)
  20. ReadLogs(info Info, config ReadConfig) (stream io.ReadCloser, err error)
  21. }
  22. // RegisterPluginGetter sets the plugingetter
  23. func RegisterPluginGetter(plugingetter getter.PluginGetter) {
  24. pluginGetter = plugingetter
  25. }
  26. // GetDriver returns a logging driver by its name.
  27. // If the driver is empty, it looks for the local driver.
  28. func getPlugin(name string, mode int) (Creator, error) {
  29. p, err := pluginGetter.Get(name, extName, mode)
  30. if err != nil {
  31. return nil, fmt.Errorf("error looking up logging plugin %s: %v", name, err)
  32. }
  33. d := &logPluginProxy{p.Client()}
  34. return makePluginCreator(name, d, p.BasePath()), nil
  35. }
  36. func makePluginCreator(name string, l *logPluginProxy, basePath string) Creator {
  37. return func(logCtx Info) (logger Logger, err error) {
  38. defer func() {
  39. if err != nil {
  40. pluginGetter.Get(name, extName, getter.Release)
  41. }
  42. }()
  43. root := filepath.Join(basePath, "run", "docker", "logging")
  44. if err := os.MkdirAll(root, 0700); err != nil {
  45. return nil, err
  46. }
  47. id := stringid.GenerateNonCryptoID()
  48. a := &pluginAdapter{
  49. driverName: name,
  50. id: id,
  51. plugin: l,
  52. basePath: basePath,
  53. fifoPath: filepath.Join(root, id),
  54. logInfo: logCtx,
  55. }
  56. cap, err := a.plugin.Capabilities()
  57. if err == nil {
  58. a.capabilities = cap
  59. }
  60. stream, err := openPluginStream(a)
  61. if err != nil {
  62. return nil, err
  63. }
  64. a.stream = stream
  65. a.enc = logdriver.NewLogEntryEncoder(a.stream)
  66. if err := l.StartLogging(strings.TrimPrefix(a.fifoPath, basePath), logCtx); err != nil {
  67. return nil, errors.Wrapf(err, "error creating logger")
  68. }
  69. if cap.ReadLogs {
  70. return &pluginAdapterWithRead{a}, nil
  71. }
  72. return a, nil
  73. }
  74. }