metrics_unix.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // +build !windows
  2. package daemon
  3. import (
  4. "net"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "github.com/Sirupsen/logrus"
  9. "github.com/docker/docker/pkg/mount"
  10. "github.com/docker/docker/pkg/plugingetter"
  11. "github.com/docker/docker/pkg/plugins"
  12. metrics "github.com/docker/go-metrics"
  13. "github.com/pkg/errors"
  14. "golang.org/x/sys/unix"
  15. )
  16. func (daemon *Daemon) listenMetricsSock() (string, error) {
  17. path := filepath.Join(daemon.configStore.ExecRoot, "metrics.sock")
  18. unix.Unlink(path)
  19. l, err := net.Listen("unix", path)
  20. if err != nil {
  21. return "", errors.Wrap(err, "error setting up metrics plugin listener")
  22. }
  23. mux := http.NewServeMux()
  24. mux.Handle("/metrics", metrics.Handler())
  25. go func() {
  26. http.Serve(l, mux)
  27. }()
  28. daemon.metricsPluginListener = l
  29. return path, nil
  30. }
  31. func registerMetricsPluginCallback(getter plugingetter.PluginGetter, sockPath string) {
  32. getter.Handle(metricsPluginType, func(name string, client *plugins.Client) {
  33. // Use lookup since nothing in the system can really reference it, no need
  34. // to protect against removal
  35. p, err := getter.Get(name, metricsPluginType, plugingetter.Lookup)
  36. if err != nil {
  37. return
  38. }
  39. mp := metricsPlugin{p}
  40. sockBase := mp.sockBase()
  41. if err := os.MkdirAll(sockBase, 0755); err != nil {
  42. logrus.WithError(err).WithField("name", name).WithField("path", sockBase).Error("error creating metrics plugin base path")
  43. return
  44. }
  45. defer func() {
  46. if err != nil {
  47. os.RemoveAll(sockBase)
  48. }
  49. }()
  50. pluginSockPath := filepath.Join(sockBase, mp.sock())
  51. _, err = os.Stat(pluginSockPath)
  52. if err == nil {
  53. mount.Unmount(pluginSockPath)
  54. } else {
  55. logrus.WithField("path", pluginSockPath).Debugf("creating plugin socket")
  56. f, err := os.OpenFile(pluginSockPath, os.O_CREATE, 0600)
  57. if err != nil {
  58. return
  59. }
  60. f.Close()
  61. }
  62. if err := mount.Mount(sockPath, pluginSockPath, "none", "bind,ro"); err != nil {
  63. logrus.WithError(err).WithField("name", name).Error("could not mount metrics socket to plugin")
  64. return
  65. }
  66. if err := pluginStartMetricsCollection(p); err != nil {
  67. if err := mount.Unmount(pluginSockPath); err != nil {
  68. if mounted, _ := mount.Mounted(pluginSockPath); mounted {
  69. logrus.WithError(err).WithField("sock_path", pluginSockPath).Error("error unmounting metrics socket from plugin during cleanup")
  70. }
  71. }
  72. logrus.WithError(err).WithField("name", name).Error("error while initializing metrics plugin")
  73. }
  74. })
  75. }