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

Golang client.NewEnvClient函数代码示例

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

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



在下文中一共展示了NewEnvClient函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	cli, err := client.NewEnvClient()
	if err != nil {
		panic(err)
	}

	certPath := os.Getenv("DOCKER_CERT_PATH")
	hostConfig := &container.HostConfig{
		NetworkMode: "serverlessdockervotingapp_default",
		Binds:       []string{fmt.Sprintf("%s:%s", certPath, certPath)},
	}
	inheritEnv := []string{"DOCKER_HOST", "DOCKER_MACHINE_NAME", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH"}

	http.Handle("/vote/", &dcgi.Handler{
		Image:      "bfirsh/serverless-vote",
		Client:     cli,
		HostConfig: hostConfig,
		InheritEnv: inheritEnv,
		Root:       "/vote", // strip /vote from all URLs
	})
	http.Handle("/result/", &dcgi.Handler{
		Image:      "bfirsh/serverless-result",
		Client:     cli,
		HostConfig: hostConfig,
		InheritEnv: inheritEnv,
		Root:       "/result",
	})
	http.ListenAndServe(":80", nil)
}
开发者ID:yamamoto-febc,项目名称:serverless-docker-voting-app,代码行数:29,代码来源:main.go


示例2: cleanContainers

func cleanContainers(c *check.C) *docker.Project {
	client, err := dockerclient.NewEnvClient()
	c.Assert(err, check.IsNil)

	filterArgs := filters.NewArgs()
	filterArgs, err = filters.ParseFlag(d.KermitLabelFilter, filterArgs)
	c.Assert(err, check.IsNil)

	containers, err := client.ContainerList(context.Background(), types.ContainerListOptions{
		All:    true,
		Filter: filterArgs,
	})
	c.Assert(err, check.IsNil)

	for _, container := range containers {
		c.Logf("cleaning container %s…", container.ID)
		if err := client.ContainerRemove(context.Background(), container.ID, types.ContainerRemoveOptions{
			Force: true,
		}); err != nil {
			c.Errorf("Error while removing container %s : %v\n", container.ID, err)
		}
	}

	return docker.NewProject(client)
}
开发者ID:vdemeester,项目名称:libkermit,代码行数:25,代码来源:helper_test.go


示例3: CreateProject

// CreateProject creates a compose project with the given name based on the
// specified compose files
func CreateProject(name string, composeFiles ...string) (*Project, error) {
	apiClient, err := client.NewEnvClient()
	if err != nil {
		return nil, err
	}
	composeProject, err := docker.NewProject(&docker.Context{
		Context: project.Context{
			ComposeFiles: composeFiles,
			ProjectName:  name,
		},
	})
	if err != nil {
		return nil, err
	}
	p := &Project{
		composeProject: composeProject,
		listenChan:     make(chan project.Event),
		started:        make(chan struct{}),
		stopped:        make(chan struct{}),
		deleted:        make(chan struct{}),
		client:         apiClient,
	}

	// Listen to compose events
	go p.startListening()
	p.composeProject.AddListener(p.listenChan)

	return p, nil
}
开发者ID:vdemeester,项目名称:libkermit,代码行数:31,代码来源:compose.go


示例4: runSave

func runSave(cmd *cobra.Command, args []string) (reterr error) {
	if len(args) == 0 {
		return errors.New("image reference missing")
	}

	output, err := cmd.Flags().GetString("output")
	if err != nil {
		return err
	}

	if output == "-" && terminal.IsTerminal(int(os.Stdout.Fd())) {
		return errors.New("refusing to output to terminal, specify output file")
	}

	client, err := engineapi.NewEnvClient()
	if err != nil {
		return err
	}

	ctx, cancel := context.WithCancel(context.Background())
	callOnSignal(ctx, cancel, syscall.SIGINT)
	defer cancel()

	graphdir, err := cmd.Flags().GetString("graph")
	if err != nil {
		return err
	}

	c, err := buildcache.New(client).Get(ctx, graphdir, args[0])
	if err != nil {
		return err
	}

	if output == "-" {
		_, err := io.Copy(os.Stdout, c)
		return err
	}

	f, err := ioutil.TempFile(filepath.Dir(output), ".buildcache-")
	if err != nil {
		return err
	}
	defer func() {
		if reterr != nil {
			os.RemoveAll(f.Name())
		}
	}()
	if n, err := io.Copy(f, c); err != nil {
		return err
	} else {
		logrus.Debugf("saving: %v", humanize.Bytes(uint64(n)))
	}
	if err := f.Sync(); err != nil {
		return err
	}
	if err := f.Close(); err != nil {
		return err
	}
	return os.Rename(f.Name(), output)
}
开发者ID:concourse,项目名称:docker-image-resource,代码行数:60,代码来源:save.go


示例5: CreateLocal

// CreateLocal creates a new local cockroach cluster. The stopper is used to
// gracefully shutdown the channel (e.g. when a signal arrives). The cluster
// must be started before being used.
func CreateLocal(cfg TestConfig, logDir string, privileged bool, stopper chan struct{}) *LocalCluster {
	select {
	case <-stopper:
		// The stopper was already closed, exit early.
		os.Exit(1)
	default:
	}

	if *cockroachImage == builderImageFull && !exists(*cockroachBinary) {
		log.Fatalf("\"%s\": does not exist", *cockroachBinary)
	}

	cli, err := client.NewEnvClient()
	maybePanic(err)

	retryingClient := retryingDockerClient{
		resilientDockerClient: resilientDockerClient{APIClient: cli},
		attempts:              10,
		timeout:               10 * time.Second,
	}

	return &LocalCluster{
		client:  retryingClient,
		stopper: stopper,
		config:  cfg,
		// TODO(tschottdorf): deadlocks will occur if these channels fill up.
		events:         make(chan Event, 1000),
		expectedEvents: make(chan Event, 1000),
		logDir:         logDir,
		privileged:     privileged,
	}
}
开发者ID:csdigi,项目名称:cockroach,代码行数:35,代码来源:localcluster.go


示例6: NewProjectFromEnv

// NewProjectFromEnv creates a project with a client that is build from environment variables.
func NewProjectFromEnv(t *testing.T) *Project {
	client, err := client.NewEnvClient()
	if err != nil {
		t.Fatalf("Error while getting a docker client from env: %s", err.Error())
	}
	return NewProject(client)
}
开发者ID:vdemeester,项目名称:libkermit,代码行数:8,代码来源:testing.go


示例7: NewProjectFromEnv

// NewProjectFromEnv creates a project with a client that is build from environment variables.
func NewProjectFromEnv() (*Project, error) {
	client, err := client.NewEnvClient()
	if err != nil {
		return nil, err
	}
	return NewProject(client), nil
}
开发者ID:vdemeester,项目名称:libkermit,代码行数:8,代码来源:docker.go


示例8: CreateLocal

// CreateLocal creates a new local cockroach cluster. The stopper is used to
// gracefully shutdown the channel (e.g. when a signal arrives). The cluster
// must be started before being used.
func CreateLocal(numLocal, numStores int, logDir string, stopper chan struct{}) *LocalCluster {
	select {
	case <-stopper:
		// The stopper was already closed, exit early.
		os.Exit(1)
	default:
	}

	if *cockroachImage == builderImage && !exists(*cockroachBinary) {
		log.Fatalf("\"%s\": does not exist", *cockroachBinary)
	}

	cli, err := dockerclient.NewEnvClient()
	maybePanic(err)

	return &LocalCluster{
		client:    cli,
		stopper:   stopper,
		numLocal:  numLocal,
		numStores: numStores,
		// TODO(tschottdorf): deadlocks will occur if these channels fill up.
		events:         make(chan Event, 1000),
		expectedEvents: make(chan Event, 1000),
		logDir:         logDir,
	}
}
开发者ID:duguruiyuan,项目名称:cockroach,代码行数:29,代码来源:localcluster.go


示例9: cleanContainers

func cleanContainers(t *testing.T) *docker.Project {
	client, err := dockerclient.NewEnvClient()
	if err != nil {
		t.Fatal(err)
	}

	filterArgs := filters.NewArgs()
	if filterArgs, err = filters.ParseFlag(docker.KermitLabelFilter, filterArgs); err != nil {
		t.Fatal(err)
	}

	containers, err := client.ContainerList(context.Background(), types.ContainerListOptions{
		All:    true,
		Filter: filterArgs,
	})
	if err != nil {
		t.Fatal(err)
	}

	for _, container := range containers {
		t.Logf("cleaning container %s…", container.ID)
		if err := client.ContainerRemove(context.Background(), container.ID, types.ContainerRemoveOptions{
			Force: true,
		}); err != nil {
			t.Errorf("Error while removing container %s : %v\n", container.ID, err)
		}
	}

	return docker.NewProject(client)
}
开发者ID:vdemeester,项目名称:libkermit,代码行数:30,代码来源:helper_test.go


示例10: getDockerID

func getDockerID() (dockerID string, err error) {
	dockerID = ""
	err = nil
	context := ctx.Background()

	// Default to Docker API Version corresponding to Docker v1.10
	if os.Getenv("DOCKER_API_VERSION") == "" {
		if err = os.Setenv("DOCKER_API_VERSION", "1.22"); err != nil {
			log.Panicf("Cannot set default Docker API Version: '%s'", err)
			os.Exit(1)
		}
	}
	cli, err := apiclient.NewEnvClient()
	if err != nil {
		return
	}

	inf, err := cli.Info(context)
	if err != nil {
		return
	}
	dockerID = inf.ID

	return
}
开发者ID:yuewko,项目名称:docker-infoblox,代码行数:25,代码来源:ipam-driver.go


示例11: getDockerClient

// Get a *dockerapi.Client, either using the endpoint passed in, or using
// DOCKER_HOST, DOCKER_TLS_VERIFY, and DOCKER_CERT path per their spec
func getDockerClient(dockerEndpoint string) (*dockerapi.Client, error) {
	if len(dockerEndpoint) > 0 {
		glog.Infof("Connecting to docker on %s", dockerEndpoint)
		return dockerapi.NewClient(dockerEndpoint, "", nil, nil)
	}
	return dockerapi.NewEnvClient()
}
开发者ID:copejon,项目名称:origin,代码行数:9,代码来源:docker.go


示例12: main

func main() {
	var dockerAddr string
	var transferAddr string
	var debug bool
	flag.BoolVar(&debug, "DEBUG", false, "enable debug")
	flag.StringVar(&dockerAddr, "d", "tcp://192.168.99.100:2376", "docker daemon addr")
	flag.StringVar(&transferAddr, "t", "10.200.8.37:8433", "transfer addr")
	flag.Parse()
	if flag.NArg() < 1 {
		fmt.Println("need at least one container id")
		return
	}
	if debug {
		log.SetLevel(log.DebugLevel)
	}

	cli, _ := client.NewEnvClient()

	metric.SetGlobalSetting(cli, 2, 3, "vnbe", "eth0")
	client := statsd.CreateStatsDClient(transferAddr)
	ctx := context.Background()

	for i := 0; i < flag.NArg(); i++ {
		if c, err := cli.ContainerInspect(ctx, flag.Arg(i)); err != nil {
			fmt.Println(flag.Arg(i), err)
			continue
		} else {
			go start_watcher(client, c.ID, c.State.Pid)
		}
	}
	for {
	}
}
开发者ID:projecteru,项目名称:eru-metric,代码行数:33,代码来源:example_statsd.go


示例13: newDockerClient

func newDockerClient() {
	cli, err := client.NewEnvClient()
	if err != nil {
		fmt.Println(err)
		return
	}
	dockerClient = &DockerClient{cli}
}
开发者ID:dmcsorley,项目名称:avast,代码行数:8,代码来源:docker.go


示例14: getMounted

func (dc *DaemonConfig) getMounted() (map[string]*storage.Mount, map[string]int, error) {
	mounts := map[string]*storage.Mount{}
	counts := map[string]int{}

	now := time.Now()

	// XXX this loop will indefinitely run if the docker service is down.
	// This is intentional to ensure we don't take any action when docker is down.
	for {
		dockerClient, err := client.NewEnvClient()
		if err != nil {
			return nil, nil, errored.Errorf("Could not initiate docker client").Combine(err)
		}

		containers, err := dockerClient.ContainerList(context.Background(), types.ContainerListOptions{})
		if err != nil {
			if now.Sub(time.Now()) > dc.Global.Timeout {
				panic("Cannot contact docker")
			}
			logrus.Error(errored.Errorf("Could not query docker; retrying").Combine(err))
			time.Sleep(time.Second)
			continue
		}

		for _, container := range containers {
			if container.State == "running" {
				for _, mount := range container.Mounts {
					if mount.Driver == dc.PluginName {
						mounts[mount.Name] = nil
						counts[mount.Name]++
					}
				}
			}
		}

		break
	}

	for driverName := range backend.MountDrivers {
		cd, err := backend.NewMountDriver(driverName, dc.Global.MountPath)
		if err != nil {
			return nil, nil, err
		}

		mounted, err := cd.Mounted(dc.Global.Timeout)
		if err != nil {
			return nil, nil, err
		}

		for _, mount := range mounted {
			logrus.Debugf("Refreshing existing mount for %q: %v", mount.Volume.Name, *mount)
			mounts[mount.Volume.Name] = mount
		}
	}

	return mounts, counts, nil
}
开发者ID:contiv,项目名称:volplugin,代码行数:57,代码来源:init.go


示例15: Gather

// Gather starts stats collection
func (d *Docker) Gather(acc telegraf.Accumulator) error {
	if d.client == nil {
		var c *client.Client
		var err error
		defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
		if d.Endpoint == "ENV" {
			c, err = client.NewEnvClient()
			if err != nil {
				return err
			}
		} else if d.Endpoint == "" {
			c, err = client.NewClient("unix:///var/run/docker.sock", "", nil, defaultHeaders)
			if err != nil {
				return err
			}
		} else {
			c, err = client.NewClient(d.Endpoint, "", nil, defaultHeaders)
			if err != nil {
				return err
			}
		}
		d.client = c
	}

	// Get daemon info
	err := d.gatherInfo(acc)
	if err != nil {
		fmt.Println(err.Error())
	}

	// List containers
	opts := types.ContainerListOptions{}
	ctx, cancel := context.WithTimeout(context.Background(), d.Timeout.Duration)
	defer cancel()
	containers, err := d.client.ContainerList(ctx, opts)
	if err != nil {
		return err
	}

	// Get container data
	var wg sync.WaitGroup
	wg.Add(len(containers))
	for _, container := range containers {
		go func(c types.Container) {
			defer wg.Done()
			err := d.gatherContainer(c, acc)
			if err != nil {
				log.Printf("Error gathering container %s stats: %s\n",
					c.Names, err.Error())
			}
		}(container)
	}
	wg.Wait()

	return nil
}
开发者ID:lizaoreo,项目名称:telegraf,代码行数:57,代码来源:docker.go


示例16: StartDaemon

// StartDaemon starts a daemon using the provided binary returning
// a client to the binary, a close function, and error.
func StartDaemon(ctx context.Context, binary string, lc LogCapturer) (DockerClient, func() error, error) {
	// Get Docker version of process
	previousVersion, err := versionutil.BinaryVersion(binary)
	if err != nil {
		return DockerClient{}, nil, fmt.Errorf("could not get binary version: %s", err)
	}

	logrus.Debugf("Starting daemon with %s", binary)
	binaryArgs := []string{}
	if previousVersion.LessThan(versionutil.StaticVersion(1, 8, 0)) {
		binaryArgs = append(binaryArgs, "--daemon")
	} else {
		binaryArgs = append(binaryArgs, "daemon")
	}
	binaryArgs = append(binaryArgs, "--log-level=debug")
	binaryArgs = append(binaryArgs, "--storage-driver="+getGraphDriver())
	cmd := exec.Command(binary, binaryArgs...)
	cmd.Stdout = lc.Stdout()
	cmd.Stderr = lc.Stderr()
	if err := cmd.Start(); err != nil {
		return DockerClient{}, nil, fmt.Errorf("could not start daemon: %s", err)
	}

	logrus.Debugf("Waiting for daemon to start")
	time.Sleep(2 * time.Second)

	cli, err := client.NewEnvClient()
	if err != nil {
		return DockerClient{}, nil, fmt.Errorf("could not initialize client: %s", err)
	}

	// Wait for it to start
	for i := 0; ; i++ {
		v, err := cli.ServerVersion(ctx)
		if err == nil {
			logrus.Debugf("Established connection to daemon with version %s", v.Version)
			break
		}
		if i >= 10 {
			logrus.Fatalf("Failed to establish connection to daemon, check logs, quitting")
		}
		time.Sleep(time.Second)
	}

	kill := func() error {
		if err := cmd.Process.Kill(); err != nil {
			return err
		}
		time.Sleep(500 * time.Millisecond)
		return os.RemoveAll("/var/run/docker.pid")
	}

	return DockerClient{Client: cli, options: &clientutil.ClientOptions{}}, kill, nil
}
开发者ID:docker,项目名称:golem,代码行数:56,代码来源:suite.go


示例17: NewTarget

//NewTarget initiates a new Target struct
func NewTarget() (a Target, err error) {
	a.Client, err = client.NewEnvClient()
	if err != nil {
		log.Fatalf("unable to create Docker client: %v\n", err)
	}
	a.Info, err = a.Client.Info()
	if err != nil {
		log.Fatalf("unable to fetch Docker daemon info: %v\n", err)
	}
	err = a.createContainerList()
	return
}
开发者ID:diogomonica,项目名称:actuary,代码行数:13,代码来源:checks.go


示例18: findContainersForProject

func findContainersForProject(name string) ([]types.Container, error) {
	client, err := client.NewEnvClient()
	if err != nil {
		return []types.Container{}, err
	}
	filterArgs := filters.NewArgs()
	if filterArgs, err = filters.ParseFlag(docker.KermitLabelFilter, filterArgs); err != nil {
		return []types.Container{}, err
	}

	return client.ContainerList(context.Background(), types.ContainerListOptions{
		All:    true,
		Filter: filterArgs,
	})
}
开发者ID:vdemeester,项目名称:libkermit,代码行数:15,代码来源:simple_test.go


示例19: main

func main() {

	cli, err := client.NewEnvClient()
	if err != nil {
		log.Fatal(err)
	}

	opts := types.EventsOptions{Filters: filters.NewArgs()}
	// opts.Filters.Add("action", "start")
	opts.Filters.Add("container", "container")

	ev, err := cli.Events(context.TODO(), opts)
	if err != nil {
		log.Fatal(err)
	}

	io.Copy(os.Stdout, ev)

}
开发者ID:gimepro,项目名称:gimepro,代码行数:19,代码来源:main.go


示例20: getDockerClient

// getDockerClient safely returns the singleton instance of the Docker client.
func getDockerClient() DockerClient {
	safeClient.Lock()
	defer safeClient.Unlock()

	if safeClient.client != nil {
		return safeClient.client
	}

	if dc, err := client.NewEnvClient(); err != nil {
		log.Printf("Could not get a docker client: %v", err)
	} else {
		safeClient.client = dc
		return dc
	}

	// The return statement is just to make golint happy about this and for
	// compliance with the API.
	exitWithCode(1)
	return nil
}
开发者ID:mssola,项目名称:zypper-docker,代码行数:21,代码来源:client.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Golang client.APIClient类代码示例发布时间:2022-05-23
下一篇:
Golang client.NewClient函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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