plugin.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2019 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package docker
  15. import (
  16. "time"
  17. "github.com/google/cadvisor/container"
  18. "github.com/google/cadvisor/fs"
  19. info "github.com/google/cadvisor/info/v1"
  20. "github.com/google/cadvisor/watcher"
  21. "golang.org/x/net/context"
  22. "k8s.io/klog"
  23. )
  24. const dockerClientTimeout = 10 * time.Second
  25. // NewPlugin returns an implementation of container.Plugin suitable for passing to container.RegisterPlugin()
  26. func NewPlugin() container.Plugin {
  27. return &plugin{}
  28. }
  29. type plugin struct{}
  30. func (p *plugin) InitializeFSContext(context *fs.Context) error {
  31. SetTimeout(dockerClientTimeout)
  32. // Try to connect to docker indefinitely on startup.
  33. dockerStatus := retryDockerStatus()
  34. context.Docker = fs.DockerContext{
  35. Root: RootDir(),
  36. Driver: dockerStatus.Driver,
  37. DriverStatus: dockerStatus.DriverStatus,
  38. }
  39. return nil
  40. }
  41. func (p *plugin) Register(factory info.MachineInfoFactory, fsInfo fs.FsInfo, includedMetrics container.MetricSet) (watcher.ContainerWatcher, error) {
  42. err := Register(factory, fsInfo, includedMetrics)
  43. return nil, err
  44. }
  45. func retryDockerStatus() info.DockerStatus {
  46. startupTimeout := dockerClientTimeout
  47. maxTimeout := 4 * startupTimeout
  48. for {
  49. ctx, _ := context.WithTimeout(context.Background(), startupTimeout)
  50. dockerStatus, err := StatusWithContext(ctx)
  51. if err == nil {
  52. return dockerStatus
  53. }
  54. switch err {
  55. case context.DeadlineExceeded:
  56. klog.Warningf("Timeout trying to communicate with docker during initialization, will retry")
  57. default:
  58. klog.V(5).Infof("Docker not connected: %v", err)
  59. return info.DockerStatus{}
  60. }
  61. startupTimeout = 2 * startupTimeout
  62. if startupTimeout > maxTimeout {
  63. startupTimeout = maxTimeout
  64. }
  65. }
  66. }