本文整理汇总了Golang中github.com/samalba/dockerclient.NewDockerClient函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDockerClient函数的具体用法?Golang NewDockerClient怎么用?Golang NewDockerClient使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewDockerClient函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: newDockerClient
// newDockerClient constructs a new docker client using the best available
// method. If DOCKER_HOST is set, initialize the client using DOCKER_TLS_VERIFY
// and DOCKER_CERT_PATH. If DOCKER_HOST is not set, look for the unix domain
// socket in /run/docker.sock and /var/run/docker.sock.
func newDockerClient() dockerclient.Client {
if host := os.Getenv("DOCKER_HOST"); host != "" {
if os.Getenv("DOCKER_TLS_VERIFY") == "" {
c, err := dockerclient.NewDockerClient(host, nil)
if err != nil {
log.Fatal(err)
}
return c
}
c, err := dockerclient.NewDockerClient(host, getTLSConfig())
if err != nil {
log.Fatal(err)
}
return c
}
for _, l := range []string{"/run/docker.sock", "/var/run/docker.sock"} {
if _, err := os.Stat(l); err != nil {
continue
}
c, err := dockerclient.NewDockerClient("unix://"+l, nil)
if err != nil {
return nil
}
return c
}
log.Fatal("docker not configured")
return nil
}
示例2: BestEffortDockerClient
// BestEfforDockerClient creates a docker client from one of:
//
// 1. Environment variables as defined in
// https://docs.docker.com/reference/commandline/cli/. Specifically
// DOCKER_HOST, DOCKER_TLS_VERIFY & DOCKER_CERT_PATH.
//
// 2. bootdocker, if darwin.
//
// 3. /run/docker.sock, if it exists.
//
// 4. /var/run/docker.sock, if it exists.
func BestEffortDockerClient() (*dockerclient.DockerClient, error) {
host := os.Getenv("DOCKER_HOST")
if host == "" {
if runtime.GOOS == "darwin" {
return Boot2DockerClient()
}
socketLocations := []string{"/run/docker.sock", "/var/run/docker.sock"}
for _, l := range socketLocations {
if _, err := os.Stat(l); err == nil {
c, err := dockerclient.NewDockerClient(fmt.Sprintf("unix://%s", l), nil)
if err != nil {
return nil, stackerr.Wrap(err)
}
return c, nil
}
}
return nil, stackerr.New("docker not configured")
}
if os.Getenv("DOCKER_TLS_VERIFY") != "" {
return DockerWithTLS(host, os.Getenv("DOCKER_CERT_PATH"))
}
c, err := dockerclient.NewDockerClient(host, nil)
if err != nil {
return nil, stackerr.Wrap(err)
}
return c, nil
}
示例3: NewDriver
func NewDriver() (*Driver, error) {
docker, err := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
if err != nil {
return nil, fmt.Errorf("could not connect to docker: %s", err)
}
// initiate the ovsdb manager port binding
var ovsdb *libovsdb.OvsdbClient
retries := 3
for i := 0; i < retries; i++ {
ovsdb, err = libovsdb.Connect(localhost, ovsdbPort)
if err == nil {
break
}
log.Errorf("could not connect to openvswitch on port [ %d ]: %s. Retrying in 5 seconds", ovsdbPort, err)
time.Sleep(5 * time.Second)
}
if ovsdb == nil {
return nil, fmt.Errorf("could not connect to open vswitch")
}
d := &Driver{
dockerer: dockerer{
client: docker,
},
ovsdber: ovsdber{
ovsdb: ovsdb,
},
networks: make(map[string]*NetworkState),
}
// Initialize ovsdb cache at rpc connection setup
d.ovsdber.initDBCache()
return d, nil
}
示例4: main
func main() {
// Load the environment variables we need
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Read the port
port := os.Getenv("PORT")
tlsConfig, err := getTLSConfig(os.Getenv("SWARM_CREDS_DIR"))
if err != nil {
log.Fatal("Could not create TLS certificate.")
}
docker, _ := dockerclient.NewDockerClient(os.Getenv("DOCKER_HOST"), tlsConfig)
mux := mux.NewRouter()
// mux.HandleFunc("/events", get_events(dbmap)).Methods("GET")
// mux.HandleFunc("/events/{year}", get_events_by_year(dbmap)).Methods("GET")
mux.HandleFunc("/spawn", spawn(docker)).Methods("GET")
mux.HandleFunc("/list-containers", list_containers(docker)).Methods("GET")
n := negroni.Classic()
n.UseHandler(mux)
log.Printf("Listening on port %s\n", port)
n.Run(":" + port)
}
示例5: HandleEvents
// HandleEvents handles events
func (ag *Agent) HandleEvents() error {
opts := ag.pluginConfig.Instance
recvErr := make(chan error, 1)
go handleNetworkEvents(ag.netPlugin, opts, recvErr)
go handleBgpEvents(ag.netPlugin, opts, recvErr)
go handleEpgEvents(ag.netPlugin, opts, recvErr)
go handleServiceLBEvents(ag.netPlugin, opts, recvErr)
go handleSvcProviderUpdEvents(ag.netPlugin, opts, recvErr)
go handleGlobalCfgEvents(ag.netPlugin, opts, recvErr)
if ag.pluginConfig.Instance.PluginMode == "docker" {
// watch for docker events
docker, _ := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
go docker.StartMonitorEvents(handleDockerEvents, recvErr, ag.netPlugin, recvErr)
} else if ag.pluginConfig.Instance.PluginMode == "kubernetes" {
// start watching kubernetes events
k8splugin.InitKubServiceWatch(ag.netPlugin)
}
err := <-recvErr
if err != nil {
log.Errorf("Failure occured. Error: %s", err)
return err
}
return nil
}
示例6: NewNode
func NewNode(controllerUrl string, dockerUrl string, tlsConfig *tls.Config, cpus float64, memory float64, heartbeatInterval int, ip string, showOnlyGridContainers bool, enableDebug bool) (*Node, error) {
if enableDebug {
log.SetLevel(log.DebugLevel)
}
u := uuid.NewV4()
id := uuid.Formatter(u, uuid.CleanHyphen)
client, err := dockerclient.NewDockerClient(dockerUrl, tlsConfig)
if err != nil {
return nil, err
}
node := &Node{
Id: id,
client: client,
controllerUrl: controllerUrl,
heartbeatInterval: heartbeatInterval,
showOnlyGridContainers: showOnlyGridContainers,
ip: ip,
Cpus: cpus,
Memory: memory,
}
return node, nil
}
示例7: handleDnsRequest
func handleDnsRequest(w dns.ResponseWriter, r *dns.Msg) {
m := new(dns.Msg)
m.SetReply(r)
records := make([]dns.RR, 0)
q := r.Question[0]
if q.Qtype == dns.TypeA && strings.HasSuffix(q.Name, ".docker.") {
docker, _ := dockerclient.NewDockerClient("unix:///var/run/docker.sock", &tls.Config{})
name := strings.SplitN(q.Name, ".", 2)[0]
containers, err := docker.ListContainers(false, false, fmt.Sprintf("{\"name\":[\"%s\"]}", name))
if err != nil {
log.Fatal(err)
}
for _, c := range containers {
info, _ := docker.InspectContainer(c.Id)
log.Printf("Container %s[%6s] has ip %s\n", name, info.Id, info.NetworkSettings.IPAddress)
records = append(records,
&dns.A{
Hdr: dns.RR_Header{
Name: q.Name,
Rrtype: dns.TypeA,
Class: dns.ClassINET,
Ttl: 60},
A: net.ParseIP(info.NetworkSettings.IPAddress),
})
}
}
m.Answer = append(m.Answer, records...)
defer w.WriteMsg(m)
}
示例8: main
func main() {
random := rand.New(rand.NewSource(int64(int(time.Now().UnixNano()) * os.Getpid())))
config := parseFlags()
ttl := time.Duration(float64(config.UpdateInterval) * 1.5)
cache, err := NewCache(config.CacheURL, config.Id, ttl)
if err != nil {
log.Fatal(err)
}
docker, err := dockerclient.NewDockerClient(config.DockerURL)
if err != nil {
log.Fatal(err)
}
rtInfo := &RuntimeInfo{config.Id, cache, docker, ttl}
log.Printf("Started monitoring Docker events (%s)\n", config.Id)
docker.StartMonitorEvents(dockerEventCallback, rtInfo)
go func() {
// Garbage collect expired hosts at random interval
for {
cache.ClearExpiredHosts()
offset := random.Intn(int(config.UpdateInterval.Seconds()))
time.Sleep(config.UpdateInterval + (time.Duration(offset) * time.Second))
}
}()
func() {
for {
update(rtInfo)
time.Sleep(config.UpdateInterval)
}
}()
}
示例9: New
func New(config *Config) (m *Monitor, err error) {
var authConfig *dockerclient.AuthConfig
if config.AuthConfig != "" {
authJson, err := base64.StdEncoding.DecodeString(config.AuthConfig)
if err != nil {
return nil, err
}
var auth dockerclient.AuthConfig
if err = json.Unmarshal(authJson, &auth); err != nil {
return nil, err
}
authConfig = &auth
}
client, err := dockerclient.NewDockerClient(config.URL, nil)
if err != nil {
return
}
m = &Monitor{
config: config,
client: client,
tasks: make(map[string]task.Task, 10),
authConfig: authConfig,
staticSource: task.NewStaticSource(),
}
return
}
示例10: init
func init() {
log.Info("registering heartbeat: docker")
Add("docker", func(conf map[string]string) (Plugin, error) {
host, ok := conf["host"]
if !ok {
host = os.Getenv("DOCKER_HOST")
if host == "" {
log.Info("no host information found, fallback to default: %s")
host = DEFAULT_DOCKER_HOST
}
}
log.Info("connecting to docker (%s)", host)
// TODO support for tls
docker, err := dockerclient.NewDockerClient(host, nil)
if err != nil {
return nil, err
}
return &DockerMonitor{
docker: docker,
logger: logger.New("sentinel.plugins.heartbeats.docker"),
}, nil
})
}
示例11: deleteDockNet
// deleteDockNet deletes a network in docker daemon
func deleteDockNet(tenantName, networkName, serviceName string) error {
// do nothing in test mode
if testMode {
return nil
}
// Trim default tenant name
docknetName := getDocknetName(tenantName, networkName, serviceName)
// connect to docker
docker, err := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
if err != nil {
log.Errorf("Unable to connect to docker. Error %v", err)
return errors.New("Unable to connect to docker")
}
log.Infof("Deleting docker network: %+v", docknetName)
// Delete network
err = docker.RemoveNetwork(docknetName)
if err != nil {
log.Errorf("Error deleting network %s. Err: %v", docknetName, err)
// FIXME: Ignore errors till we fully move to docker 1.9
return nil
}
return nil
}
示例12: NewDriver
// NewDriver creates a new MACVLAN Driver
func NewDriver(version string, ctx *cli.Context) (*Driver, error) {
docker, err := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
if err != nil {
return nil, fmt.Errorf("could not connect to docker: %s", err)
}
// lower bound of v4 MTU is 68-bytes per rfc791
if ctx.Int("mtu") <= 0 {
cliMTU = defaultMTU
} else if ctx.Int("mtu") >= minMTU {
cliMTU = ctx.Int("mtu")
} else {
log.Fatalf("The MTU value passed [ %d ] must be greater than [ %d ] bytes per rfc791", ctx.Int("mtu"), minMTU)
}
// Set the default mode to bridge
if ctx.String("mode") == "" {
macvlanMode = bridgeMode
}
switch ctx.String("mode") {
case bridgeMode:
macvlanMode = bridgeMode
// todo: in other modes if relevant
}
d := &Driver{
networks: networkTable{},
dockerer: dockerer{
client: docker,
},
}
return d, nil
}
示例13: NewApiMiddleware
func NewApiMiddleware(dockerAddr string) *ApiMiddleware {
docker, err := dockerclient.NewDockerClient(dockerAddr, nil)
if err != nil {
return nil
}
return &ApiMiddleware{dockerClient: docker}
}
示例14: getContainers
func (u DockerResource) getContainers(request *restful.Request, response *restful.Response) {
// Init the client
docker, err := dockerclient.NewDockerClient(u.url, nil)
if err != nil {
log.Fatal("Couldn't connect to docker client")
}
if request.QueryParameter("detailed") == "false" {
containers, err := docker.ListContainers(true, false, "")
if err != nil {
log.Println(err)
log.Fatal("Unable to fetch running containers")
}
response.WriteEntity(containers)
} else {
containers, err := containers.ListContainersDetailed(docker)
if err != nil {
log.Println(err)
log.Fatal("Unable to fetch running containers")
}
response.WriteEntity(containers)
}
}
示例15: stopInjector
func stopInjector(t, e string) {
if t == "" {
log.Error("Unspecified CID.")
return
}
if e == "" {
log.Error("Unspecified Docker endpoint.")
return
}
client, err := docker.NewDockerClient(e, nil)
if err != nil {
log.Error(err)
return
}
err = client.StopContainer(t, 30)
if err != nil {
if err == docker.ErrNotFound {
log.Info("Unable to recover deleted injector: %s", t)
} else {
log.Error(err)
}
}
}