Skip to content

Commit

Permalink
Rollback to use dynamic port binding
Browse files Browse the repository at this point in the history
  • Loading branch information
junbeomlee committed Nov 1, 2018
1 parent 88d0206 commit fe94c90
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 4 deletions.
47 changes: 43 additions & 4 deletions container/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,20 @@ package container

import (
"context"

"docker.io/go-docker/api/types"

"errors"

"net"
"strconv"
"time"

"docker.io/go-docker/api/types"
"github.com/it-chain/iLogger"
"github.com/it-chain/tesseract"
"github.com/it-chain/tesseract/docker"
"github.com/it-chain/tesseract/rpc"
)

var ErrFailedPullImage = errors.New("failed to pull image")
var defaultPort = "50001"

func Create(config tesseract.ContainerConfig) (DockerContainer, error) {

Expand All @@ -50,6 +49,14 @@ func Create(config tesseract.ContainerConfig) (DockerContainer, error) {
return DockerContainer{}, ErrFailedPullImage
}

if config.Network == nil {
var port string
if port, err = getAvailablePort(); err != nil {
return DockerContainer{}, err
}
config.Port = port
}

// Create Docker
res, err := docker.CreateContainer(
config,
Expand Down Expand Up @@ -145,3 +152,35 @@ func retryConnectWithTimeOut(ipAddress string, port string, timeout time.Duratio
return client, nil
}
}

func getAvailablePort() (string, error) {
portList, err := docker.GetPorts()
if err != nil {
return "", err
}

findLoop:
for {
portNumber, err := strconv.Atoi(defaultPort)
if err != nil {
return "", err
}
for _, portInfo := range portList {
if portNumber == int(portInfo.PublicPort) || portNumber == int(portInfo.PrivatePort) {
portNumber++
defaultPort = strconv.Itoa(portNumber)
continue findLoop
}
}

lis, err := net.Listen("tcp", "127.0.0.1:"+defaultPort)

if err == nil {
lis.Close()
return defaultPort, nil
}

portNumber++
defaultPort = strconv.Itoa(portNumber)
}
}
27 changes: 27 additions & 0 deletions docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,33 @@ func FindVolumeByName(name string) (tesseract.Volume, error) {
return tesseract.Volume{}, nil
}

func GetPorts() ([]types.Port, error) {

ctx := context.Background()
cli, _ := docker.NewEnvClient()
defer cli.Close()

portList := make([]types.Port, 0)
containerList, err := cli.ContainerList(ctx, types.ContainerListOptions{All: true})

if err != nil {
return portList, err
}

for _, container := range containerList {
for _, port := range container.Ports {
portInfo := types.Port{
IP: port.IP,
PrivatePort: port.PrivatePort,
PublicPort: port.PublicPort,
}
portList = append(portList, portInfo)
}
}

return portList, nil
}

func isVolumeEmpty(vol tesseract.Volume) bool {
return reflect.DeepEqual(vol, tesseract.Volume{})
}
Expand Down

0 comments on commit fe94c90

Please sign in to comment.