Engine.Connect()
方法用来完成对Docker engine
的连接工作:
// Connect will initialize a connection to the Docker daemon running on the
// host, gather machine specs (memory, cpu, ...) and monitor state changes.
func (e *Engine) Connect(config *tls.Config) error {
host, _, err := net.SplitHostPort(e.Addr)
if err != nil {
return err
}
addr, err := net.ResolveIPAddr("ip4", host)
if err != nil {
return err
}
e.IP = addr.IP.String()
c, err := dockerclient.NewDockerClientTimeout("tcp://"+e.Addr, config, time.Duration(requestTimeout), setTCPUserTimeout)
if err != nil {
return err
}
// Use HTTP Client used by dockerclient to create engine-api client
apiClient, err := engineapi.NewClient("tcp://"+e.Addr, "", c.HTTPClient, nil)
if err != nil {
return err
}
return e.ConnectWithClient(c, apiClient)
}
Engine.Connect()
利用了另外两个Docker
项目:dockerclient和engine-api。首先调用dockerclient.NewDockerClientTimeout("tcp://"+e.Addr, config, time.Duration(requestTimeout), setTCPUserTimeout)
生成一个DockerClient
结构体:
type DockerClient struct {
URL *url.URL
HTTPClient *http.Client
TLSConfig *tls.Config
monitorStats int32
eventStopChan chan (struct{})
}
再把DockerClient.HTTPClient
传入engineapi.NewClient()
函数,作为engine-api
的http.Client
,作为HTTP
请求的传输载体。最后调用Engine.ConnectWithClient()
连接Docker engine
,获得Docker
信息。
有疑问加站长微信联系(非本文作者)