예제 #1
0
func (s *S) TestCreateContainerForward(c *gocheck.C) {
	cmutex.Lock()
	oldClusterNodes := clusterNodes
	clusterNodes = map[string]string{
		"server": "http://localhost:8081",
	}
	cmutex.Unlock()
	defer func() {
		cmutex.Lock()
		clusterNodes = oldClusterNodes
		cmutex.Unlock()
	}()
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	client, err := dockerClient.NewClient(s.server.URL())
	c.Assert(err, gocheck.IsNil)
	images, err := client.ListImages(true)
	c.Assert(err, gocheck.IsNil)
	cmds := []string{"ps", "-ef"}
	app := testing.NewFakeApp("myapp", "python", 1)
	cont := container{Name: "myName", AppName: app.GetName(), Type: app.GetPlatform(), Status: "created"}
	context := action.FWContext{Previous: cont, Params: []interface{}{app, images[0].ID, cmds}}
	r, err := createContainer.Forward(context)
	c.Assert(err, gocheck.IsNil)
	cont = r.(container)
	defer cont.remove()
	c.Assert(cont, gocheck.FitsTypeOf, container{})
	c.Assert(cont.ID, gocheck.Not(gocheck.Equals), "")
	c.Assert(cont.HostAddr, gocheck.Equals, "localhost")
	dcli, err := dockerClient.NewClient(s.server.URL())
	c.Assert(err, gocheck.IsNil)
	cc, err := dcli.InspectContainer(cont.ID)
	c.Assert(err, gocheck.IsNil)
	c.Assert(cc.State.Running, gocheck.Equals, false)
}
예제 #2
0
func (s *SchedulerSuite) TestSchedulerSchedule(c *gocheck.C) {
	server0, err := testing.NewServer(nil)
	c.Assert(err, gocheck.IsNil)
	defer server0.Stop()
	server1, err := testing.NewServer(nil)
	c.Assert(err, gocheck.IsNil)
	defer server1.Stop()
	server2, err := testing.NewServer(nil)
	c.Assert(err, gocheck.IsNil)
	defer server2.Stop()
	var buf bytes.Buffer
	client, _ := dcli.NewClient(server0.URL())
	client.PullImage(dcli.PullImageOptions{Repository: "tsuru/python"}, &buf)
	client, _ = dcli.NewClient(server1.URL())
	client.PullImage(dcli.PullImageOptions{Repository: "tsuru/python"}, &buf)
	client, _ = dcli.NewClient(server2.URL())
	client.PullImage(dcli.PullImageOptions{Repository: "tsuru/python"}, &buf)
	a1 := app.App{Name: "impius", Teams: []string{"tsuruteam", "nodockerforme"}}
	a2 := app.App{Name: "mirror", Teams: []string{"tsuruteam"}}
	a3 := app.App{Name: "dedication", Teams: []string{"nodockerforme"}}
	cont1 := container{ID: "1", Name: "impius1", AppName: a1.Name}
	cont2 := container{ID: "2", Name: "mirror1", AppName: a2.Name}
	cont3 := container{ID: "3", Name: "dedication1", AppName: a3.Name}
	err = s.storage.Apps().Insert(a1, a2, a3)
	c.Assert(err, gocheck.IsNil)
	defer s.storage.Apps().RemoveAll(bson.M{"name": bson.M{"$in": []string{a1.Name, a2.Name, a3.Name}}})
	coll := s.storage.Collection(schedulerCollection)
	err = coll.Insert(
		node{ID: "server0", Address: server0.URL(), Teams: []string{"tsuruteam"}},
		node{ID: "server1", Address: server1.URL(), Teams: []string{"tsuruteam"}},
		node{ID: "server2", Address: server2.URL()},
	)
	c.Assert(err, gocheck.IsNil)
	defer coll.RemoveAll(bson.M{"_id": bson.M{"$in": []string{"server0", "server1", "server2"}}})
	contColl := collection()
	err = contColl.Insert(
		cont1, cont2, cont3,
	)
	c.Assert(err, gocheck.IsNil)
	defer contColl.RemoveAll(bson.M{"name": bson.M{"$in": []string{cont1.Name, cont2.Name, cont3.Name}}})
	var scheduler segregatedScheduler
	config := docker.Config{Cmd: []string{"/usr/sbin/sshd", "-D"}, Image: "tsuru/python"}
	opts := dcli.CreateContainerOptions{Name: cont1.Name}
	node, _, err := scheduler.Schedule(opts, &config)
	c.Assert(err, gocheck.IsNil)
	c.Check(node, gocheck.Equals, "server1")
	config = docker.Config{Cmd: []string{"/usr/sbin/sshd", "-D"}, Image: "tsuru/python"}
	opts = dcli.CreateContainerOptions{Name: cont2.Name}
	node, _, err = scheduler.Schedule(opts, &config)
	c.Assert(err, gocheck.IsNil)
	c.Check(node == "server0" || node == "server1", gocheck.Equals, true)
	config = docker.Config{Cmd: []string{"/usr/sbin/sshd", "-D"}, Image: "tsuru/python"}
	opts = dcli.CreateContainerOptions{Name: cont3.Name}
	node, _, err = scheduler.Schedule(opts, &config)
	c.Assert(err, gocheck.IsNil)
	c.Check(node, gocheck.Equals, "server2")
}
예제 #3
0
func NewDockerClient(endpoint string) (*docker.Client, error) {
	if strings.HasPrefix(endpoint, "unix:") {
		return docker.NewClient(endpoint)
	} else if tlsVerify || tlsEnabled() {
		if tlsVerify {
			if e, err := pathExists(tlsCaCert); !e || err != nil {
				return nil, errors.New("TLS verification was requested, but CA cert does not exist")
			}
		}

		return docker.NewTLSClient(endpoint, tlsCert, tlsKey, tlsCaCert)
	}
	return docker.NewClient(endpoint)
}
예제 #4
0
파일: docker_test.go 프로젝트: nemx/tsuru
func (s *S) TestNewContainer(c *gocheck.C) {
	oldClusterNodes := clusterNodes
	clusterNodes = map[string]string{"server": s.server.URL()}
	defer func() { clusterNodes = oldClusterNodes }()
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	app := testing.NewFakeApp("app-name", "python", 1)
	rtesting.FakeRouter.AddBackend(app.GetName())
	defer rtesting.FakeRouter.RemoveBackend(app.GetName())
	cont, err := newContainer(app, getImage(app), []string{"docker", "run"})
	c.Assert(err, gocheck.IsNil)
	defer s.removeTestContainer(&cont)
	c.Assert(cont.ID, gocheck.Not(gocheck.Equals), "")
	c.Assert(cont, gocheck.FitsTypeOf, container{})
	c.Assert(cont.AppName, gocheck.Equals, app.GetName())
	c.Assert(cont.Type, gocheck.Equals, app.GetPlatform())
	u, _ := url.Parse(s.server.URL())
	host, _, _ := net.SplitHostPort(u.Host)
	c.Assert(cont.HostAddr, gocheck.Equals, host)
	port, err := getPort()
	c.Assert(err, gocheck.IsNil)
	c.Assert(cont.Port, gocheck.Equals, port)
	user, err := config.GetString("docker:ssh:user")
	c.Assert(err, gocheck.IsNil)
	dcli, _ := dockerClient.NewClient(s.server.URL())
	container, err := dcli.InspectContainer(cont.ID)
	c.Assert(err, gocheck.IsNil)
	c.Assert(container.Config.User, gocheck.Equals, user)
}
예제 #5
0
파일: docker.go 프로젝트: jmitchell/nomad
func (d *DockerDriver) Open(ctx *ExecContext, handleID string) (DriverHandle, error) {
	cleanupContainer, err := strconv.ParseBool(d.config.ReadDefault("docker.cleanup.container", "true"))
	if err != nil {
		return nil, fmt.Errorf("Unable to parse docker.cleanup.container: %s", err)
	}
	cleanupImage, err := strconv.ParseBool(d.config.ReadDefault("docker.cleanup.image", "true"))
	if err != nil {
		return nil, fmt.Errorf("Unable to parse docker.cleanup.image: %s", err)
	}

	// Split the handle
	pidBytes := []byte(strings.TrimPrefix(handleID, "DOCKER:"))
	pid := &dockerPID{}
	err = json.Unmarshal(pidBytes, pid)
	if err != nil {
		return nil, fmt.Errorf("Failed to parse handle '%s': %v", handleID, err)
	}
	d.logger.Printf("[INFO] driver.docker: re-attaching to docker process: %s", handleID)

	// Initialize docker API client
	dockerEndpoint := d.config.ReadDefault("docker.endpoint", "unix:///var/run/docker.sock")
	client, err := docker.NewClient(dockerEndpoint)
	if err != nil {
		return nil, fmt.Errorf("Failed to connect to docker.endpoint (%s): %s", dockerEndpoint, err)
	}

	// Look for a running container with this ID
	containers, err := client.ListContainers(docker.ListContainersOptions{
		Filters: map[string][]string{
			"id": []string{pid.ContainerID},
		},
	})
	if err != nil {
		return nil, fmt.Errorf("Failed to query for container %s: %v", pid.ContainerID, err)
	}

	found := false
	for _, container := range containers {
		if container.ID == pid.ContainerID {
			found = true
		}
	}
	if !found {
		return nil, fmt.Errorf("Failed to find container %s: %v", pid.ContainerID, err)
	}

	// Return a driver handle
	h := &dockerHandle{
		client:           client,
		cleanupContainer: cleanupContainer,
		cleanupImage:     cleanupImage,
		logger:           d.logger,
		imageID:          pid.ImageID,
		containerID:      pid.ContainerID,
		doneCh:           make(chan struct{}),
		waitCh:           make(chan error, 1),
	}
	go h.run()
	return h, nil
}
예제 #6
0
// ListContainers returns a slice of all containers in the cluster matching the
// given criteria.
func (c *Cluster) ListContainers(opts dcli.ListContainersOptions) ([]docker.APIContainers, error) {
	nodes, err := c.scheduler.Nodes()
	if err != nil {
		return nil, err
	}
	var wg sync.WaitGroup
	result := make(chan []docker.APIContainers, len(nodes))
	errs := make(chan error, len(nodes))
	for _, n := range nodes {
		wg.Add(1)
		client, _ := dcli.NewClient(n.Address)
		go func(n node) {
			defer wg.Done()
			if containers, err := n.ListContainers(opts); err != nil {
				errs <- err
			} else {
				result <- containers
			}
		}(node{id: n.ID, Client: client})
	}
	wg.Wait()
	var group []docker.APIContainers
	for {
		select {
		case containers := <-result:
			group = append(group, containers...)
		case err = <-errs:
		default:
			return group, err
		}
	}
}
예제 #7
0
func (s *S) TestProvisionRemoveOldUnitForward(c *gocheck.C) {
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	container, err := s.newContainer(nil)
	c.Assert(err, gocheck.IsNil)
	defer rtesting.FakeRouter.RemoveBackend(container.AppName)
	client, err := dockerClient.NewClient(s.server.URL())
	c.Assert(err, gocheck.IsNil)
	err = client.StartContainer(container.ID, nil)
	c.Assert(err, gocheck.IsNil)
	app := testing.NewFakeApp(container.AppName, "python", 0)
	unit := provision.Unit{
		Name:    container.ID,
		AppName: app.GetName(),
		Type:    app.GetPlatform(),
		Ip:      container.HostAddr,
		Status:  provision.StatusBuilding,
	}
	context := action.FWContext{Params: []interface{}{app, "", *container}, Previous: unit}
	result, err := provisionRemoveOldUnit.Forward(context)
	c.Assert(err, gocheck.IsNil)
	retUnit := result.(provision.Unit)
	c.Assert(retUnit, gocheck.DeepEquals, unit)
	_, err = getContainer(container.ID)
	c.Assert(err, gocheck.NotNil)
}
예제 #8
0
파일: main.go 프로젝트: rtlong/docker-util
func createClient() {
	var (
		dockerEndpoint string
		err            error
	)

	if dockerEndpoint = os.Getenv("DOCKER_HOST"); len(dockerEndpoint) == 0 {
		dockerEndpoint = "unix:///var/run/docker.sock"
	}

	if debug {
		log.Println("Connecting to Docker daemon via:", dockerEndpoint)
	}

	client, err = docker.NewClient(dockerEndpoint)
	if err != nil {
		log.Fatal(err)
	}

	dockerVersion, err = client.Version()
	if err != nil {
		log.Fatal("Could not connect to Docker daemon: ", err)
	}
	if debug {
		showDockerVersion()
	}
}
예제 #9
0
파일: runtime.go 프로젝트: zombor/galaxy
func NewServiceRuntime(configStore *config.Store, dns, hostIP string) *ServiceRuntime {
	var err error
	var client *docker.Client

	dockerZero, err := dockerBridgeIp()
	if err != nil {
		log.Fatalf("ERROR: Unable to find docker0 bridge: %s", err)
	}

	endpoint := GetEndpoint()

	if certPath := os.Getenv("DOCKER_CERT_PATH"); certPath != "" {
		cert := certPath + "/cert.pem"
		key := certPath + "/key.pem"
		ca := certPath + "/ca.pem"
		client, err = docker.NewTLSClient(endpoint, cert, key, ca)
	} else {
		client, err = docker.NewClient(endpoint)
	}

	if err != nil {
		log.Fatalf("ERROR: Unable to initialize docker client: %s: %s", err, endpoint)
	}

	client.HTTPClient.Timeout = 60 * time.Second

	return &ServiceRuntime{
		dns:          dns,
		configStore:  configStore,
		hostIP:       hostIP,
		dockerIP:     dockerZero,
		dockerClient: client,
	}
}
예제 #10
0
파일: slug.go 프로젝트: rochacon/cargo
// Run runs a slug process
func Run(slugUrl string, cmd ...string) (*dcli.Container, error) {
	docker, err := dcli.NewClient(getRandomServer())
	if err != nil {
		return nil, err
	}

	port := strconv.Itoa(getRandomPort())

	opts := dcli.CreateContainerOptions{
		"",
		&dcli.Config{
			Cmd:       cmd,
			Env:       []string{"PORT=" + port, "SLUG_URL=" + slugUrl},
			PortSpecs: []string{port + "/tcp"},
			Image:     "flynn/slugrunner",
			Tty:       true,
		},
	}

	container, err := docker.CreateContainer(opts)
	if err != nil {
		return nil, err
	}

	err = docker.StartContainer(container.ID, &dcli.HostConfig{})
	if err != nil {
		return nil, err
	}

	return docker.InspectContainer(container.ID)
}
예제 #11
0
func (s *S) TestRemoveUnitInSameHostAsAnotherUnitShouldEnqueueAnotherBind(c *gocheck.C) {
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	c1, err := s.newContainer(nil)
	c.Assert(err, gocheck.IsNil)
	c2, err := s.newContainer(nil)
	c.Assert(err, gocheck.IsNil)
	defer rtesting.FakeRouter.RemoveBackend(c1.AppName)
	client, err := dockerClient.NewClient(s.server.URL())
	c.Assert(err, gocheck.IsNil)
	err = client.StartContainer(c1.ID, nil)
	c.Assert(err, gocheck.IsNil)
	a := testing.NewFakeApp(c1.AppName, "python", 0)
	var p dockerProvisioner
	err = p.RemoveUnit(a, c1.ID)
	c.Assert(err, gocheck.IsNil)
	_, err = getContainer(c1.ID)
	c.Assert(err, gocheck.NotNil)
	_, err = getContainer(c2.ID)
	c.Assert(err, gocheck.IsNil)
	q, err := getQueue()
	c.Assert(err, gocheck.IsNil)
	message, err := q.Get(1e6)
	c.Assert(err, gocheck.IsNil)
	expected := &queue.Message{Action: app.BindService, Args: []string{a.GetName(), c2.ID}}
	c.Assert(message, gocheck.DeepEquals, expected)
}
예제 #12
0
func validateDockerInfo() (string, string) {
	client, err := dclient.NewClient(*docker.ArgDockerEndpoint)
	if err == nil {
		info, err := client.Info()
		if err == nil {
			execDriver := info.Get("ExecutionDriver")
			storageDriver := info.Get("Driver")
			desc := fmt.Sprintf("Docker exec driver is %s. Storage driver is %s.\n", execDriver, storageDriver)
			if docker.UseSystemd() {
				desc += "\tsystemd is being used to create cgroups.\n"
			} else {
				desc += "\tCgroups are being created through cgroup filesystem.\n"
			}
			if strings.Contains(execDriver, "native") {
				stateFile := docker.DockerStateDir()
				if !utils.FileExists(stateFile) {
					desc += fmt.Sprintf("\tDocker container state directory %q is not accessible.\n", stateFile)
					return Unsupported, desc
				}
				desc += fmt.Sprintf("\tDocker container state directory is at %q and is accessible.\n", stateFile)
				return Recommended, desc
			} else if strings.Contains(execDriver, "lxc") {
				return Supported, desc
			}
			return Unknown, desc
		}
	}
	return Unknown, "Docker remote API not reachable\n\t"
}
예제 #13
0
func (s *S) TestProvisionerStopSkipAlreadyStoppedContainers(c *gocheck.C) {
	dcli, _ := dockerClient.NewClient(s.server.URL())
	app := testing.NewFakeApp("almah", "static", 2)
	p := dockerProvisioner{}
	container, err := s.newContainer(&newContainerOpts{AppName: app.GetName()})
	c.Assert(err, gocheck.IsNil)
	defer s.removeTestContainer(container)
	err = dcli.StartContainer(container.ID, nil)
	c.Assert(err, gocheck.IsNil)
	dockerContainer, err := dcli.InspectContainer(container.ID)
	c.Assert(err, gocheck.IsNil)
	c.Assert(dockerContainer.State.Running, gocheck.Equals, true)
	container2, err := s.newContainer(&newContainerOpts{AppName: app.GetName()})
	c.Assert(err, gocheck.IsNil)
	defer s.removeTestContainer(container2)
	err = dcli.StartContainer(container2.ID, nil)
	c.Assert(err, gocheck.IsNil)
	err = dcli.StopContainer(container2.ID, 1)
	c.Assert(err, gocheck.IsNil)
	container2.setStatus(provision.StatusStopped.String())
	dockerContainer2, err := dcli.InspectContainer(container2.ID)
	c.Assert(err, gocheck.IsNil)
	c.Assert(dockerContainer2.State.Running, gocheck.Equals, false)
	err = p.Stop(app)
	c.Assert(err, gocheck.IsNil)
	dockerContainer, err = dcli.InspectContainer(container.ID)
	c.Assert(err, gocheck.IsNil)
	c.Assert(dockerContainer.State.Running, gocheck.Equals, false)
	dockerContainer2, err = dcli.InspectContainer(container2.ID)
	c.Assert(err, gocheck.IsNil)
	c.Assert(dockerContainer2.State.Running, gocheck.Equals, false)
}
예제 #14
0
파일: client.go 프로젝트: jgatkinsn/os
func NewClient(endpoint string) (*dockerClient.Client, error) {
	client, err := dockerClient.NewClient(endpoint)
	if err != nil {
		return nil, err
	}

	retry := false
	for i := 0; i < (MAX_WAIT / INTERVAL); i++ {
		_, err = client.Info()
		if err == nil {
			break
		}

		retry = true

		log.Infof("Waiting for Docker at %s", endpoint)
		time.Sleep(INTERVAL * time.Millisecond)
	}

	if err != nil {
		return nil, err
	}

	if retry {
		log.Infof("Connected to Docker at %s", endpoint)
	}
	return client, nil
}
예제 #15
0
func CreateCassandraAndStart(name, port string) (*docker.Container, error) {
	endpoint := "unix:///var/run/docker.sock"
	client, err := docker.NewClient(endpoint)
	if err != nil {
		return nil, err
	}

	hostConf := &docker.HostConfig{
		PortBindings: map[docker.Port][]docker.PortBinding{
			docker.Port("9042/tcp"): []docker.PortBinding{{
				HostIP:   "0.0.0.0",
				HostPort: port,
			}},
		},
	}
	/*hostConf := &docker.HostConfig{
		PublishAllPorts: true,
	}*/

	opts := docker.CreateContainerOptions{
		Name: name,
		Config: &docker.Config{
			Image: "spotify/cassandra:latest",
		},
		HostConfig: hostConf,
	}

	container, err := client.CreateContainer(opts)
	if err != nil {
		return nil, err
	}

	return container, client.StartContainer(container.ID, hostConf)
}
func main() {

	fmt.Println("dockerapi started...")
	time.Sleep(time.Millisecond * 5000)
	fmt.Println("action: " + ACTION)
	fmt.Println("containers: " + CONTAINERS)
	var containers = strings.Split(CONTAINERS, ",")
	var docker *dockerapi.Client
	var err error
	docker, err = dockerapi.NewClient(DOCKER_HOST)
	if err != nil {
		fmt.Println(err.Error())
	}
	err = docker.Ping()

	for i := range containers {
		fmt.Println(ACTION + " issued for " + containers[i])
		switch ACTION {
		case "stop":
			err = docker.StopContainer(containers[i], 5)
		case "start":
			err = docker.StartContainer(containers[i], nil)
		default:
			fmt.Println(ACTION + " unsupported action")
		}
		if err != nil {
			fmt.Println(err.Error())
		}
		time.Sleep(time.Millisecond * 2000)
	}
}
예제 #17
0
파일: docker.go 프로젝트: jmitchell/nomad
func (d *DockerDriver) Fingerprint(cfg *config.Config, node *structs.Node) (bool, error) {
	// Initialize docker API client
	dockerEndpoint := d.config.ReadDefault("docker.endpoint", "unix:///var/run/docker.sock")
	client, err := docker.NewClient(dockerEndpoint)
	if err != nil {
		return false, nil
	}

	_, err = strconv.ParseBool(d.config.ReadDefault("docker.cleanup.container", "true"))
	if err != nil {
		return false, fmt.Errorf("Unable to parse docker.cleanup.container: %s", err)
	}
	_, err = strconv.ParseBool(d.config.ReadDefault("docker.cleanup.image", "true"))
	if err != nil {
		return false, fmt.Errorf("Unable to parse docker.cleanup.image: %s", err)
	}

	env, err := client.Version()
	if err != nil {
		// Check the "no such file" error if the unix file is missing
		if strings.Contains(err.Error(), "no such file") {
			return false, nil
		}

		// We connected to the daemon but couldn't read the version so something
		// is broken.
		return false, err
	}
	node.Attributes["driver.docker"] = "true"
	node.Attributes["driver.docker.version"] = env.Get("Version")

	return true, nil
}
예제 #18
0
func newDockerClient() (*docker.Client, error) {
	if len(*tlscert) == 0 {
		return docker.NewClient(*serverIP)
	} else {
		return docker.NewTLSClient(*serverIP, *tlscert, *tlskey, *tlscacert)
	}
}
예제 #19
0
파일: container_test.go 프로젝트: slashk/os
func testDockerClientNames(t *testing.T) {
	assert := require.New(t)
	client, err := dockerClient.NewClient(config.DOCKER_HOST)

	assert.NoError(err, "")

	c, err := client.CreateContainer(dockerClient.CreateContainerOptions{
		Name: "foo",
		Config: &dockerClient.Config{
			Image: "ubuntu",
		},
	})

	assert.NoError(err, "")
	assert.Equal("foo", c.Name)

	c2, err := client.InspectContainer(c.ID)

	assert.NoError(err, "")
	assert.Equal("/foo", c2.Name)

	c2, err = inspect(client, c.ID)

	assert.NoError(err, "")
	assert.Equal("foo", c2.Name)

	client.RemoveContainer(dockerClient.RemoveContainerOptions{
		ID:    c2.ID,
		Force: true,
	})
}
func DockerStop(w rest.ResponseWriter, r *rest.Request) {
	logit.Info.Println("DockerStop called")
	req := DockerStopRequest{}
	err := r.DecodeJsonPayload(&req)
	if err != nil {
		logit.Error.Println(err.Error())
		rest.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	docker, err3 := dockerapi.NewClient("unix://var/run/docker.sock")
	if err3 != nil {
		logit.Error.Println("can't get connection to docker socket")
		rest.Error(w, err3.Error(), http.StatusInternalServerError)
		return
	}
	err3 = docker.StopContainer(req.ContainerName, 10)
	if err3 != nil {
		logit.Error.Println("can't stop container " + req.ContainerName)
		rest.Error(w, err3.Error(), http.StatusInternalServerError)
		return
	}

	var response DockerStopResponse
	response.Output = "success"
	w.WriteJson(&response)
}
예제 #21
0
func Init() {
	docker, err := dcli.NewClient("http://127.0.0.1:4243")
	DockerClient = docker
	if err != nil {
		revel.ERROR.Fatal(err)
	}
}
예제 #22
0
// New creates a new execution engine using the yaml config files in the
// specified directory. Only disableApparmor for development, docker alone isn't
// sufficient to fully sandbox the code.
func New(confPath string, disableApparmor bool) (result *Engine, err error) {
	result = &Engine{}
	configs, err := filepath.Glob(confPath + "/lang-*.yml")
	if err != nil {
		return
	}

	if len(configs) < 1 {
		err = fmt.Errorf("no languages found at path '%s'", confPath)
		return
	}

	result.client, err = docker.NewClient(endpoint)
	if err != nil {
		return
	}

	for _, config := range configs {
		var lang *Language
		lang, err = loadLanguage(config)
		if err != nil {
			err = fmt.Errorf("Error loading language '%s': %s", config, err)
			// fail everything if one language fails to load
			return
		}
		lang.client = result.client
		if disableApparmor {
			lang.disableAppArmor()
		}
		result.languages = append(result.languages, lang)
	}

	return
}
예제 #23
0
func (s *S) newContainer() (*container, error) {
	container := container{
		AppName:  "container",
		ID:       "id",
		IP:       "10.10.10.10",
		HostPort: "3333",
		Port:     "8888",
	}
	rtesting.FakeRouter.AddBackend(container.AppName)
	rtesting.FakeRouter.AddRoute(container.AppName, container.getAddress())
	client, err := dockerClient.NewClient(s.server.URL())
	if err != nil {
		return nil, err
	}
	config := docker.Config{
		Image:     "tsuru/python",
		Cmd:       []string{"ps"},
		PortSpecs: []string{"8888"},
	}
	c, err := client.CreateContainer(&config)
	if err != nil {
		return nil, err
	}
	container.ID = c.ID
	err = s.conn.Collection(s.collName).Insert(&container)
	if err != nil {
		return nil, err
	}
	return &container, err
}
예제 #24
0
func init() {
	var err error
	client, err = docker.NewClient("unix:///var/run/docker.sock")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error connecting to docker: %s\n", err.Error())
	}
}
예제 #25
0
func main() {
	flag.Parse()

	log.SetOutput(os.Stdout)
	log.SetLevel(log.DebugLevel)

	var client *docker.Client
	if os.Getenv("DOCKER_HOST") != "" {
		var err error
		certPath := os.Getenv("DOCKER_CERT_PATH")
		client, err = docker.NewTLSClient(os.Getenv("DOCKER_HOST"), path.Join(certPath, "cert.pem"), path.Join(certPath, "key.pem"), path.Join(certPath, "ca.pem"))
		if err != nil {
			log.Fatal(err)
		}
	} else {
		var err error
		client, err = docker.NewClient("unix:///var/run/docker.sock")
		if err != nil {
			log.Fatal(err)
		}
	}

	handler := Handler{docker: client, domain: fmt.Sprintf("%s.", *domain)}

	server := dns.Server{}
	server.Handler = &handler
	server.Net = *network
	server.Addr = *addr

	err := server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}
예제 #26
0
func main() {
	host := os.Getenv("DOCKER_HOST")
	if host == "" {
		log.Fatalln("Please provide DOCKER_HOST environment variable!")
	}

	client, err := docker.NewClient(host)
	if err != nil {
		log.Fatalln(err)
	}

	gateway := NewGateway(client)
	if gateway.DefaultDomain == "" {
		log.Fatalln("Please provide GW_DOMAIN environment variable!")
	}

	listener := NewListener(client, gateway)
	listener.Init()
	go listener.Start()

	listenHost := getEnvVar("GW_HOST", "0.0.0.0")
	listenPort := getEnvVar("GW_PORT", "2377")

	err = gateway.Start(listenHost + ":" + listenPort)
	if err != nil {
		log.Fatalln(err)
	}
}
예제 #27
0
파일: docker.go 프로젝트: stigkj/nomad
// dockerClient creates *docker.Client. In test / dev mode we can use ENV vars
// to connect to the docker daemon. In production mode we will read
// docker.endpoint from the config file.
func (d *DockerDriver) dockerClient() (*docker.Client, error) {
	if client != nil {
		return client, nil
	}

	var err error
	createClient.Do(func() {
		// Default to using whatever is configured in docker.endpoint. If this is
		// not specified we'll fall back on NewClientFromEnv which reads config from
		// the DOCKER_* environment variables DOCKER_HOST, DOCKER_TLS_VERIFY, and
		// DOCKER_CERT_PATH. This allows us to lock down the config in production
		// but also accept the standard ENV configs for dev and test.
		dockerEndpoint := d.config.Read("docker.endpoint")
		if dockerEndpoint != "" {
			cert := d.config.Read("docker.tls.cert")
			key := d.config.Read("docker.tls.key")
			ca := d.config.Read("docker.tls.ca")

			if cert+key+ca != "" {
				d.logger.Printf("[DEBUG] driver.docker: using TLS client connection to %s", dockerEndpoint)
				client, err = docker.NewTLSClient(dockerEndpoint, cert, key, ca)
			} else {
				d.logger.Printf("[DEBUG] driver.docker: using standard client connection to %s", dockerEndpoint)
				client, err = docker.NewClient(dockerEndpoint)
			}
			return
		}

		d.logger.Println("[DEBUG] driver.docker: using client connection initialized from environment")
		client, err = docker.NewClientFromEnv()
	})
	return client, err
}
예제 #28
0
파일: container.go 프로젝트: Empia/block
func notmain() {
	client, err := dcli.NewClient("http://127.0.0.1:4243")
	if err != nil {
		panic(err)
	}

	outReader, outWriter := io.Pipe()
	errReader, errWriter := io.Pipe()
	runner := NewRunner(client, "ruby", "puts \"yo i'm rubby #{7*7}\"")
	runner.OutStream = outWriter
	runner.ErrStream = errWriter

	go tailOutput("stdout", outReader)
	go tailOutput("stderr", errReader)

	log.Println("Running code...")
	if _, err := runner.Run(10000); err != nil {
		panic(err)
	}

	outReader.Close()
	errReader.Close()

	time.Sleep(1e9)
}
예제 #29
0
// Get a *docker.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) (*docker.Client, error) {
	if len(dockerEndpoint) > 0 {
		glog.Infof("Connecting to docker on %s", dockerEndpoint)
		return docker.NewClient(dockerEndpoint)
	}
	return docker.NewClientFromEnv()
}
예제 #30
0
파일: docker_test.go 프로젝트: nemx/tsuru
func (s *S) TestRemoveContainerIgnoreErrors(c *gocheck.C) {
	handler, cleanup := startSSHAgentServer("")
	defer cleanup()
	fexec := &etesting.FakeExecutor{}
	setExecut(fexec)
	defer setExecut(nil)
	err := newImage("tsuru/python", s.server.URL())
	c.Assert(err, gocheck.IsNil)
	container, err := s.newContainer(nil)
	c.Assert(err, gocheck.IsNil)
	defer s.removeTestContainer(container)
	client, _ := dockerClient.NewClient(s.server.URL())
	err = client.RemoveContainer(container.ID)
	c.Assert(err, gocheck.IsNil)
	err = container.remove()
	c.Assert(err, gocheck.IsNil)
	c.Assert(handler.requests[0].Method, gocheck.Equals, "DELETE")
	c.Assert(handler.requests[0].URL.Path, gocheck.Equals, "/container/"+container.IP)
	coll := collection()
	defer coll.Close()
	err = coll.FindId(container.ID).One(&container)
	c.Assert(err, gocheck.NotNil)
	c.Assert(err.Error(), gocheck.Equals, "not found")
	c.Assert(rtesting.FakeRouter.HasRoute(container.AppName, container.getAddress()), gocheck.Equals, false)
}