metrics_unix.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //go:build !windows
  2. package daemon // import "github.com/docker/docker/daemon"
  3. import (
  4. "net"
  5. "net/http"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. "github.com/docker/docker/pkg/plugingetter"
  10. "github.com/docker/docker/pkg/plugins"
  11. "github.com/docker/docker/plugin"
  12. metrics "github.com/docker/go-metrics"
  13. specs "github.com/opencontainers/runtime-spec/specs-go"
  14. "github.com/pkg/errors"
  15. "github.com/sirupsen/logrus"
  16. "golang.org/x/sys/unix"
  17. )
  18. func (daemon *Daemon) listenMetricsSock() (string, error) {
  19. path := filepath.Join(daemon.configStore.ExecRoot, "metrics.sock")
  20. unix.Unlink(path)
  21. l, err := net.Listen("unix", path)
  22. if err != nil {
  23. return "", errors.Wrap(err, "error setting up metrics plugin listener")
  24. }
  25. mux := http.NewServeMux()
  26. mux.Handle("/metrics", metrics.Handler())
  27. go func() {
  28. logrus.Debugf("metrics API listening on %s", l.Addr())
  29. srv := &http.Server{
  30. Handler: mux,
  31. ReadHeaderTimeout: 5 * time.Minute, // "G112: Potential Slowloris Attack (gosec)"; not a real concern for our use, so setting a long timeout.
  32. }
  33. if err := srv.Serve(l); err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
  34. logrus.WithError(err).Error("error serving metrics API")
  35. }
  36. }()
  37. daemon.metricsPluginListener = l
  38. return path, nil
  39. }
  40. func registerMetricsPluginCallback(store *plugin.Store, sockPath string) {
  41. store.RegisterRuntimeOpt(metricsPluginType, func(s *specs.Spec) {
  42. f := plugin.WithSpecMounts([]specs.Mount{
  43. {Type: "bind", Source: sockPath, Destination: "/run/docker/metrics.sock", Options: []string{"bind", "ro"}},
  44. })
  45. f(s)
  46. })
  47. store.Handle(metricsPluginType, func(name string, client *plugins.Client) {
  48. // Use lookup since nothing in the system can really reference it, no need
  49. // to protect against removal
  50. p, err := store.Get(name, metricsPluginType, plugingetter.Lookup)
  51. if err != nil {
  52. return
  53. }
  54. adapter, err := makePluginAdapter(p)
  55. if err != nil {
  56. logrus.WithError(err).WithField("plugin", p.Name()).Error("Error creating plugin adapter")
  57. }
  58. if err := adapter.StartMetrics(); err != nil {
  59. logrus.WithError(err).WithField("plugin", p.Name()).Error("Error starting metrics collector plugin")
  60. }
  61. })
  62. }