github.com/google/cadvisor@v0.49.1/container/docker/plugin.go (about)

     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  
    15  package docker
    16  
    17  import (
    18  	"time"
    19  
    20  	"golang.org/x/net/context"
    21  	"k8s.io/klog/v2"
    22  
    23  	"github.com/google/cadvisor/container"
    24  	"github.com/google/cadvisor/fs"
    25  	info "github.com/google/cadvisor/info/v1"
    26  	"github.com/google/cadvisor/watcher"
    27  )
    28  
    29  const dockerClientTimeout = 10 * time.Second
    30  
    31  // NewPlugin returns an implementation of container.Plugin suitable for passing to container.RegisterPlugin()
    32  func NewPlugin() container.Plugin {
    33  	return &plugin{}
    34  }
    35  
    36  type plugin struct{}
    37  
    38  func (p *plugin) InitializeFSContext(context *fs.Context) error {
    39  	SetTimeout(dockerClientTimeout)
    40  	// Try to connect to docker indefinitely on startup.
    41  	dockerStatus := retryDockerStatus()
    42  	context.Docker = fs.DockerContext{
    43  		Root:         RootDir(),
    44  		Driver:       dockerStatus.Driver,
    45  		DriverStatus: dockerStatus.DriverStatus,
    46  	}
    47  	return nil
    48  }
    49  
    50  func (p *plugin) Register(factory info.MachineInfoFactory, fsInfo fs.FsInfo, includedMetrics container.MetricSet) (watcher.ContainerWatcher, error) {
    51  	err := Register(factory, fsInfo, includedMetrics)
    52  	return nil, err
    53  }
    54  
    55  func retryDockerStatus() info.DockerStatus {
    56  	startupTimeout := dockerClientTimeout
    57  	maxTimeout := 4 * startupTimeout
    58  	for {
    59  		ctx, _ := context.WithTimeout(context.Background(), startupTimeout)
    60  		dockerStatus, err := StatusWithContext(ctx)
    61  		if err == nil {
    62  			return dockerStatus
    63  		}
    64  
    65  		switch err {
    66  		case context.DeadlineExceeded:
    67  			klog.Warningf("Timeout trying to communicate with docker during initialization, will retry")
    68  		default:
    69  			klog.V(5).Infof("Docker not connected: %v", err)
    70  			return info.DockerStatus{}
    71  		}
    72  
    73  		startupTimeout = 2 * startupTimeout
    74  		if startupTimeout > maxTimeout {
    75  			startupTimeout = maxTimeout
    76  		}
    77  	}
    78  }