• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang dockerclient.NewDockerClient函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/samalba/dockerclient.NewDockerClient函数的典型用法代码示例。如果您正苦于以下问题:Golang NewDockerClient函数的具体用法?Golang NewDockerClient怎么用?Golang NewDockerClient使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewDockerClient函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:nkhuyu,项目名称:cockroach,代码行数:33,代码来源:docker.go


示例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
}
开发者ID:hopkings2008,项目名称:dockerutil,代码行数:44,代码来源:client.go


示例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
}
开发者ID:zhuchance,项目名称:docker-ovs-plugin,代码行数:35,代码来源:driver.go


示例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)

}
开发者ID:odewahn,项目名称:thebe-server,代码行数:29,代码来源:main.go


示例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
}
开发者ID:abhinandanpb,项目名称:netplugin,代码行数:33,代码来源:agent.go


示例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
}
开发者ID:carriercomm,项目名称:docker-grid,代码行数:25,代码来源:node.go


示例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)
}
开发者ID:rsampaio,项目名称:docker-dns,代码行数:31,代码来源:server.go


示例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)
		}
	}()
}
开发者ID:pombredanne,项目名称:docker-stuff,代码行数:30,代码来源:docker_cache.go


示例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
}
开发者ID:JeremyOT,项目名称:docker-ci,代码行数:26,代码来源:monitor.go


示例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
	})
}
开发者ID:hackliff,项目名称:sentinel,代码行数:25,代码来源:docker.go


示例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
}
开发者ID:nikolayvoronchikhin,项目名称:netplugin,代码行数:29,代码来源:network.go


示例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
}
开发者ID:predakanga,项目名称:macvlan-docker-plugin,代码行数:31,代码来源:driver.go


示例13: NewApiMiddleware

func NewApiMiddleware(dockerAddr string) *ApiMiddleware {
	docker, err := dockerclient.NewDockerClient(dockerAddr, nil)
	if err != nil {
		return nil
	}
	return &ApiMiddleware{dockerClient: docker}
}
开发者ID:CloudSide,项目名称:specter,代码行数:7,代码来源:middleware.go


示例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)
	}
}
开发者ID:th3architect,项目名称:sherdock,代码行数:25,代码来源:main.go


示例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)
		}
	}
}
开发者ID:ZhukovAlexander,项目名称:entropy,代码行数:25,代码来源:scheduler.go


示例16: DockerWithTLS

// DockerWithTLS returns a DockerClient with the certs in the specified
// directory. The names of the certs are the standard names of "cert.pem",
// "key.pem" and "ca.pem".
func DockerWithTLS(url, certPath string) (*dockerclient.DockerClient, error) {
	var tlsConfig *tls.Config
	clientCert, err := tls.LoadX509KeyPair(
		filepath.Join(certPath, "cert.pem"),
		filepath.Join(certPath, "key.pem"),
	)
	if err != nil {
		return nil, stackerr.Wrap(err)
	}

	rootCAs := x509.NewCertPool()
	caCert, err := ioutil.ReadFile(filepath.Join(certPath, "ca.pem"))
	if err != nil {
		return nil, stackerr.Wrap(err)
	}
	rootCAs.AppendCertsFromPEM(caCert)

	tlsConfig = &tls.Config{
		Certificates: []tls.Certificate{clientCert},
		RootCAs:      rootCAs,
	}
	client, err := dockerclient.NewDockerClient(url, tlsConfig)
	if err != nil {
		return nil, stackerr.Wrap(err)
	}
	return client, nil
}
开发者ID:hopkings2008,项目名称:dockerutil,代码行数:30,代码来源:client.go


示例17: RestartContainer

func RestartContainer(request common.RequestData) (code int, result string) {
	strDockerServer := fmt.Sprintf("%s:%d", request.ServerIP, request.Port)
	fmt.Println("strDockerServer=", strDockerServer)
	client, _ := dockerclient.NewDockerClient(strDockerServer, nil)

	strID, ok := GetContainerID(request.Params)
	if !ok {
		logger.Println("cannot Restart Container ")
		code = 1
		result = "faild"
		return code, result
	}
	//fmt.Println("strID=", strID)

	nTime := 30
	err := client.RestartContainer(strID, nTime)
	if err != nil {
		logger.Println("cannot get containers: %s", err)
		code = 1
		result = "faild"
		return code, result
	}

	return 0, "ok"
}
开发者ID:masterpy,项目名称:autodep,代码行数:25,代码来源:action_container.go


示例18: main

func main() {
	flag.Parse()
	docker, _ = dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
	kong = kongo.NewKong(kongUrl)

	endpoints, err := kong.GetEndpoints()
	if err != nil {
		panic(err)
	}
	for _, endpoint := range endpoints {
		log.Printf("%s => %s\n", endpoint.Path, endpoint.TargetUrl)
	}

	// Get running containers
	containers, err := docker.ListContainers(false, false, "")
	if err != nil {
		log.Fatal(err)
	}

	for _, c := range containers {
		checkAndSync(c.Id)
	}

	// Listen to events
	docker.StartMonitorEvents(eventCallback, nil)

	// Hold the execution to look at the events coming
	for true {
		time.Sleep(3600 * time.Second)
		log.Println("PONG")
	}
}
开发者ID:jeffrydegrande,项目名称:autokong,代码行数:32,代码来源:main.go


示例19: main

func main() {
	fmt.Println("Devices runner")

	// Init the client
	docker, err := dc.NewDockerClient("unix:///var/run/docker.sock", nil)
	if err != nil {
		panic(err)
	}

	containers, err := docker.ListContainers(true)
	if err != nil {
		panic(err)
	}

	for _, c := range containers {
		fmt.Println("container: ", c.Names, " status: ", c.Status)
	}

	// let's create an API for starting devices

	http.HandleFunc("/device", func(w http.ResponseWriter, r *http.Request) { devicesHandler(w, r, docker) })
	http.HandleFunc("/device/", func(w http.ResponseWriter, r *http.Request) { deviceHandler(w, r, docker) })

	http.ListenAndServe(":8080", nil)
}
开发者ID:jvermillard,项目名称:daas,代码行数:25,代码来源:main.go


示例20: main

func main() {
	flag.Parse()
	for {
		client, err := dockerclient.NewDockerClient(*addr, nil)
		if err != nil {
			log.Fatal(err)
		}

		expiredContainers, expiredImages, err := getExpired(client)
		if err != nil {
			log.Fatal(err)
		}
		if err := removeContainers(client, expiredContainers); err != nil {
			log.Fatal(err)
		}

		if err := removeImages(client, expiredImages); err != nil {
			log.Fatal(err)
		}

		if *interval == 0 {
			break
		}
		log.Printf("Sleeping for %s", *interval)
		time.Sleep(*interval)
	}
}
开发者ID:dawidmalina,项目名称:docker-proper,代码行数:27,代码来源:docker-proper.go



注:本文中的github.com/samalba/dockerclient.NewDockerClient函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang dockerclient.NewDockerClientTimeout函数代码示例发布时间:2022-05-28
下一篇:
Golang webapp.Context类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap