當前位置: 首頁>>代碼示例>>Golang>>正文


Golang go-dockerclient.Client類代碼示例

本文整理匯總了Golang中github.com/fsouza/go-dockerclient.Client的典型用法代碼示例。如果您正苦於以下問題:Golang Client類的具體用法?Golang Client怎麽用?Golang Client使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Client類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Init

func Init(docker *goDocker.Client, newContChan chan<- goDocker.Container, removeContChan chan<- string, drawStatsChan chan<- StatsMsg) {

	dockerEventChan = make(chan *goDocker.APIEvents, 10)
	statsResultsChan = make(chan StatsResult)
	statsResultsDoneChan = make(chan string)

	dockerClient = docker

	err := docker.AddEventListener(dockerEventChan)
	if err != nil {
		panic("Failed to add event listener: " + err.Error())
	}

	go statsRenderingRoutine(drawStatsChan)

	go dockerEventRoutingRoutine(dockerEventChan, newContChan, removeContChan)

	containers, _ := dockerClient.ListContainers(goDocker.ListContainersOptions{})
	Info.Println("Listing intial", len(containers), "containers as started")
	for _, cont := range containers {
		Info.Println("Marking", cont.ID, "as started")
		dockerEventChan <- &goDocker.APIEvents{ID: cont.ID, Status: "start"}
		//startedContainerChan <- cont.ID
	}

}
開發者ID:byrnedo,項目名稱:dockdash,代碼行數:26,代碼來源:docklistener.go

示例2: Action

// Action makes a skydns REST API call based on the docker event
func Action(logger *log.Logger, action string, containerId string, docker *dockerapi.Client, TTL uint64, CONSUL string, DOMAIN string) {

	//if we fail on inspection, that is ok because we might
	//be checking for a crufty container that no longer exists
	//due to docker being shutdown uncleanly

	container, dockerErr := docker.InspectContainer(containerId)
	if dockerErr != nil {
		logger.Printf("unable to inspect container:%s %s", containerId, dockerErr)
		return
	}
	var hostname = container.Name[1:]
	var ipaddress = container.NetworkSettings.IPAddress

	if ipaddress == "" {
		logger.Println("no ipaddress returned for container: " + hostname)
		return
	}

	switch action {
	case "start":
		logger.Println("new container name=" + container.Name[1:] + " ip:" + ipaddress)
		Deregister(CONSUL, logger, hostname)
		service := Service{Name: hostname, Address: ipaddress}
		Register(CONSUL, logger, &service)
	case "stop":
		logger.Println("removing container name=" + container.Name[1:] + " ip:" + ipaddress)
		Deregister(CONSUL, logger, hostname)
	case "destroy":
		logger.Println("removing container name=" + container.Name[1:] + " ip:" + ipaddress)
		Deregister(CONSUL, logger, hostname)
	default:
	}

}
開發者ID:xraduhx,項目名稱:crunchy-containers,代碼行數:36,代碼來源:dnsbridgeapi.go

示例3: containerAddress

func containerAddress(client *dockerapi.Client, containerId string) (string, error) {
	container, err := client.InspectContainer(containerId)
	if err != nil {
		return "", err
	}
	return container.NetworkSettings.IPAddress, nil
}
開發者ID:raceli,項目名稱:resolvable,代碼行數:7,代碼來源:docker_test.go

示例4: RegisterDockerEventListener

// RegisterDockerEventListener registers function as event listener with docker.
// laziness defines how many seconds to wait, after an event is received, until a refresh is triggered
func RegisterDockerEventListener(client *docker.Client, function func(), wg *sync.WaitGroup, laziness int) {
	wg.Add(1)
	defer wg.Done()

	events := make(chan *docker.APIEvents)
	defer close(events)

	err := client.AddEventListener((chan<- *docker.APIEvents)(events))
	if err != nil {
		log.Fatalf("Unable to add docker event listener: %s", err)
	}
	defer client.RemoveEventListener(events)

	log.Info("Listening to docker events...")
	for {
		event := <-events

		if event == nil {
			continue
		}

		if event.Status == "start" || event.Status == "stop" || event.Status == "die" {
			log.Debug("Received event %s for container %s", event.Status, event.ID[:12])

			Refresh.Mu.Lock()
			if !Refresh.IsTriggered {
				log.Info("Triggering refresh in %d seconds", laziness)
				Refresh.timer = time.AfterFunc(time.Duration(laziness)*time.Second, function)
				Refresh.IsTriggered = true
			}
			Refresh.Mu.Unlock()
		}
	}
}
開發者ID:wildone,項目名稱:docker-logstash-forwarder,代碼行數:36,代碼來源:utils.go

示例5: checkImages

func checkImages(client *docker.Client, config *Config) error {
	images, err := client.ListImages(docker.ListImagesOptions{})
	if err != nil {
		log.Fatalln(err)
	}

	imagesWithTags := map[string]bool{}

	for _, image := range images {
		for _, tag := range image.RepoTags {
			imagesWithTags[tag] = true
		}
	}

	fmt.Println("checking images...")
	for _, lang := range Extensions {
		if imagesWithTags[lang.Image] == true {
			log.Printf("image %s exists", lang.Image)
		} else {
			if config.FetchImages {
				log.Println("pulling", lang.Image, "image...")
				err := pullImage(lang.Image, client)
				if err != nil {
					log.Fatalln(err)
				}
			} else {
				return fmt.Errorf("image %s does not exist", lang.Image)
			}
		}
	}

	return nil
}
開發者ID:P0rtk3y,項目名稱:api,代碼行數:33,代碼來源:main.go

示例6: Boot

func Boot(client *docker.Client, opt *docker.CreateContainerOptions,
	exitCh chan error) (*docker.Container, error) {
	log.Debugf("Creating container for image %s", opt.Config.Image)
	container, err := client.CreateContainer(*opt)
	if err != nil {
		return container, err
	}

	log.Debugf("Starting container %s", container.ID)
	go func() {
		exitCh <- dockerpty.Start(client, container, opt.HostConfig)
	}()

	trial := 0
	for {
		container, err = client.InspectContainer(container.ID)
		if container.State.StartedAt.Unix() > 0 {
			break
		}
		if trial > 30 {
			return container, fmt.Errorf("container %s seems not started. state=%#v", container.ID, container.State)
		}
		trial += 1
		time.Sleep(time.Duration(trial*100) * time.Millisecond)
	}
	log.Debugf("container state=%#v", container.State)
	return container, nil
}
開發者ID:terminiter,項目名稱:earthquake,代碼行數:28,代碼來源:boot.go

示例7: createImage

// createImage creates a docker image either by pulling it from a registry or by
// loading it from the file system
func (d *DockerDriver) createImage(driverConfig *DockerDriverConfig, client *docker.Client, taskDir string) error {
	image := driverConfig.ImageName
	repo, tag := docker.ParseRepositoryTag(image)
	if tag == "" {
		tag = "latest"
	}

	var dockerImage *docker.Image
	var err error
	// We're going to check whether the image is already downloaded. If the tag
	// is "latest" we have to check for a new version every time so we don't
	// bother to check and cache the id here. We'll download first, then cache.
	if tag != "latest" {
		dockerImage, err = client.InspectImage(image)
	}

	// Download the image
	if dockerImage == nil {
		if len(driverConfig.LoadImages) > 0 {
			return d.loadImage(driverConfig, client, taskDir)
		}

		return d.pullImage(driverConfig, client, repo, tag)
	}
	return err
}
開發者ID:hooklift,項目名稱:nomad,代碼行數:28,代碼來源:docker.go

示例8: execInContainer

func execInContainer(client *docker.Client,
	id string,
	command []string) (string, string, error) {

	exec, err := client.CreateExec(docker.CreateExecOptions{
		AttachStderr: true,
		AttachStdin:  false,
		AttachStdout: true,
		Tty:          false,
		Cmd:          command,
		Container:    id,
	})

	if err != nil {
		return "", "", err
	}

	var outputBytes []byte
	outputWriter := bytes.NewBuffer(outputBytes)
	var errorBytes []byte
	errorWriter := bytes.NewBuffer(errorBytes)

	err = client.StartExec(exec.ID, docker.StartExecOptions{
		OutputStream: outputWriter,
		ErrorStream:  errorWriter,
	})

	return outputWriter.String(), errorWriter.String(), err
}
開發者ID:nishizhen,項目名稱:codetainer,代碼行數:29,代碼來源:container.go

示例9: destroyContainer

func destroyContainer(client *docker.Client, id string) error {
	return client.RemoveContainer(docker.RemoveContainerOptions{
		ID:            id,
		RemoveVolumes: true,
		Force:         true,
	})
}
開發者ID:bitrun,項目名稱:api,代碼行數:7,代碼來源:run.go

示例10: fetchDockerContainer

func fetchDockerContainer(name string, client *dc.Client) (*dc.APIContainers, error) {
	apiContainers, err := client.ListContainers(dc.ListContainersOptions{All: true})

	if err != nil {
		return nil, fmt.Errorf("Error fetching container information from Docker: %s\n", err)
	}

	for _, apiContainer := range apiContainers {
		// Sometimes the Docker API prefixes container names with /
		// like it does in these commands. But if there's no
		// set name, it just uses the ID without a /...ugh.
		switch len(apiContainer.Names) {
		case 0:
			if apiContainer.ID == name {
				return &apiContainer, nil
			}
		default:
			for _, containerName := range apiContainer.Names {
				if strings.TrimLeft(containerName, "/") == name {
					return &apiContainer, nil
				}
			}
		}
	}

	return nil, nil
}
開發者ID:rgl,項目名稱:terraform,代碼行數:27,代碼來源:resource_docker_container_funcs.go

示例11: fetchDockerContainer

func fetchDockerContainer(name string, client *dc.Client) (*dc.APIContainers, error) {
	apiContainers, err := client.ListContainers(dc.ListContainersOptions{All: true})

	if err != nil {
		return nil, fmt.Errorf("Error fetching container information from Docker: %s\n", err)
	}

	for _, apiContainer := range apiContainers {
		// Sometimes the Docker API prefixes container names with /
		// like it does in these commands. But if there's no
		// set name, it just uses the ID without a /...ugh.
		var dockerContainerName string
		if len(apiContainer.Names) > 0 {
			dockerContainerName = strings.TrimLeft(apiContainer.Names[0], "/")
		} else {
			dockerContainerName = apiContainer.ID
		}

		if dockerContainerName == name {
			return &apiContainer, nil
		}
	}

	return nil, nil
}
開發者ID:pyhrus,項目名稱:terraform,代碼行數:25,代碼來源:resource_docker_container_funcs.go

示例12: build

// build takes a Dockerfile and builds an image.
func build(c cookoo.Context, path, tag string, client *docli.Client) error {
	dfile := filepath.Join(path, "Dockerfile")

	// Stat the file
	info, err := os.Stat(dfile)
	if err != nil {
		return fmt.Errorf("Dockerfile stat: %s", err)
	}
	file, err := os.Open(dfile)
	if err != nil {
		return fmt.Errorf("Dockerfile open: %s", err)
	}
	defer file.Close()

	var buf bytes.Buffer
	tw := tar.NewWriter(&buf)
	tw.WriteHeader(&tar.Header{
		Name:    "Dockerfile",
		Size:    info.Size(),
		ModTime: info.ModTime(),
	})
	io.Copy(tw, file)
	if err := tw.Close(); err != nil {
		return fmt.Errorf("Dockerfile tar: %s", err)
	}

	options := docli.BuildImageOptions{
		Name:         tag,
		InputStream:  &buf,
		OutputStream: os.Stdout,
	}
	return client.BuildImage(options)
}
開發者ID:naveenholla,項目名稱:deis,代碼行數:34,代碼來源:docker.go

示例13: getLayerIdsToDownload

func (cli *DogestryCli) getLayerIdsToDownload(fromId remote.ID, imageRoot string, r remote.Remote, client *docker.Client) ([]remote.ID, error) {
	toDownload := make([]remote.ID, 0)

	err := r.WalkImages(fromId, func(id remote.ID, image docker.Image, err error) error {
		fmt.Printf("Examining id '%s' on remote docker host...\n", id.Short())
		if err != nil {
			return err
		}

		_, err = client.InspectImage(string(id))

		if err == docker.ErrNoSuchImage {
			toDownload = append(toDownload, id)
			return nil
		} else if err != nil {
			return err
		} else {
			fmt.Printf("Docker host already has id '%s', stop scanning.\n", id.Short())
			return remote.BreakWalk
		}

		return nil
	})

	return toDownload, err
}
開發者ID:sbecker,項目名稱:dogestry,代碼行數:26,代碼來源:cli.go

示例14: GetContainerNum

// GetContainerNum returns container number in the system
func GetContainerNum(client *docker.Client, all bool) int {
	containers, err := client.ListContainers(docker.ListContainersOptions{All: all})
	if err != nil {
		panic(fmt.Sprintf("Error list containers: %v", err))
	}
	return len(containers)
}
開發者ID:jojimt,項目名稱:contrib,代碼行數:8,代碼來源:docker_helpers.go

示例15: pullImage

// pullImage pulls the inspected image using the given client.
// It will try to use all the given authentication methods and will fail
// only if all of them failed.
func (i *defaultImageInspector) pullImage(client *docker.Client) error {
	log.Printf("Pulling image %s", i.opts.Image)

	var imagePullAuths *docker.AuthConfigurations
	var authCfgErr error
	if imagePullAuths, authCfgErr = i.getAuthConfigs(); authCfgErr != nil {
		return authCfgErr
	}

	reader, writer := io.Pipe()
	// handle closing the reader/writer in the method that creates them
	defer writer.Close()
	defer reader.Close()
	imagePullOption := docker.PullImageOptions{
		Repository:    i.opts.Image,
		OutputStream:  writer,
		RawJSONStream: true,
	}

	bytesChan := make(chan int)
	go aggregateBytesAndReport(bytesChan)
	go decodeDockerPullMessages(bytesChan, reader)

	// Try all the possible auth's from the config file
	var authErr error
	for name, auth := range imagePullAuths.Configs {
		if authErr = client.PullImage(imagePullOption, auth); authErr == nil {
			return nil
		}
		log.Printf("Authentication with %s failed: %v", name, authErr)
	}
	return fmt.Errorf("Unable to pull docker image: %v\n", authErr)
}
開發者ID:openshift,項目名稱:image-inspector,代碼行數:36,代碼來源:image-inspector.go


注:本文中的github.com/fsouza/go-dockerclient.Client類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。