From 2f8caac175faeba004352e0f74f94834d39df1be Mon Sep 17 00:00:00 2001 From: Melanie Thielker Date: Thu, 3 Nov 2016 19:26:37 +0000 Subject: [PATCH 01/11] Allow tag com.dnsdock.prefix to select which of a container's IPs is added For containers that are both on a private, internal network and a bridge network, dnsdock often chooses the address of the internal network which is not accessible from the host. Setting the prefix to the address prefix the bridge network uses allows to prevent this. Usage: -l com.dnsdock.prefix=172.17.0. --- src/docker.go | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/docker.go b/src/docker.go index 345aa97..2d6ad91 100644 --- a/src/docker.go +++ b/src/docker.go @@ -117,18 +117,33 @@ func (d *DockerManager) getService(id string) (*Service, error) { service.Image = "" } service.Name = cleanContainerName(desc.Name) + + prefix := "" + if v, ok := desc.Config.Labels["com.dnsdock.prefix"]; ok { + prefix = v; + } + if v, ok := splitEnv(desc.Config.Env)["DNSDOCK_PREFIX"]; ok { + prefix = v; + } + switch len(desc.NetworkSettings.Networks) { case 0: log.Println("Warning, no IP address found for container ", desc.Name) default: v := make([]*network.EndpointSettings, 0, len(desc.NetworkSettings.Networks)) for _, value := range desc.NetworkSettings.Networks { - v = append(v, value) + if prefix == "" || strings.HasPrefix(value.IPAddress, prefix) { + v = append(v, value) + } } 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) + } else if len(v) == 0 { + log.Println("Warning, no valid IP address found for container ", desc.Name) + } else { + service.IP = net.ParseIP(v[0].IPAddress) } - service.IP = net.ParseIP(v[0].IPAddress) } service = overrideFromLabels(service, desc.Config.Labels) From a0ff9a1bd44fef4679d20fb8c8013b39e5f204af Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sat, 5 Nov 2016 19:22:35 +0100 Subject: [PATCH 02/11] Collecting multiple IPs from containers --- src/dnsserver.go | 51 +++++++++++++++++++++++++++++------------------- src/docker.go | 10 ++++++++-- src/http.go | 2 +- 3 files changed, 40 insertions(+), 23 deletions(-) diff --git a/src/dnsserver.go b/src/dnsserver.go index db5bb97..ada1541 100644 --- a/src/dnsserver.go +++ b/src/dnsserver.go @@ -16,7 +16,7 @@ import ( type Service struct { Name string Image string - IP net.IP + IPs []net.IP TTL int Aliases []string } @@ -78,22 +78,26 @@ func (s *DNSServer) Stop() { // AddService adds a new container and thus new DNS records func (s *DNSServer) AddService(id string, service Service) { - defer s.lock.Unlock() - s.lock.Lock() - - id = s.getExpandedID(id) - s.services[id] = &service - - if s.config.verbose { - log.Println("Added service:", id, service) - } - - for _, alias := range service.Aliases { - if s.config.verbose { - log.Println("Handling DNS requests for " + alias + ".") - } - s.mux.HandleFunc(alias+".", s.handleRequest) - } + if len(service.IPs) > 0 { + defer s.lock.Unlock() + s.lock.Lock() + + id = s.getExpandedID(id) + s.services[id] = &service + + if s.config.verbose { + log.Println("Added service:", id, service) + } + + for _, alias := range service.Aliases { + if s.config.verbose { + log.Println("Handling DNS requests for " + alias + ".") + } + s.mux.HandleFunc(alias+".", s.handleRequest) + } + } else { + log.Println("Service '"+id+"' ignored: No IP provided:", id) + } } // RemoveService removes a new container and thus DNS records @@ -222,8 +226,15 @@ func (s *DNSServer) makeServiceA(n string, service *Service) dns.RR { Ttl: uint32(ttl), } - rr.A = service.IP - + if len(service.IPs) != 0 { + if len(service.IPs) > 1 { + log.Println("Warning, Multiple IP address found for container ", service.Name, ". Only the first address will be used") + } + rr.A = service.IPs[0] + } else { + log.Println("Warning, no valid IP address found for container ", service.Name) + } + return rr } @@ -382,7 +393,7 @@ func (s *DNSServer) queryIP(query string) chan *Service { s.lock.RLock() for _, service := range s.services { - if service.IP.String() == ip { + if service.IPs[0].String() == ip { c <- service } } diff --git a/src/docker.go b/src/docker.go index 2d6ad91..58a9a13 100644 --- a/src/docker.go +++ b/src/docker.go @@ -143,6 +143,10 @@ func (d *DockerManager) getService(id string) (*Service, error) { log.Println("Warning, no valid IP address found for container ", desc.Name) } else { service.IP = net.ParseIP(v[0].IPAddress) + ip := net.ParseIP(value.IPAddress) + if ip != nil { + service.IPs = append(service.IPs,ip) + } } } @@ -238,7 +242,8 @@ 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) } } } @@ -290,7 +295,8 @@ 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) } } } diff --git a/src/http.go b/src/http.go index 6f41675..5347175 100644 --- a/src/http.go +++ b/src/http.go @@ -99,7 +99,7 @@ func (s *HTTPServer) addService(w http.ResponseWriter, req *http.Request) { return } - if service.IP == nil { + if len(service.IPs) == 0 || service.IPs[0] == nil { http.Error(w, "Property \"ip\" is required", http.StatusInternalServerError) return } From a63662ca22f9e32931022df47f190ead551703d3 Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sat, 5 Nov 2016 19:22:55 +0100 Subject: [PATCH 03/11] Filtering collected ips using the prefix --- src/docker.go | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/src/docker.go b/src/docker.go index 58a9a13..38188d4 100644 --- a/src/docker.go +++ b/src/docker.go @@ -6,7 +6,6 @@ import ( "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" "net" @@ -118,31 +117,11 @@ func (d *DockerManager) getService(id string) (*Service, error) { } service.Name = cleanContainerName(desc.Name) - prefix := "" - if v, ok := desc.Config.Labels["com.dnsdock.prefix"]; ok { - prefix = v; - } - if v, ok := splitEnv(desc.Config.Env)["DNSDOCK_PREFIX"]; ok { - prefix = v; - } - switch len(desc.NetworkSettings.Networks) { case 0: log.Println("Warning, no IP address found for container ", desc.Name) default: - v := make([]*network.EndpointSettings, 0, len(desc.NetworkSettings.Networks)) for _, value := range desc.NetworkSettings.Networks { - if prefix == "" || strings.HasPrefix(value.IPAddress, prefix) { - v = append(v, value) - } - } - 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) - } else if len(v) == 0 { - log.Println("Warning, no valid IP address found for container ", desc.Name) - } else { - service.IP = net.ParseIP(v[0].IPAddress) ip := net.ParseIP(value.IPAddress) if ip != nil { service.IPs = append(service.IPs,ip) @@ -246,6 +225,19 @@ func overrideFromLabels(in *Service, labels map[string]string) (out *Service) { in.IPs = append(in.IPs, ipAddr) } } + + if k == "com.dnsdock.prefix" { + addrs := make([]net.IP, 0) + for _, value := range in.IPs { + log.Printf(value.String()) + log.Printf(v) + + if strings.HasPrefix(value.String(), v) { + addrs = append(addrs, value) + } + } + in.IPs = addrs + } } if len(region) > 0 { @@ -299,6 +291,16 @@ func overrideFromEnv(in *Service, env map[string]string) (out *Service) { 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 { From 363af15be37ceb952682681fa0f3a01739663b22 Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sat, 5 Nov 2016 20:06:58 +0100 Subject: [PATCH 04/11] Switched to go-logging framework --- Godeps/Godeps.json | 10 ++++++++- src/config.go | 3 +-- src/dnsserver.go | 54 ++++++++++++++++------------------------------ src/docker.go | 22 ++++++++----------- src/http.go | 16 ++++++-------- src/loggers.go | 52 ++++++++++++++++++++++++++++++++++++++++++++ src/main.go | 16 +++++++------- 7 files changed, 105 insertions(+), 68 deletions(-) create mode 100644 src/loggers.go diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index c5f51af..88e82b6 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,7 +1,10 @@ { - "ImportPath": "github.com/tonistiigi/dnsdock", + "ImportPath": "github.com/aacebedo/dnsdock", "GoVersion": "go1.6", "GodepVersion": "v74", + "Packages": [ + "./..." + ], "Deps": [ { "ImportPath": "github.com/Microsoft/go-winio", @@ -132,6 +135,11 @@ "ImportPath": "github.com/miekg/dns", "Rev": "5d001d020961ae1c184f9f8152fdc73810481677" }, + { + "ImportPath": "github.com/op/go-logging", + "Comment": "v1-7-g970db52", + "Rev": "970db520ece77730c7e4724c61121037378659d9" + }, { "ImportPath": "github.com/opencontainers/runc/libcontainer/user", "Comment": "v1.0.0-rc1-50-g7221e38", diff --git a/src/config.go b/src/config.go index 467f02e..4e11536 100644 --- a/src/config.go +++ b/src/config.go @@ -51,8 +51,7 @@ type Config struct { tlsVerify bool tlsCaCert string tlsCert string - tlsKey string - verbose bool + tlsKey string httpAddr string ttl int createAlias bool diff --git a/src/dnsserver.go b/src/dnsserver.go index ada1541..5cf0755 100644 --- a/src/dnsserver.go +++ b/src/dnsserver.go @@ -2,7 +2,6 @@ package main import ( "errors" - "log" "net" "regexp" "strings" @@ -52,9 +51,7 @@ func NewDNSServer(c *Config) *DNSServer { lock: &sync.RWMutex{}, } - if s.config.verbose { - log.Println("Handling DNS requests for " + c.domain.String() + ".") - } + logger.Debugf("Handling DNS requests for '%s'.", c.domain.String()) s.mux = dns.NewServeMux() s.mux.HandleFunc(c.domain.String()+".", s.handleRequest) @@ -84,19 +81,15 @@ func (s *DNSServer) AddService(id string, service Service) { id = s.getExpandedID(id) s.services[id] = &service - - if s.config.verbose { - log.Println("Added service:", id, service) - } + + logger.Debugf("Added service: '%s': %s.", id, service) for _, alias := range service.Aliases { - if s.config.verbose { - log.Println("Handling DNS requests for " + alias + ".") - } + logger.Debugf("Handling DNS requests for '%s'.", alias) s.mux.HandleFunc(alias+".", s.handleRequest) } } else { - log.Println("Service '"+id+"' ignored: No IP provided:", id) + logger.Warningf("Service '%s' ignored: No IP provided:", id, id) } } @@ -116,9 +109,7 @@ func (s *DNSServer) RemoveService(id string) error { delete(s.services, id) - if s.config.verbose { - log.Println("Stopped service:", id) - } + logger.Debugf("Stopped service '%s'", id) return nil } @@ -174,18 +165,16 @@ func (s *DNSServer) listDomains(service *Service) chan string { } func (s *DNSServer) handleForward(w dns.ResponseWriter, r *dns.Msg) { - if s.config.verbose { - log.Println("Using DNS forwarding for " + r.Question[0].Name) - log.Println("Forwarding DNS nameservers: " + s.config.nameserver.String()) - } + + logger.Debugf("Using DNS forwarding for '%s'",r.Question[0].Name) + logger.Debugf("Forwarding DNS nameservers: %s",s.config.nameserver.String()) + // Otherwise just forward the request to another server c := new(dns.Client) // look at each nameserver, stop on success for i := range s.config.nameserver { - if s.config.verbose { - log.Println("Using nameserver " + s.config.nameserver[i]) - } + logger.Debugf("Using nameserver %s", s.config.nameserver[i]) in, _, err := c.Exchange(r, s.config.nameserver[i]) if err == nil { @@ -194,7 +183,7 @@ func (s *DNSServer) handleForward(w dns.ResponseWriter, r *dns.Msg) { } if i == (len(s.config.nameserver) - 1) { - log.Println("Error forwarding DNS: " + err.Error() + ": fatal, no more nameservers to try") + logger.Fatalf("DNS fowarding for '%s' failed: no more nameservers to try", err.Error()) // Send failure reply m := new(dns.Msg) @@ -204,7 +193,7 @@ func (s *DNSServer) handleForward(w dns.ResponseWriter, r *dns.Msg) { w.WriteMsg(m) } else { - log.Println("Error forwarding DNS: " + err.Error() + ": trying next nameserver...") + logger.Errorf("DNS fowarding for '%s' failed: trying next nameserver...", err.Error()) } } } @@ -228,11 +217,11 @@ func (s *DNSServer) makeServiceA(n string, service *Service) dns.RR { if len(service.IPs) != 0 { if len(service.IPs) > 1 { - log.Println("Warning, Multiple IP address found for container ", service.Name, ". Only the first address will be used") + logger.Warningf("Multiple IP address found for container '%s'. Only the first address will be used", service.Name) } rr.A = service.IPs[0] } else { - log.Println("Warning, no valid IP address found for container ", service.Name) + logger.Errorf("No valid IP address found for container ", service.Name) } return rr @@ -287,9 +276,7 @@ func (s *DNSServer) handleRequest(w dns.ResponseWriter, r *dns.Msg) { query = query[:len(query)-1] } - if s.config.verbose { - log.Println("DNS request for query " + query + " from remote " + w.RemoteAddr().String()) - } + logger.Debugf("DNS request for query '%s' from remote '%s'", w.RemoteAddr().String(), w.RemoteAddr()) for service := range s.queryServices(query) { var rr dns.RR @@ -308,9 +295,8 @@ func (s *DNSServer) handleRequest(w dns.ResponseWriter, r *dns.Msg) { return } - if s.config.verbose { - log.Println("DNS record found for " + query) - } + logger.Debugf("DNS record found for query '%s'",query) + m.Answer = append(m.Answer, rr) } @@ -318,9 +304,7 @@ func (s *DNSServer) handleRequest(w dns.ResponseWriter, r *dns.Msg) { if len(m.Answer) == 0 { m.Ns = s.createSOA() m.SetRcode(r, dns.RcodeNameError) // NXDOMAIN - if s.config.verbose { - log.Println("No DNS record found for " + query) - } + logger.Debugf("No DNS record found for query '%s'",query) } w.WriteMsg(m) diff --git a/src/docker.go b/src/docker.go index 38188d4..f7b0deb 100644 --- a/src/docker.go +++ b/src/docker.go @@ -7,7 +7,6 @@ import ( "github.com/docker/engine-api/types" eventtypes "github.com/docker/engine-api/types/events" "github.com/vdemeester/docker-events" - "log" "net" "regexp" "strconv" @@ -41,17 +40,17 @@ 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) } @@ -59,11 +58,11 @@ func (d *DockerManager) Start() error { 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) } @@ -87,7 +86,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) @@ -112,14 +111,14 @@ func (d *DockerManager) getService(id string) (*Service, error) { 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: for _, value := range desc.NetworkSettings.Networks { ip := net.ParseIP(value.IPAddress) @@ -229,10 +228,7 @@ func overrideFromLabels(in *Service, labels map[string]string) (out *Service) { if k == "com.dnsdock.prefix" { addrs := make([]net.IP, 0) for _, value := range in.IPs { - log.Printf(value.String()) - log.Printf(v) - - if strings.HasPrefix(value.String(), v) { + if strings.HasPrefix(value.String(), v) { addrs = append(addrs, value) } } diff --git a/src/http.go b/src/http.go index 5347175..f0ca4da 100644 --- a/src/http.go +++ b/src/http.go @@ -3,7 +3,6 @@ package main import ( "encoding/json" "github.com/gorilla/mux" - "log" "net/http" ) @@ -45,16 +44,15 @@ func (s *HTTPServer) getServices(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "application/json; charset=UTF-8") if err := json.NewEncoder(w).Encode(s.list.GetAllServices()); err != nil { - log.Println("Error encoding: ", err) + logger.Errorf("Encoding error: %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) } } func (s *HTTPServer) getService(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) - - w.Header().Set("Content-Type", "application/json; charset=UTF-8") - + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + id, ok := vars["id"] if !ok { http.Error(w, "ID required", http.StatusBadRequest) @@ -68,7 +66,7 @@ func (s *HTTPServer) getService(w http.ResponseWriter, req *http.Request) { } if err := json.NewEncoder(w).Encode(service); err != nil { - log.Println("Error: ", err) + logger.Errorf("Encoding error: %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) } } @@ -84,7 +82,7 @@ func (s *HTTPServer) addService(w http.ResponseWriter, req *http.Request) { service := NewService() if err := json.NewDecoder(req.Body).Decode(&service); err != nil { - log.Println("Error decoding JSON: ", err) + logger.Errorf("JSON decoding error: %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -139,7 +137,7 @@ func (s *HTTPServer) updateService(w http.ResponseWriter, req *http.Request) { var input map[string]interface{} if err := json.NewDecoder(req.Body).Decode(&input); err != nil { - log.Println("Error decoding JSON: ", err) + logger.Errorf("JSON decoding error: %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } @@ -177,7 +175,7 @@ func (s *HTTPServer) updateService(w http.ResponseWriter, req *http.Request) { func (s *HTTPServer) setTTL(w http.ResponseWriter, req *http.Request) { var value int if err := json.NewDecoder(req.Body).Decode(&value); err != nil { - log.Println("Error decoding value: ", err) + logger.Errorf("Decoding error: %s", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } diff --git a/src/loggers.go b/src/loggers.go new file mode 100644 index 0000000..131557e --- /dev/null +++ b/src/loggers.go @@ -0,0 +1,52 @@ +//This file is part of CFDNSUpdater. +// +// CFDNSUpdater is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// CFDNSUpdater is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with CFDNSUpdater. If not, see . + +package main + +import ( + "os" + "path/filepath" + "github.com/op/go-logging" +) + +var logger = logging.MustGetLogger("dnsdock") + + +func InitLoggers(verbose bool, quiet bool) (err error) { + var format logging.Formatter + + var backend logging.Backend + + var outstream *os.File + if quiet { + outstream = os.NewFile(uintptr(3), filepath.Join("/","dev","null")) + } else { + outstream = os.Stderr + } + backend = logging.NewLogBackend(outstream, "", 0) + format = logging.MustStringFormatter(`%{color}%{time:15:04:05.000} | %{level:.10s} ▶%{color:reset} %{message}`) + + formatter := logging.NewBackendFormatter(backend, format) + leveledBackend := logging.AddModuleLevel(formatter) + + if verbose { + leveledBackend.SetLevel(logging.DEBUG, "") + } else { + leveledBackend.SetLevel(logging.INFO, "") + } + + logging.SetBackend(leveledBackend) + return +} diff --git a/src/main.go b/src/main.go index 73fcdf7..1e66c03 100644 --- a/src/main.go +++ b/src/main.go @@ -6,7 +6,6 @@ import ( "flag" "fmt" "io/ioutil" - "log" "os" ) @@ -27,7 +26,6 @@ func main() { flag.StringVar(&config.tlsCaCert, "tlscacert", config.tlsCaCert, "Path to CA certificate") flag.StringVar(&config.tlsCert, "tlscert", config.tlsCert, "Path to client certificate") flag.StringVar(&config.tlsKey, "tlskey", config.tlsKey, "Path to client certificate private key") - flag.BoolVar(&config.verbose, "verbose", true, "Verbose output") flag.IntVar(&config.ttl, "ttl", config.ttl, "TTL for matched requests") flag.BoolVar(&config.createAlias, "create-alias", config.createAlias, "Automatically create an alias with just the container name.") @@ -38,6 +36,8 @@ func main() { flag.Parse() + InitLoggers(true,false) + if showVersion { fmt.Println("dnsdock", version) return @@ -57,7 +57,7 @@ func main() { if config.tlsVerify { clientCert, err := tls.LoadX509KeyPair(config.tlsCert, config.tlsKey) if err != nil { - log.Fatal(err) + logger.Fatalf("Error: '%s'", err) } tlsConfig = &tls.Config{ MinVersion: tls.VersionTLS12, @@ -69,26 +69,26 @@ func main() { rootCert.AppendCertsFromPEM(pemData) tlsConfig.RootCAs = rootCert } else { - log.Print(err) + logger.Fatalf("Error: '%s'", err) } } docker, err := NewDockerManager(config, dnsServer, tlsConfig) if err != nil { - log.Fatal(err) + logger.Fatalf("Error: '%s'", err) } if err := docker.Start(); err != nil { - log.Fatal(err) + logger.Fatalf("Error: '%s'", err) } httpServer := NewHTTPServer(config, dnsServer) go func() { if err := httpServer.Start(); err != nil { - log.Fatal(err) + logger.Fatalf("Error: '%s'", err) } }() if err := dnsServer.Start(); err != nil { - log.Fatal(err) + logger.Fatalf("Error: '%s'", err) } } From 5b7f5eb992922fb320f97c2a6a756c1a2cf6485a Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sun, 6 Nov 2016 10:04:58 +0100 Subject: [PATCH 05/11] Replace old argument parser with kingpin.v2 --- src/cmdline.go | 53 +++++++++++++++++++++++++++++++++++++++++++++ src/config.go | 4 ++++ src/loggers.go | 30 +++++++++++++------------ src/main.go | 59 ++++++++++++++++---------------------------------- 4 files changed, 92 insertions(+), 54 deletions(-) create mode 100644 src/cmdline.go diff --git a/src/cmdline.go b/src/cmdline.go new file mode 100644 index 0000000..fb92bbc --- /dev/null +++ b/src/cmdline.go @@ -0,0 +1,53 @@ +package main + +import ( + "fmt" + "gopkg.in/alecthomas/kingpin.v2" + "strconv" +) + +const ( + VERSION = "0.9.1" +) + +type CommandLine struct{} + +func (self *CommandLine) ParseParameters(rawParams []string) (res *Config, err error) { + + res = 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 = 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 +} diff --git a/src/config.go b/src/config.go index 4e11536..f994cdb 100644 --- a/src/config.go +++ b/src/config.go @@ -55,6 +55,8 @@ type Config struct { httpAddr string ttl int createAlias bool + verbose bool + quiet bool } // NewConfig creates a new config @@ -80,6 +82,8 @@ func NewConfig() *Config { tlsCaCert: dockerCerts + "/ca.pem", tlsCert: dockerCerts + "/cert.pem", tlsKey: dockerCerts + "/key.pem", + verbose: false, + quiet: false, } } diff --git a/src/loggers.go b/src/loggers.go index 131557e..cf0d60b 100644 --- a/src/loggers.go +++ b/src/loggers.go @@ -17,36 +17,38 @@ package main import ( "os" - "path/filepath" + "io/ioutil" "github.com/op/go-logging" ) var logger = logging.MustGetLogger("dnsdock") -func InitLoggers(verbose bool, quiet bool) (err error) { +func InitLoggers(verbosity int) (err error) { var format logging.Formatter var backend logging.Backend - var outstream *os.File - if quiet { - outstream = os.NewFile(uintptr(3), filepath.Join("/","dev","null")) - } else { - outstream = os.Stderr - } - backend = logging.NewLogBackend(outstream, "", 0) + switch { + case verbosity == 0 : + backend = logging.NewLogBackend(ioutil.Discard, "", 0) + case verbosity >= 1 : + backend = logging.NewLogBackend(os.Stdout, "", 0) + } + format = logging.MustStringFormatter(`%{color}%{time:15:04:05.000} | %{level:.10s} ▶%{color:reset} %{message}`) formatter := logging.NewBackendFormatter(backend, format) leveledBackend := logging.AddModuleLevel(formatter) - - if verbose { - leveledBackend.SetLevel(logging.DEBUG, "") - } else { - leveledBackend.SetLevel(logging.INFO, "") + + switch { + case verbosity == 1 : + leveledBackend.SetLevel(logging.INFO, "") + case verbosity >= 2 : + leveledBackend.SetLevel(logging.DEBUG, "") } logging.SetBackend(leveledBackend) return } + diff --git a/src/main.go b/src/main.go index 1e66c03..bb35540 100644 --- a/src/main.go +++ b/src/main.go @@ -3,8 +3,6 @@ package main import ( "crypto/tls" "crypto/x509" - "flag" - "fmt" "io/ioutil" "os" ) @@ -12,52 +10,32 @@ import ( var version string func main() { - help := flag.Bool("help", false, "Show this message") - config := NewConfig() - - flag.Var(&config.nameserver, "nameserver", "Comma separated list of DNS server(s) for unmatched requests") - flag.StringVar(&config.dnsAddr, "dns", config.dnsAddr, "Listen DNS requests on this address") - flag.StringVar(&config.httpAddr, "http", config.httpAddr, "Listen HTTP requests on this address") - domain := flag.String("domain", config.domain.String(), "Domain that is appended to all requests") - environment := flag.String("environment", "", "Optional context before domain suffix") - flag.StringVar(&config.dockerHost, "docker", config.dockerHost, "Path to the docker socket") - flag.BoolVar(&config.tlsVerify, "tlsverify", false, "Enable mTLS when connecting to docker") - flag.StringVar(&config.tlsCaCert, "tlscacert", config.tlsCaCert, "Path to CA certificate") - flag.StringVar(&config.tlsCert, "tlscert", config.tlsCert, "Path to client certificate") - flag.StringVar(&config.tlsKey, "tlskey", config.tlsKey, "Path to client certificate private key") - flag.IntVar(&config.ttl, "ttl", config.ttl, "TTL for matched requests") - flag.BoolVar(&config.createAlias, "create-alias", config.createAlias, "Automatically create an alias with just the container name.") - - var showVersion bool - if len(version) > 0 { - flag.BoolVar(&showVersion, "version", false, "Show application version") + var cmdLine CommandLine + config, err := cmdLine.ParseParameters(os.Args[1:]) + if err != nil { + logger.Fatalf(err.Error()) } - - flag.Parse() - - InitLoggers(true,false) - - if showVersion { - fmt.Println("dnsdock", version) - return + verbosity := 0 + if config.quiet == false { + if config.verbose == false { + verbosity = 1 + } else { + verbosity = 2 + } } - - if *help { - fmt.Fprintf(os.Stderr, "Usage: %s [options]\n", os.Args[0]) - flag.PrintDefaults() - return + err = InitLoggers(verbosity) + if err != nil { + logger.Fatalf("Unable to initialize loggers! %s", err.Error()) } - - config.domain = NewDomain(*environment + "." + *domain) - + dnsServer := NewDNSServer(config) var tlsConfig *tls.Config if config.tlsVerify { clientCert, err := tls.LoadX509KeyPair(config.tlsCert, config.tlsKey) if err != nil { - logger.Fatalf("Error: '%s'", err) + logger.Fatalf("Error: '%s'", err) } tlsConfig = &tls.Config{ MinVersion: tls.VersionTLS12, @@ -69,9 +47,10 @@ func main() { rootCert.AppendCertsFromPEM(pemData) tlsConfig.RootCAs = rootCert } else { - logger.Fatalf("Error: '%s'", err) + logger.Fatalf("Error: '%s'", err) } } + docker, err := NewDockerManager(config, dnsServer, tlsConfig) if err != nil { logger.Fatalf("Error: '%s'", err) @@ -79,7 +58,7 @@ func main() { if err := docker.Start(); err != nil { logger.Fatalf("Error: '%s'", err) } - + httpServer := NewHTTPServer(config, dnsServer) go func() { if err := httpServer.Start(); err != nil { From a625b50884bc1a14ba87ad99181ebf06d805aa2d Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sun, 6 Nov 2016 10:05:07 +0100 Subject: [PATCH 06/11] Updated dependencies --- Godeps/Godeps.json | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index 88e82b6..fcab44a 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -16,14 +16,26 @@ "Comment": "v0.10.0-19-gf3cfb45", "Rev": "f3cfb454f4c209e6668c95216c4744b8fddb2356" }, + { + "ImportPath": "github.com/alecthomas/template", + "Rev": "a0175ee3bccc567396460bf5acd36800cb10c49c" + }, + { + "ImportPath": "github.com/alecthomas/template/parse", + "Rev": "a0175ee3bccc567396460bf5acd36800cb10c49c" + }, + { + "ImportPath": "github.com/alecthomas/units", + "Rev": "2efee857e7cfd4f3d0138cc3cbb1b4966962b93a" + }, { "ImportPath": "github.com/docker/distribution/digest", - "Comment": "v2.5.0-rc.1-22-g4e17ab5", + "Comment": "docs-v2.4.1-2016-06-28-6-g4e17ab5", "Rev": "4e17ab5d319ac5b70b2769442947567a83386fbc" }, { "ImportPath": "github.com/docker/distribution/reference", - "Comment": "v2.5.0-rc.1-22-g4e17ab5", + "Comment": "docs-v2.4.1-2016-06-28-6-g4e17ab5", "Rev": "4e17ab5d319ac5b70b2769442947567a83386fbc" }, { @@ -103,22 +115,22 @@ }, { "ImportPath": "github.com/docker/go-connections/nat", - "Comment": "v0.2.0-8-g990a1a1", + "Comment": "v0.2.1", "Rev": "990a1a1a70b0da4c4cb70e117971a4f0babfbf1a" }, { "ImportPath": "github.com/docker/go-connections/sockets", - "Comment": "v0.2.0-8-g990a1a1", + "Comment": "v0.2.1", "Rev": "990a1a1a70b0da4c4cb70e117971a4f0babfbf1a" }, { "ImportPath": "github.com/docker/go-connections/tlsconfig", - "Comment": "v0.2.0-8-g990a1a1", + "Comment": "v0.2.1", "Rev": "990a1a1a70b0da4c4cb70e117971a4f0babfbf1a" }, { "ImportPath": "github.com/docker/go-units", - "Comment": "v0.1.0-23-g5d2041e", + "Comment": "v0.3.0", "Rev": "5d2041e26a699eaca682e2ea41c8f891e1060444" }, { @@ -164,6 +176,11 @@ { "ImportPath": "golang.org/x/sys/windows", "Rev": "62bee037599929a6e9146f29d10dd5208c43507d" + }, + { + "ImportPath": "gopkg.in/alecthomas/kingpin.v2", + "Comment": "v2.2.3", + "Rev": "e9044be3ab2a8e11d4e1f418d12f0790d57e8d70" } ] } From 1348326f8040879adee2a55b0ac1f486df5e466e Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sun, 6 Nov 2016 10:19:25 +0100 Subject: [PATCH 07/11] Corrected tests --- src/dnsserver_test.go | 30 +++++++++++++++--------------- src/http_test.go | 12 ++++++------ 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/dnsserver_test.go b/src/dnsserver_test.go index 0151753..9fc186b 100644 --- a/src/dnsserver_test.go +++ b/src/dnsserver_test.go @@ -21,10 +21,10 @@ func TestDNSResponse(t *testing.T) { // Allow some time for server to start time.Sleep(250 * time.Millisecond) - server.AddService("foo", Service{Name: "foo", Image: "bar", IP: net.ParseIP("127.0.0.1")}) - server.AddService("baz", Service{Name: "baz", Image: "bar", IP: net.ParseIP("127.0.0.1"), TTL: -1}) - server.AddService("biz", Service{Name: "hey", Image: "", IP: net.ParseIP("127.0.0.4")}) - server.AddService("joe", Service{Name: "joe", Image: "", IP: net.ParseIP("127.0.0.5"), Aliases: []string{"lala.docker", "super-alias", "alias.domain"}}) + server.AddService("foo", Service{Name: "foo", Image: "bar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) + server.AddService("baz", Service{Name: "baz", Image: "bar", IPs: []net.IP {net.ParseIP("127.0.0.1")}, TTL: -1}) + server.AddService("biz", Service{Name: "hey", Image: "", IPs: []net.IP {net.ParseIP("127.0.0.4")}}) + server.AddService("joe", Service{Name: "joe", Image: "", IPs: []net.IP {net.ParseIP("127.0.0.5")}, Aliases: []string{"lala.docker", "super-alias", "alias.domain"}}) var inputs = []struct { query string @@ -106,7 +106,7 @@ func TestServiceManagement(t *testing.T) { t.Error("Initial service count should be 0.") } - A := Service{Name: "bar"} + A := Service{Name: "bar", IPs: []net.IP {net.ParseIP("127.0.0.1")}} list.AddService("foo", A) if len(list.GetAllServices()) != 1 { @@ -130,7 +130,7 @@ func TestServiceManagement(t *testing.T) { t.Error("Request to boo should have failed") } - list.AddService("boo", Service{Name: "boo"}) + list.AddService("boo", Service{Name: "boo", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) all := list.GetAllServices() @@ -160,7 +160,7 @@ func TestServiceManagement(t *testing.T) { t.Error("Item count after remove should be 1") } - list.AddService("416261e74515b7dd1dbd55f35e8625b063044f6ddf74907269e07e9f142bc0df", Service{Name: "mysql"}) + list.AddService("416261e74515b7dd1dbd55f35e8625b063044f6ddf74907269e07e9f142bc0df", Service{Name: "mysql", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) if s1, _ = list.GetService("416261"); s1.Name != "mysql" { t.Error("Container can't be found by prefix") @@ -180,10 +180,10 @@ func TestServiceManagement(t *testing.T) { func TestDNSRequestMatch(t *testing.T) { server := NewDNSServer(NewConfig()) - server.AddService("foo", Service{Name: "foo", Image: "bar"}) - server.AddService("baz", Service{Name: "baz", Image: "bar"}) - server.AddService("abc", Service{Name: "def", Image: "ghi"}) - server.AddService("qux", Service{Name: "qux", Image: ""}) + server.AddService("foo", Service{Name: "foo", Image: "bar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) + server.AddService("baz", Service{Name: "baz", Image: "bar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) + server.AddService("abc", Service{Name: "def", Image: "ghi", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) + server.AddService("qux", Service{Name: "qux", Image: "", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) inputs := []struct { query, domain string @@ -227,10 +227,10 @@ func TestDNSRequestMatch(t *testing.T) { func TestDNSRequestMatchNamesWithDots(t *testing.T) { server := NewDNSServer(NewConfig()) - server.AddService("boo", Service{Name: "foo.boo", Image: "bar.zar"}) - server.AddService("baz", Service{Name: "baz", Image: "bar.zar"}) - server.AddService("abc", Service{Name: "bar", Image: "zar"}) - server.AddService("qux", Service{Name: "qux.quu", Image: ""}) + server.AddService("boo", Service{Name: "foo.boo", Image: "bar.zar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) + server.AddService("baz", Service{Name: "baz", Image: "bar.zar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) + server.AddService("abc", Service{Name: "bar", Image: "zar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) + server.AddService("qux", Service{Name: "qux.quu", Image: "", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) inputs := []struct { query, domain string diff --git a/src/http_test.go b/src/http_test.go index a2243c1..d0d5feb 100644 --- a/src/http_test.go +++ b/src/http_test.go @@ -27,14 +27,14 @@ func TestServiceRequests(t *testing.T) { {"GET", "/services", "", "{}", 200}, {"GET", "/services/foo", "", "", 404}, {"PUT", "/services/foo", `{"name": "foo"}`, "", 500}, - {"PUT", "/services/foo", `{"name": "foo", "image": "bar", "ip": "127.0.0.1", "aliases": ["foo.docker"]}`, "", 200}, - {"GET", "/services/foo", "", `{"Name":"foo","Image":"bar","IP":"127.0.0.1","TTL":-1,"Aliases":["foo.docker"]}`, 200}, - {"PUT", "/services/boo", `{"name": "baz", "image": "bar", "ip": "127.0.0.2"}`, "", 200}, - {"GET", "/services", "", `{"boo":{"Name":"baz","Image":"bar","IP":"127.0.0.2","TTL":-1,"Aliases":null},"foo":{"Name":"foo","Image":"bar","IP":"127.0.0.1","TTL":-1,"Aliases":["foo.docker"]}}`, 200}, + {"PUT", "/services/foo", `{"name": "foo", "image": "bar", "ips": ["127.0.0.1"], "aliases": ["foo.docker"]}`, "", 200}, + {"GET", "/services/foo", "", `{"Name":"foo","Image":"bar","IPs":["127.0.0.1"],"TTL":-1,"Aliases":["foo.docker"]}`, 200}, + {"PUT", "/services/boo", `{"name": "baz", "image": "bar", "ips": ["127.0.0.2"]}`, "", 200}, + {"GET", "/services", "", `{"boo":{"Name":"baz","Image":"bar","IPs":["127.0.0.2"],"TTL":-1,"Aliases":null},"foo":{"Name":"foo","Image":"bar","IPs":["127.0.0.1"],"TTL":-1,"Aliases":["foo.docker"]}}`, 200}, {"PATCH", "/services/boo", `{"name": "bar", "ttl": 20, "image": "bar"}`, "", 200}, - {"GET", "/services/boo", "", `{"Name":"bar","Image":"bar","IP":"127.0.0.2","TTL":20,"Aliases":null}`, 200}, + {"GET", "/services/boo", "", `{"Name":"bar","Image":"bar","IPs":["127.0.0.2"],"TTL":20,"Aliases":null}`, 200}, {"DELETE", "/services/foo", ``, "", 200}, - {"GET", "/services", "", `{"boo":{"Name":"bar","Image":"bar","IP":"127.0.0.2","TTL":20,"Aliases":null}}`, 200}, + {"GET", "/services", "", `{"boo":{"Name":"bar","Image":"bar","IPs":["127.0.0.2"],"TTL":20,"Aliases":null}}`, 200}, } for _, input := range tests { From 52c6ebb02fcaae1ba7a16ea728ea8ff94ce634b6 Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sun, 6 Nov 2016 10:24:22 +0100 Subject: [PATCH 08/11] Passed go vet and golint --- src/cmdline.go | 8 +++++--- src/dnsserver.go | 2 +- src/loggers.go | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/cmdline.go b/src/cmdline.go index fb92bbc..9fa0d3f 100644 --- a/src/cmdline.go +++ b/src/cmdline.go @@ -7,13 +7,15 @@ import ( ) const ( - VERSION = "0.9.1" + // VERSION dnsdock version + VERSION = "0.9.1" ) +// CommandLine structure handling parameter parsing type CommandLine struct{} -func (self *CommandLine) ParseParameters(rawParams []string) (res *Config, err error) { - +// ParseParameters Parse parameters +func (cmdline *CommandLine) ParseParameters(rawParams []string) (res *Config, err error) { res = NewConfig() app := kingpin.New("dnsdock", "Automatic DNS for docker containers.") diff --git a/src/dnsserver.go b/src/dnsserver.go index 5cf0755..d1ccb07 100644 --- a/src/dnsserver.go +++ b/src/dnsserver.go @@ -221,7 +221,7 @@ func (s *DNSServer) makeServiceA(n string, service *Service) dns.RR { } rr.A = service.IPs[0] } else { - logger.Errorf("No valid IP address found for container ", service.Name) + logger.Errorf("No valid IP address found for container '%s' ", service.Name) } return rr diff --git a/src/loggers.go b/src/loggers.go index cf0d60b..ffce7e9 100644 --- a/src/loggers.go +++ b/src/loggers.go @@ -23,7 +23,7 @@ import ( var logger = logging.MustGetLogger("dnsdock") - +// InitLoggers initialize loggers func InitLoggers(verbosity int) (err error) { var format logging.Formatter From b68e16347c21c1fa225a92465ec6025751556f1d Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sun, 6 Nov 2016 13:49:21 +0100 Subject: [PATCH 09/11] Massive code refactoring Rearchitectured project's structure --- src/{ => core}/cmdline.go | 58 +++++++++++++++-------------- src/{ => core}/docker.go | 23 ++++++------ src/{ => core}/docker_test.go | 7 ++-- src/core/loggers.go | 7 ++++ src/main.go | 26 +++++++------ src/{ => servers}/dnsserver.go | 46 +++++++++++------------ src/{ => servers}/dnsserver_test.go | 20 +++++----- src/{ => servers}/http.go | 11 +++--- src/{ => servers}/http_test.go | 13 ++++--- src/servers/loggers.go | 7 ++++ src/{ => utils}/config.go | 52 +++++++++++++------------- src/{ => utils}/config_test.go | 2 +- src/{ => utils}/loggers.go | 20 +--------- 13 files changed, 150 insertions(+), 142 deletions(-) rename src/{ => core}/cmdline.go (61%) rename src/{ => core}/docker.go (90%) rename src/{ => core}/docker_test.go (94%) create mode 100644 src/core/loggers.go rename src/{ => servers}/dnsserver.go (90%) rename src/{ => servers}/dnsserver_test.go (95%) rename src/{ => servers}/http.go (94%) rename src/{ => servers}/http_test.go (91%) create mode 100644 src/servers/loggers.go rename src/{ => utils}/config.go (66%) rename src/{ => utils}/config_test.go (96%) rename src/{ => utils}/loggers.go (51%) diff --git a/src/cmdline.go b/src/core/cmdline.go similarity index 61% rename from src/cmdline.go rename to src/core/cmdline.go index 9fa0d3f..8b6366f 100644 --- a/src/cmdline.go +++ b/src/core/cmdline.go @@ -1,11 +1,13 @@ -package main +package core import ( "fmt" "gopkg.in/alecthomas/kingpin.v2" + "github.com/aacebedo/dnsdock/src/utils" "strconv" ) + const ( // VERSION dnsdock version VERSION = "0.9.1" @@ -15,41 +17,41 @@ const ( type CommandLine struct{} // ParseParameters Parse parameters -func (cmdline *CommandLine) ParseParameters(rawParams []string) (res *Config, err error) { - res = NewConfig() +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() + 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() + 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 = 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 + 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 } diff --git a/src/docker.go b/src/core/docker.go similarity index 90% rename from src/docker.go rename to src/core/docker.go index f7b0deb..da98ac0 100644 --- a/src/docker.go +++ b/src/core/docker.go @@ -1,4 +1,4 @@ -package main +package core import ( "crypto/tls" @@ -7,26 +7,27 @@ import ( "github.com/docker/engine-api/types" eventtypes "github.com/docker/engine-api/types/events" "github.com/vdemeester/docker-events" + "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 @@ -100,13 +101,13 @@ 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) @@ -134,7 +135,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 @@ -180,7 +181,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" { @@ -243,7 +244,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" { diff --git a/src/docker_test.go b/src/core/docker_test.go similarity index 94% rename from src/docker_test.go rename to src/core/docker_test.go index ea69793..1a37e29 100644 --- a/src/docker_test.go +++ b/src/core/docker_test.go @@ -1,8 +1,9 @@ -package main +package core import ( "reflect" "testing" + "github.com/aacebedo/dnsdock/src/servers" ) func TestGetImageName(t *testing.T) { @@ -68,8 +69,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 diff --git a/src/core/loggers.go b/src/core/loggers.go new file mode 100644 index 0000000..efe485d --- /dev/null +++ b/src/core/loggers.go @@ -0,0 +1,7 @@ +package core + +import ( + "github.com/op/go-logging" +) + +var logger = logging.MustGetLogger("dnsdock.core") diff --git a/src/main.go b/src/main.go index bb35540..28cd3a8 100644 --- a/src/main.go +++ b/src/main.go @@ -5,35 +5,39 @@ import ( "crypto/x509" "io/ioutil" "os" + "github.com/aacebedo/dnsdock/src/core" + "github.com/aacebedo/dnsdock/src/utils" + "github.com/aacebedo/dnsdock/src/servers" + "github.com/op/go-logging" ) -var version string +var logger = logging.MustGetLogger("dnsdock.main") func main() { - var cmdLine CommandLine + var cmdLine core.CommandLine config, err := cmdLine.ParseParameters(os.Args[1:]) if err != nil { logger.Fatalf(err.Error()) } verbosity := 0 - if config.quiet == false { - if config.verbose == false { + if config.Quiet == false { + if config.Verbose == false { verbosity = 1 } else { verbosity = 2 } } - err = InitLoggers(verbosity) + err = utils.InitLoggers(verbosity) if err != nil { logger.Fatalf("Unable to initialize loggers! %s", err.Error()) } - dnsServer := NewDNSServer(config) + dnsServer := servers.NewDNSServer(config) var tlsConfig *tls.Config - if config.tlsVerify { - clientCert, err := tls.LoadX509KeyPair(config.tlsCert, config.tlsKey) + if config.TlsVerify { + clientCert, err := tls.LoadX509KeyPair(config.TlsCert, config.TlsKey) if err != nil { logger.Fatalf("Error: '%s'", err) } @@ -41,7 +45,7 @@ func main() { MinVersion: tls.VersionTLS12, Certificates: []tls.Certificate{clientCert}, } - pemData, err := ioutil.ReadFile(config.tlsCaCert) + pemData, err := ioutil.ReadFile(config.TlsCaCert) if err == nil { rootCert := x509.NewCertPool() rootCert.AppendCertsFromPEM(pemData) @@ -51,7 +55,7 @@ func main() { } } - docker, err := NewDockerManager(config, dnsServer, tlsConfig) + docker, err := core.NewDockerManager(config, dnsServer, tlsConfig) if err != nil { logger.Fatalf("Error: '%s'", err) } @@ -59,7 +63,7 @@ func main() { logger.Fatalf("Error: '%s'", err) } - httpServer := NewHTTPServer(config, dnsServer) + httpServer := servers.NewHTTPServer(config, dnsServer) go func() { if err := httpServer.Start(); err != nil { logger.Fatalf("Error: '%s'", err) diff --git a/src/dnsserver.go b/src/servers/dnsserver.go similarity index 90% rename from src/dnsserver.go rename to src/servers/dnsserver.go index d1ccb07..619e02e 100644 --- a/src/dnsserver.go +++ b/src/servers/dnsserver.go @@ -1,4 +1,4 @@ -package main +package servers import ( "errors" @@ -7,7 +7,7 @@ import ( "strings" "sync" "time" - + "github.com/aacebedo/dnsdock/src/utils" "github.com/miekg/dns" ) @@ -36,7 +36,7 @@ type ServiceListProvider interface { // DNSServer represents a DNS server type DNSServer struct { - config *Config + config *utils.Config server *dns.Server mux *dns.ServeMux services map[string]*Service @@ -44,21 +44,21 @@ type DNSServer struct { } // NewDNSServer create a new DNSServer -func NewDNSServer(c *Config) *DNSServer { +func NewDNSServer(c *utils.Config) *DNSServer { s := &DNSServer{ config: c, services: make(map[string]*Service), lock: &sync.RWMutex{}, } - logger.Debugf("Handling DNS requests for '%s'.", c.domain.String()) + logger.Debugf("Handling DNS requests for '%s'.", c.Domain.String()) s.mux = dns.NewServeMux() - s.mux.HandleFunc(c.domain.String()+".", s.handleRequest) + s.mux.HandleFunc(c.Domain.String()+".", s.handleRequest) s.mux.HandleFunc("in-addr.arpa.", s.handleReverseRequest) s.mux.HandleFunc(".", s.handleForward) - s.server = &dns.Server{Addr: c.dnsAddr, Net: "udp", Handler: s.mux} + s.server = &dns.Server{Addr: c.DnsAddr, Net: "udp", Handler: s.mux} return s } @@ -146,9 +146,9 @@ func (s *DNSServer) listDomains(service *Service) chan string { go func() { if service.Image == "" { - c <- service.Name + "." + s.config.domain.String() + "." + c <- service.Name + "." + s.config.Domain.String() + "." } else { - domain := service.Image + "." + s.config.domain.String() + "." + domain := service.Image + "." + s.config.Domain.String() + "." c <- service.Name + "." + domain c <- domain @@ -167,22 +167,22 @@ func (s *DNSServer) listDomains(service *Service) chan string { func (s *DNSServer) handleForward(w dns.ResponseWriter, r *dns.Msg) { logger.Debugf("Using DNS forwarding for '%s'",r.Question[0].Name) - logger.Debugf("Forwarding DNS nameservers: %s",s.config.nameserver.String()) + logger.Debugf("Forwarding DNS nameservers: %s",s.config.Nameserver.String()) // Otherwise just forward the request to another server c := new(dns.Client) - // look at each nameserver, stop on success - for i := range s.config.nameserver { - logger.Debugf("Using nameserver %s", s.config.nameserver[i]) + // look at each Nameserver, stop on success + for i := range s.config.Nameserver { + logger.Debugf("Using Nameserver %s", s.config.Nameserver[i]) - in, _, err := c.Exchange(r, s.config.nameserver[i]) + in, _, err := c.Exchange(r, s.config.Nameserver[i]) if err == nil { w.WriteMsg(in) return } - if i == (len(s.config.nameserver) - 1) { + if i == (len(s.config.Nameserver) - 1) { logger.Fatalf("DNS fowarding for '%s' failed: no more nameservers to try", err.Error()) // Send failure reply @@ -193,7 +193,7 @@ func (s *DNSServer) handleForward(w dns.ResponseWriter, r *dns.Msg) { w.WriteMsg(m) } else { - logger.Errorf("DNS fowarding for '%s' failed: trying next nameserver...", err.Error()) + logger.Errorf("DNS fowarding for '%s' failed: trying next Nameserver...", err.Error()) } } } @@ -205,7 +205,7 @@ func (s *DNSServer) makeServiceA(n string, service *Service) dns.RR { if service.TTL != -1 { ttl = service.TTL } else { - ttl = s.config.ttl + ttl = s.config.Ttl } rr.Hdr = dns.RR_Header{ @@ -234,7 +234,7 @@ func (s *DNSServer) makeServiceMX(n string, service *Service) dns.RR { if service.TTL != -1 { ttl = service.TTL } else { - ttl = s.config.ttl + ttl = s.config.Ttl } rr.Hdr = dns.RR_Header{ @@ -341,7 +341,7 @@ func (s *DNSServer) handleReverseRequest(w dns.ResponseWriter, r *dns.Msg) { if service.TTL != -1 { ttl = service.TTL } else { - ttl = s.config.ttl + ttl = s.config.Ttl } for domain := range s.listDomains(service) { @@ -409,7 +409,7 @@ func (s *DNSServer) queryServices(query string) chan *Service { test = append(test, strings.Split(service.Image, ".")...) } - test = append(test, s.config.domain...) + test = append(test, s.config.Domain...) if isPrefixQuery(query, test) { c <- service @@ -461,20 +461,20 @@ func (s *DNSServer) getExpandedID(in string) (out string) { // for a long time. The other defaults left as is(skydns source) because they // do not have an use case in this situation. func (s *DNSServer) createSOA() []dns.RR { - dom := dns.Fqdn(s.config.domain.String() + ".") + dom := dns.Fqdn(s.config.Domain.String() + ".") soa := &dns.SOA{ Hdr: dns.RR_Header{ Name: dom, Rrtype: dns.TypeSOA, Class: dns.ClassINET, - Ttl: uint32(s.config.ttl)}, + Ttl: uint32(s.config.Ttl)}, Ns: "dnsdock." + dom, Mbox: "dnsdock.dnsdock." + dom, Serial: uint32(time.Now().Truncate(time.Hour).Unix()), Refresh: 28800, Retry: 7200, Expire: 604800, - Minttl: uint32(s.config.ttl), + Minttl: uint32(s.config.Ttl), } return []dns.RR{soa} } diff --git a/src/dnsserver_test.go b/src/servers/dnsserver_test.go similarity index 95% rename from src/dnsserver_test.go rename to src/servers/dnsserver_test.go index 9fc186b..afa8be5 100644 --- a/src/dnsserver_test.go +++ b/src/servers/dnsserver_test.go @@ -1,19 +1,19 @@ -package main +package servers import ( "net" "strings" "testing" "time" - + "github.com/aacebedo/dnsdock/src/utils" "github.com/miekg/dns" ) func TestDNSResponse(t *testing.T) { const TestAddr = "127.0.0.1:9953" - config := NewConfig() - config.dnsAddr = TestAddr + config := utils.NewConfig() + config.DnsAddr = TestAddr server := NewDNSServer(config) go server.Start() @@ -100,7 +100,7 @@ func TestDNSResponse(t *testing.T) { } func TestServiceManagement(t *testing.T) { - list := ServiceListProvider(NewDNSServer(NewConfig())) + list := ServiceListProvider(NewDNSServer(utils.NewConfig())) if len(list.GetAllServices()) != 0 { t.Error("Initial service count should be 0.") @@ -178,7 +178,7 @@ func TestServiceManagement(t *testing.T) { } func TestDNSRequestMatch(t *testing.T) { - server := NewDNSServer(NewConfig()) + server := NewDNSServer(utils.NewConfig()) server.AddService("foo", Service{Name: "foo", Image: "bar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) server.AddService("baz", Service{Name: "baz", Image: "bar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) @@ -209,7 +209,7 @@ func TestDNSRequestMatch(t *testing.T) { } for _, input := range inputs { - server.config.domain = NewDomain(input.domain) + server.config.Domain = utils.NewDomain(input.domain) t.Log(input.query, input.domain) @@ -225,7 +225,7 @@ func TestDNSRequestMatch(t *testing.T) { } func TestDNSRequestMatchNamesWithDots(t *testing.T) { - server := NewDNSServer(NewConfig()) + server := NewDNSServer(utils.NewConfig()) server.AddService("boo", Service{Name: "foo.boo", Image: "bar.zar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) server.AddService("baz", Service{Name: "baz", Image: "bar.zar", IPs: []net.IP {net.ParseIP("127.0.0.1")}}) @@ -253,7 +253,7 @@ func TestDNSRequestMatchNamesWithDots(t *testing.T) { } for _, input := range inputs { - server.config.domain = NewDomain(input.domain) + server.config.Domain = utils.NewDomain(input.domain) t.Log(input.query, input.domain) actual := 0 @@ -268,7 +268,7 @@ func TestDNSRequestMatchNamesWithDots(t *testing.T) { } func TestgetExpandedID(t *testing.T) { - server := NewDNSServer(NewConfig()) + server := NewDNSServer(utils.NewConfig()) server.AddService("416261e74515b7dd1dbd55f35e8625b063044f6ddf74907269e07e9f142bc0df", Service{}) server.AddService("316261e74515b7dd1dbd55f35e8625b063044f6ddf74907269e07e9f14nothex", Service{}) diff --git a/src/http.go b/src/servers/http.go similarity index 94% rename from src/http.go rename to src/servers/http.go index f0ca4da..ffd1584 100644 --- a/src/http.go +++ b/src/servers/http.go @@ -1,20 +1,21 @@ -package main +package servers import ( "encoding/json" "github.com/gorilla/mux" "net/http" + "github.com/aacebedo/dnsdock/src/utils" ) // HTTPServer represents the http endpoint type HTTPServer struct { - config *Config + config *utils.Config list ServiceListProvider server *http.Server } // NewHTTPServer create a new http endpoint -func NewHTTPServer(c *Config, list ServiceListProvider) *HTTPServer { +func NewHTTPServer(c *utils.Config, list ServiceListProvider) *HTTPServer { s := &HTTPServer{ config: c, list: list, @@ -29,7 +30,7 @@ func NewHTTPServer(c *Config, list ServiceListProvider) *HTTPServer { router.HandleFunc("/set/ttl", s.setTTL).Methods("PUT") - s.server = &http.Server{Addr: c.httpAddr, Handler: router} + s.server = &http.Server{Addr: c.HttpAddr, Handler: router} return s } @@ -180,6 +181,6 @@ func (s *HTTPServer) setTTL(w http.ResponseWriter, req *http.Request) { return } - s.config.ttl = value + s.config.Ttl = value } diff --git a/src/http_test.go b/src/servers/http_test.go similarity index 91% rename from src/http_test.go rename to src/servers/http_test.go index d0d5feb..a5009ce 100644 --- a/src/http_test.go +++ b/src/servers/http_test.go @@ -1,4 +1,4 @@ -package main +package servers import ( "io/ioutil" @@ -6,13 +6,14 @@ import ( "strings" "testing" "time" + "github.com/aacebedo/dnsdock/src/utils" ) func TestServiceRequests(t *testing.T) { const TestAddr = "127.0.0.1:9980" - config := NewConfig() - config.httpAddr = TestAddr + config := utils.NewConfig() + config.HttpAddr = TestAddr server := NewHTTPServer(config, NewDNSServer(config)) go server.Start() @@ -68,7 +69,7 @@ func TestServiceRequests(t *testing.T) { } t.Log("Test TTL setter") - if config.ttl != 0 { + if config.Ttl != 0 { t.Error("Default TTL is not 0") } req, err := http.NewRequest("PUT", "http://"+TestAddr+"/set/ttl", strings.NewReader("12")) @@ -79,7 +80,7 @@ func TestServiceRequests(t *testing.T) { if err != nil { t.Error(err) } - if config.ttl != 12 { - t.Error("TTL not updated. Expected: 12 Got:", config.ttl) + if config.Ttl != 12 { + t.Error("TTL not updated. Expected: 12 Got:", config.Ttl) } } diff --git a/src/servers/loggers.go b/src/servers/loggers.go new file mode 100644 index 0000000..4ec4fba --- /dev/null +++ b/src/servers/loggers.go @@ -0,0 +1,7 @@ +package servers + +import ( + "github.com/op/go-logging" +) + +var logger = logging.MustGetLogger("dnsdock.servers") diff --git a/src/config.go b/src/utils/config.go similarity index 66% rename from src/config.go rename to src/utils/config.go index f994cdb..4b52ae8 100644 --- a/src/config.go +++ b/src/utils/config.go @@ -1,4 +1,4 @@ -package main +package utils import ( "os" @@ -44,19 +44,19 @@ func (n *nameservers) Set(value string) error { // Config contains DNSDock configuration type Config struct { - nameserver nameservers - dnsAddr string - domain Domain - dockerHost string - tlsVerify bool - tlsCaCert string - tlsCert string - tlsKey string - httpAddr string - ttl int - createAlias bool - verbose bool - quiet bool + Nameserver nameservers + DnsAddr string + Domain Domain + DockerHost string + TlsVerify bool + TlsCaCert string + TlsCert string + TlsKey string + HttpAddr string + Ttl int + CreateAlias bool + Verbose bool + Quiet bool } // NewConfig creates a new config @@ -72,18 +72,18 @@ func NewConfig() *Config { } return &Config{ - nameserver: nameservers{"8.8.8.8:53"}, - dnsAddr: ":53", - domain: NewDomain("docker"), - dockerHost: dockerHost, - httpAddr: ":80", - createAlias: false, - tlsVerify: tlsVerify, - tlsCaCert: dockerCerts + "/ca.pem", - tlsCert: dockerCerts + "/cert.pem", - tlsKey: dockerCerts + "/key.pem", - verbose: false, - quiet: false, + Nameserver: nameservers{"8.8.8.8:53"}, + DnsAddr: ":53", + Domain: NewDomain("docker"), + DockerHost: dockerHost, + HttpAddr: ":80", + CreateAlias: false, + TlsVerify: tlsVerify, + TlsCaCert: dockerCerts + "/ca.pem", + TlsCert: dockerCerts + "/cert.pem", + TlsKey: dockerCerts + "/key.pem", + Verbose: false, + Quiet: false, } } diff --git a/src/config_test.go b/src/utils/config_test.go similarity index 96% rename from src/config_test.go rename to src/utils/config_test.go index b6224bd..cd503e9 100644 --- a/src/config_test.go +++ b/src/utils/config_test.go @@ -1,4 +1,4 @@ -package main +package utils import ( "testing" diff --git a/src/loggers.go b/src/utils/loggers.go similarity index 51% rename from src/loggers.go rename to src/utils/loggers.go index ffce7e9..b4df700 100644 --- a/src/loggers.go +++ b/src/utils/loggers.go @@ -1,19 +1,5 @@ -//This file is part of CFDNSUpdater. -// -// CFDNSUpdater is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// CFDNSUpdater is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with CFDNSUpdater. If not, see . - -package main + +package utils import ( "os" @@ -21,8 +7,6 @@ import ( "github.com/op/go-logging" ) -var logger = logging.MustGetLogger("dnsdock") - // InitLoggers initialize loggers func InitLoggers(verbosity int) (err error) { var format logging.Formatter From faf3fb4fe6db43c1d306e0a336f2ab736e6ab76f Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sun, 6 Nov 2016 13:53:47 +0100 Subject: [PATCH 10/11] Applied MIT license to all files --- src/core/cmdline.go | 8 ++++++++ src/core/docker.go | 8 ++++++++ src/core/docker_test.go | 8 ++++++++ src/core/loggers.go | 8 ++++++++ src/main.go | 8 ++++++++ src/servers/dnsserver.go | 8 ++++++++ src/servers/dnsserver_test.go | 8 ++++++++ src/servers/http.go | 8 ++++++++ src/servers/http_test.go | 8 ++++++++ src/servers/loggers.go | 8 ++++++++ src/utils/config.go | 8 ++++++++ src/utils/config_test.go | 8 ++++++++ src/utils/loggers.go | 9 ++++++++- 13 files changed, 104 insertions(+), 1 deletion(-) diff --git a/src/core/cmdline.go b/src/core/cmdline.go index 8b6366f..b39da9d 100644 --- a/src/core/cmdline.go +++ b/src/core/cmdline.go @@ -1,3 +1,11 @@ +/* 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 ( diff --git a/src/core/docker.go b/src/core/docker.go index da98ac0..11cf624 100644 --- a/src/core/docker.go +++ b/src/core/docker.go @@ -1,3 +1,11 @@ +/* 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 ( diff --git a/src/core/docker_test.go b/src/core/docker_test.go index 1a37e29..f6b1d2a 100644 --- a/src/core/docker_test.go +++ b/src/core/docker_test.go @@ -1,3 +1,11 @@ +/* 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 ( diff --git a/src/core/loggers.go b/src/core/loggers.go index efe485d..257aa02 100644 --- a/src/core/loggers.go +++ b/src/core/loggers.go @@ -1,3 +1,11 @@ +/* loggers.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 ( diff --git a/src/main.go b/src/main.go index 28cd3a8..4ba9b12 100644 --- a/src/main.go +++ b/src/main.go @@ -1,3 +1,11 @@ +/* dnsdock.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 main import ( diff --git a/src/servers/dnsserver.go b/src/servers/dnsserver.go index 619e02e..24252e5 100644 --- a/src/servers/dnsserver.go +++ b/src/servers/dnsserver.go @@ -1,3 +1,11 @@ +/* dnsserver.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 servers import ( diff --git a/src/servers/dnsserver_test.go b/src/servers/dnsserver_test.go index afa8be5..e906413 100644 --- a/src/servers/dnsserver_test.go +++ b/src/servers/dnsserver_test.go @@ -1,3 +1,11 @@ +/* dnsserver_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 servers import ( diff --git a/src/servers/http.go b/src/servers/http.go index ffd1584..c312f2f 100644 --- a/src/servers/http.go +++ b/src/servers/http.go @@ -1,3 +1,11 @@ +/* http.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 servers import ( diff --git a/src/servers/http_test.go b/src/servers/http_test.go index a5009ce..34422ab 100644 --- a/src/servers/http_test.go +++ b/src/servers/http_test.go @@ -1,3 +1,11 @@ +/* http_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 servers import ( diff --git a/src/servers/loggers.go b/src/servers/loggers.go index 4ec4fba..15a9116 100644 --- a/src/servers/loggers.go +++ b/src/servers/loggers.go @@ -1,3 +1,11 @@ +/* loggers.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 servers import ( diff --git a/src/utils/config.go b/src/utils/config.go index 4b52ae8..c381a78 100644 --- a/src/utils/config.go +++ b/src/utils/config.go @@ -1,3 +1,11 @@ +/* config.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 utils import ( diff --git a/src/utils/config_test.go b/src/utils/config_test.go index cd503e9..e60fc4b 100644 --- a/src/utils/config_test.go +++ b/src/utils/config_test.go @@ -1,3 +1,11 @@ +/* config_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 utils import ( diff --git a/src/utils/loggers.go b/src/utils/loggers.go index b4df700..2437680 100644 --- a/src/utils/loggers.go +++ b/src/utils/loggers.go @@ -1,4 +1,11 @@ - +/* loggers.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 utils import ( From c937be1bc1c5853f8a20822b506ce770fefbf29c Mon Sep 17 00:00:00 2001 From: Alexandre ACEBEDO Date: Sun, 6 Nov 2016 14:07:18 +0100 Subject: [PATCH 11/11] Changed version --- src/core/cmdline.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/core/cmdline.go b/src/core/cmdline.go index b39da9d..28bf585 100644 --- a/src/core/cmdline.go +++ b/src/core/cmdline.go @@ -18,7 +18,7 @@ import ( const ( // VERSION dnsdock version - VERSION = "0.9.1" + VERSION = "1.16.0" ) // CommandLine structure handling parameter parsing