plugin.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. fifoPath: filepath.Join(root, id),
  53. logInfo: logCtx,
  54. }
  55. cap, err := a.plugin.Capabilities()
  56. if err == nil {
  57. a.capabilities = cap
  58. }
  59. stream, err := openPluginStream(a)
  60. if err != nil {
  61. return nil, err
  62. }
  63. a.stream = stream
  64. a.enc = logdriver.NewLogEntryEncoder(a.stream)
  65. if err := l.StartLogging(strings.TrimPrefix(a.fifoPath, basePath), logCtx); err != nil {
  66. return nil, errors.Wrapf(err, "error creating logger")
  67. }
  68. if cap.ReadLogs {
  69. return &pluginAdapterWithRead{a}, nil
  70. }
  71. return a, nil
  72. }
  73. }