Skip to content

Commit

Permalink
Merged release/1.16.0 into master
Browse files Browse the repository at this point in the history
  • Loading branch information
aacebedo committed Nov 6, 2016
2 parents 9e223d7 + c937be1 commit b1e322f
Show file tree
Hide file tree
Showing 14 changed files with 469 additions and 230 deletions.
39 changes: 32 additions & 7 deletions Godeps/Godeps.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

65 changes: 65 additions & 0 deletions src/core/cmdline.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/* cmdline.go
*
* Copyright (C) 2016 Alexandre ACEBEDO
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/

package core

import (
"fmt"
"gopkg.in/alecthomas/kingpin.v2"
"github.com/aacebedo/dnsdock/src/utils"
"strconv"
)


const (
// VERSION dnsdock version
VERSION = "1.16.0"
)

// CommandLine structure handling parameter parsing
type CommandLine struct{}

// ParseParameters Parse parameters
func (cmdline *CommandLine) ParseParameters(rawParams []string) (res *utils.Config, err error) {
res = utils.NewConfig()

app := kingpin.New("dnsdock", "Automatic DNS for docker containers.")
app.Version(VERSION)
app.HelpFlag.Short('h')
nameservers := app.Flag("nameserver", "Comma separated list of DNS server(s) for unmatched requests").Strings()
dns := app.Flag("dns", "Listen DNS requests on this address").Default(res.DnsAddr).Short('d').String()
http := app.Flag("http", "Listen HTTP requests on this address").Default(res.HttpAddr).Short('t').String()
domain := app.Flag("domain", "Domain that is appended to all requests").Default(res.Domain.String()).String()
environment := app.Flag("environment", "Optional context before domain suffix").Default("").String()
docker := app.Flag("docker", "Path to the docker socket").Default(res.DockerHost).String()
tlsverify := app.Flag("tlsverify", "Enable mTLS when connecting to docker").Default(strconv.FormatBool(res.TlsVerify)).Bool()
tlscacert := app.Flag("tlscacert", "Path to CA certificate").Default(res.TlsCaCert).String()
tlscert := app.Flag("tlscert", "Path to Client certificate").Default(res.TlsCert).String()
tlskey := app.Flag("tlskey", "Path to client certificate private key").Default(res.TlsKey).String()
ttl := app.Flag("ttl", "TTL for matched requests").Default(strconv.FormatInt(int64(res.Ttl), 10)).Int()
createAlias := app.Flag("alias", "Automatically create an alias with just the container name.").Default(strconv.FormatBool(res.CreateAlias)).Bool()
verbose := app.Flag("verbose", "Verbose mode.").Default(strconv.FormatBool(res.Verbose)).Short('v').Bool()
quiet := app.Flag("quiet", "Quiet mode.").Default(strconv.FormatBool(res.Quiet)).Short('q').Bool()

kingpin.MustParse(app.Parse(rawParams))

res.Verbose = *verbose
res.Quiet = *quiet
res.Nameserver = *nameservers
res.DnsAddr = *dns
res.HttpAddr = *http
res.Domain = utils.NewDomain(fmt.Sprintf("%s.%s", *environment, *domain))
res.DockerHost = *docker
res.TlsVerify = *tlsverify
res.TlsCaCert = *tlscacert
res.TlsCert = *tlscert
res.TlsKey = *tlskey
res.Ttl = *ttl
res.CreateAlias = *createAlias
return
}
86 changes: 57 additions & 29 deletions src/docker.go → src/core/docker.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,41 @@
package main
/* docker.go
*
* Copyright (C) 2016 Alexandre ACEBEDO
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/

package core

import (
"crypto/tls"
"errors"
"github.com/docker/engine-api/client"
"github.com/docker/engine-api/types"
eventtypes "github.com/docker/engine-api/types/events"
"github.com/docker/engine-api/types/network"
"github.com/vdemeester/docker-events"
"log"
"github.com/aacebedo/dnsdock/src/utils"
"github.com/aacebedo/dnsdock/src/servers"
"net"
"regexp"
"strconv"
"strings"

"golang.org/x/net/context"
)

// DockerManager is the entrypoint to the docker daemon
type DockerManager struct {
config *Config
list ServiceListProvider
config *utils.Config
list servers.ServiceListProvider
client *client.Client
cancel context.CancelFunc
}

// NewDockerManager creates a new DockerManager
func NewDockerManager(c *Config, list ServiceListProvider, tlsConfig *tls.Config) (*DockerManager, error) {
func NewDockerManager(c *utils.Config, list servers.ServiceListProvider, tlsConfig *tls.Config) (*DockerManager, error) {
defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
dclient, err := client.NewClient(c.dockerHost, "v1.22", nil, defaultHeaders)
dclient, err := client.NewClient(c.DockerHost, "v1.22", nil, defaultHeaders)

if err != nil {
return nil, err
Expand All @@ -42,29 +49,29 @@ func (d *DockerManager) Start() error {
ctx, cancel := context.WithCancel(context.Background())
d.cancel = cancel
startHandler := func(m eventtypes.Message) {
log.Printf("Started container '%s'", m.ID)
logger.Debugf("Started container '%s'", m.ID)
service, err := d.getService(m.ID)
if err != nil {
log.Println(err)
logger.Errorf("%s", err)
} else {
d.list.AddService(m.ID, *service)
}
}

stopHandler := func(m eventtypes.Message) {
log.Printf("Stopped container '%s'", m.ID)
logger.Debugf("Stopped container '%s'", m.ID)
d.list.RemoveService(m.ID)
}

renameHandler := func(m eventtypes.Message) {
oldName, ok := m.Actor.Attributes["oldName"]
name, ok2 := m.Actor.Attributes["oldName"]
if ok && ok2 {
log.Printf("Renamed container '%s' into '%s'", oldName, name)
logger.Debugf("Renamed container '%s' into '%s'", oldName, name)
d.list.RemoveService(oldName)
service, err := d.getService(m.ID)
if err != nil {
log.Println(err)
logger.Errorf("%s", err)
} else {
d.list.AddService(m.ID, *service)
}
Expand All @@ -88,7 +95,7 @@ func (d *DockerManager) Start() error {
for _, container := range containers {
service, err := d.getService(container.ID)
if err != nil {
log.Println(err)
logger.Errorf("%s", err)
continue
}
d.list.AddService(container.ID, *service)
Expand All @@ -102,33 +109,32 @@ func (d *DockerManager) Stop() {
d.cancel()
}

func (d *DockerManager) getService(id string) (*Service, error) {
func (d *DockerManager) getService(id string) (*servers.Service, error) {
desc, err := d.client.ContainerInspect(context.Background(), id)
if err != nil {
return nil, err
}

service := NewService()
service := servers.NewService()
service.Aliases = make([]string, 0)

service.Image = getImageName(desc.Config.Image)
if imageNameIsSHA(service.Image, desc.Image) {
log.Println("Warning: Can't route ", id[:10], ", image", service.Image, "is not a tag.")
logger.Warningf("Warning: Can't route %s, image %s is not a tag.", id[:10], service.Image)
service.Image = ""
}
service.Name = cleanContainerName(desc.Name)

switch len(desc.NetworkSettings.Networks) {
case 0:
log.Println("Warning, no IP address found for container ", desc.Name)
logger.Warningf("Warning, no IP address found for container '%s' ", desc.Name)
default:
v := make([]*network.EndpointSettings, 0, len(desc.NetworkSettings.Networks))
for _, value := range desc.NetworkSettings.Networks {
v = append(v, value)
ip := net.ParseIP(value.IPAddress)
if ip != nil {
service.IPs = append(service.IPs,ip)
}
}
if len(v) > 1 {
log.Println("Warning, Multiple IP address found for container ", desc.Name, ". Only the first address will be used")
}
service.IP = net.ParseIP(v[0].IPAddress)
}

service = overrideFromLabels(service, desc.Config.Labels)
Expand All @@ -137,7 +143,7 @@ func (d *DockerManager) getService(id string) (*Service, error) {
return nil, errors.New("Skipping " + id)
}

if d.config.createAlias {
if d.config.CreateAlias {
service.Aliases = append(service.Aliases, service.Name)
}
return service, nil
Expand Down Expand Up @@ -183,7 +189,7 @@ func splitEnv(in []string) (out map[string]string) {
return
}

func overrideFromLabels(in *Service, labels map[string]string) (out *Service) {
func overrideFromLabels(in *servers.Service, labels map[string]string) (out *servers.Service) {
var region string
for k, v := range labels {
if k == "com.dnsdock.ignore" {
Expand Down Expand Up @@ -223,9 +229,20 @@ func overrideFromLabels(in *Service, labels map[string]string) (out *Service) {
if k == "com.dnsdock.ip_addr" {
ipAddr := net.ParseIP(v)
if ipAddr != nil {
in.IP = ipAddr
in.IPs = in.IPs[:0]
in.IPs = append(in.IPs, ipAddr)
}
}

if k == "com.dnsdock.prefix" {
addrs := make([]net.IP, 0)
for _, value := range in.IPs {
if strings.HasPrefix(value.String(), v) {
addrs = append(addrs, value)
}
}
in.IPs = addrs
}
}

if len(region) > 0 {
Expand All @@ -235,7 +252,7 @@ func overrideFromLabels(in *Service, labels map[string]string) (out *Service) {
return
}

func overrideFromEnv(in *Service, env map[string]string) (out *Service) {
func overrideFromEnv(in *servers.Service, env map[string]string) (out *servers.Service) {
var region string
for k, v := range env {
if k == "DNSDOCK_IGNORE" || k == "SERVICE_IGNORE" {
Expand Down Expand Up @@ -275,9 +292,20 @@ func overrideFromEnv(in *Service, env map[string]string) (out *Service) {
if k == "DNSDOCK_IPADDRESS" {
ipAddr := net.ParseIP(v)
if ipAddr != nil {
in.IP = ipAddr
in.IPs = in.IPs[:0]
in.IPs = append(in.IPs, ipAddr)
}
}

if k == "DNSDOCK_PREFIX" {
addrs := make([]net.IP, 0)
for _, value := range in.IPs {
if strings.HasPrefix(value.String(), v) {
addrs = append(addrs, value)
}
}
in.IPs = addrs
}
}

if len(region) > 0 {
Expand Down
15 changes: 12 additions & 3 deletions src/docker_test.go → src/core/docker_test.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,17 @@
package main
/* docker_test.go
*
* Copyright (C) 2016 Alexandre ACEBEDO
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/

package core

import (
"reflect"
"testing"
"github.com/aacebedo/dnsdock/src/servers"
)

func TestGetImageName(t *testing.T) {
Expand Down Expand Up @@ -68,8 +77,8 @@ func TestSplitEnv(t *testing.T) {
}

func TestOverrideFromEnv(t *testing.T) {
getService := func() *Service {
service := NewService()
getService := func() *servers.Service {
service := servers.NewService()
service.Name = "myfoo"
service.Image = "mybar"
return service
Expand Down
Loading

0 comments on commit b1e322f

Please sign in to comment.