Clean up remove caddy refs (#139)

* Changed reference to Caddy over to CoreDNS

* Removing references to caddy

* Fixed misleading error message to reference coredns

* Cleaning up references to caddy

* Adding clean and deps targets

Muscle memory is resulting in "make clean" commands.

* Adding test target to makefile

* More "Caddy" cleanup
This commit is contained in:
Michael Richmond 2016-04-28 11:07:44 -07:00 committed by Miek Gieben
parent bba63f7765
commit e34280e7af
19 changed files with 146 additions and 134 deletions

View file

@ -5,3 +5,15 @@ all:
docker: docker:
GOOS=linux go build -a -tags netgo -installsuffix netgo GOOS=linux go build -a -tags netgo -installsuffix netgo
docker build -t $$USER/coredns . docker build -t $$USER/coredns .
.PHONY: deps
deps:
go get
.PHONY: test
test:
go test
.PHONY: clean
clean:
go clean

View file

@ -7,6 +7,6 @@ import (
func TestPath(t *testing.T) { func TestPath(t *testing.T) {
if actual := Path(); !strings.HasSuffix(actual, ".coredns") { if actual := Path(); !strings.HasSuffix(actual, ".coredns") {
t.Errorf("Expected path to be a .caddy folder, got: %v", actual) t.Errorf("Expected path to be a .coredns folder, got: %v", actual)
} }
} }

View file

@ -1,16 +1,16 @@
// Package caddy implements the Caddy web server as a service // Package caddy implements the CoreDNS web server as a service
// in your own Go programs. // in your own Go programs.
// //
// To use this package, follow a few simple steps: // To use this package, follow a few simple steps:
// //
// 1. Set the AppName and AppVersion variables. // 1. Set the AppName and AppVersion variables.
// 2. Call LoadCaddyfile() to get the Caddyfile (it // 2. Call LoadCorefile() to get the Corefile (it
// might have been piped in as part of a restart). // might have been piped in as part of a restart).
// You should pass in your own Caddyfile loader. // You should pass in your own Corefile loader.
// 3. Call caddy.Start() to start Caddy, caddy.Stop() // 3. Call caddy.Start() to start CoreDNS, caddy.Stop()
// to stop it, or caddy.Restart() to restart it. // to stop it, or caddy.Restart() to restart it.
// //
// You should use caddy.Wait() to wait for all Caddy servers // You should use caddy.Wait() to wait for all CoreDNS servers
// to quit before your process exits. // to quit before your process exits.
package core package core
@ -52,14 +52,14 @@ var (
) )
var ( var (
// caddyfile is the input configuration text used for this process // corefile is the input configuration text used for this process
caddyfile Input corefile Input
// caddyfileMu protects caddyfile during changes // corefileMu protects corefile during changes
caddyfileMu sync.Mutex corefileMu sync.Mutex
// errIncompleteRestart occurs if this process is a fork // errIncompleteRestart occurs if this process is a fork
// of the parent but no Caddyfile was piped in // of the parent but no Corefile was piped in
errIncompleteRestart = errors.New("incomplete restart") errIncompleteRestart = errors.New("incomplete restart")
// servers is a list of all the currently-listening servers // servers is a list of all the currently-listening servers
@ -75,9 +75,9 @@ var (
// a graceful restart; it is used to map listeners to their // a graceful restart; it is used to map listeners to their
// index in the list of inherited file descriptors. This // index in the list of inherited file descriptors. This
// variable is not safe for concurrent access. // variable is not safe for concurrent access.
loadedGob caddyfileGob loadedGob corefileGob
// startedBefore should be set to true if caddy has been started // startedBefore should be set to true if CoreDNS has been started
// at least once (does not indicate whether currently running). // at least once (does not indicate whether currently running).
startedBefore bool startedBefore bool
) )
@ -91,8 +91,8 @@ const (
DefaultRoot = "." DefaultRoot = "."
) )
// Start starts Caddy with the given Caddyfile. If cdyfile // Start starts CoreDNS with the given Corefile. If crfile
// is nil, the LoadCaddyfile function will be called to get // is nil, the LoadCorefile function will be called to get
// one. // one.
// //
// This function blocks until all the servers are listening. // This function blocks until all the servers are listening.
@ -101,12 +101,12 @@ const (
// restart more than once within the duration of the graceful // restart more than once within the duration of the graceful
// cutoff (i.e. the child process called Start a first time, // cutoff (i.e. the child process called Start a first time,
// then called Stop, then Start again within the first 5 seconds // then called Stop, then Start again within the first 5 seconds
// or however long GracefulTimeout is) and the Caddyfiles have // or however long GracefulTimeout is) and the Corefiles have
// at least one listener address in common, the second Start // at least one listener address in common, the second Start
// may fail with "address already in use" as there's no // may fail with "address already in use" as there's no
// guarantee that the parent process has relinquished the // guarantee that the parent process has relinquished the
// address before the grace period ends. // address before the grace period ends.
func Start(cdyfile Input) (err error) { func Start(crfile Input) (err error) {
// If we return with no errors, we must do two things: tell the // If we return with no errors, we must do two things: tell the
// parent that we succeeded and write to the pidfile. // parent that we succeeded and write to the pidfile.
defer func() { defer func() {
@ -122,19 +122,19 @@ func Start(cdyfile Input) (err error) {
}() }()
// Input must never be nil; try to load something // Input must never be nil; try to load something
if cdyfile == nil { if crfile == nil {
cdyfile, err = LoadCaddyfile(nil) crfile, err = LoadCorefile(nil)
if err != nil { if err != nil {
return err return err
} }
} }
caddyfileMu.Lock() corefileMu.Lock()
caddyfile = cdyfile corefile = crfile
caddyfileMu.Unlock() corefileMu.Unlock()
// load the server configs (activates Let's Encrypt) // load the server configs (activates Let's Encrypt)
configs, err := loadConfigs(path.Base(cdyfile.Path()), bytes.NewReader(cdyfile.Body())) configs, err := loadConfigs(path.Base(crfile.Path()), bytes.NewReader(crfile.Body()))
if err != nil { if err != nil {
return err return err
} }
@ -303,14 +303,14 @@ func Wait() {
wg.Wait() wg.Wait()
} }
// LoadCaddyfile loads a Caddyfile, prioritizing a Caddyfile // LoadCorefile loads a Corefile, prioritizing a Corefile
// piped from stdin as part of a restart (only happens on first call // piped from stdin as part of a restart (only happens on first call
// to LoadCaddyfile). If it is not a restart, this function tries // to LoadCorefile). If it is not a restart, this function tries
// calling the user's loader function, and if that returns nil, then // calling the user's loader function, and if that returns nil, then
// this function resorts to the default configuration. Thus, if there // this function resorts to the default configuration. Thus, if there
// are no other errors, this function always returns at least the // are no other errors, this function always returns at least the
// default Caddyfile. // default Corefile.
func LoadCaddyfile(loader func() (Input, error)) (cdyfile Input, err error) { func LoadCorefile(loader func() (Input, error)) (crfile Input, err error) {
// If we are a fork, finishing the restart is highest priority; // If we are a fork, finishing the restart is highest priority;
// piped input is required in this case. // piped input is required in this case.
if IsRestart() { if IsRestart() {
@ -318,30 +318,30 @@ func LoadCaddyfile(loader func() (Input, error)) (cdyfile Input, err error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
cdyfile = loadedGob.Caddyfile crfile = loadedGob.Corefile
atomic.StoreInt32(https.OnDemandIssuedCount, loadedGob.OnDemandTLSCertsIssued) atomic.StoreInt32(https.OnDemandIssuedCount, loadedGob.OnDemandTLSCertsIssued)
} }
// Try user's loader // Try user's loader
if cdyfile == nil && loader != nil { if crfile == nil && loader != nil {
cdyfile, err = loader() crfile, err = loader()
} }
// Otherwise revert to default // Otherwise revert to default
if cdyfile == nil { if crfile == nil {
cdyfile = DefaultInput() crfile = DefaultInput()
} }
return return
} }
// CaddyfileFromPipe loads the Caddyfile input from f if f is // CorefileFromPipe loads the Corefile input from f if f is
// not interactive input. f is assumed to be a pipe or stream, // not interactive input. f is assumed to be a pipe or stream,
// such as os.Stdin. If f is not a pipe, no error is returned // such as os.Stdin. If f is not a pipe, no error is returned
// but the Input value will be nil. An error is only returned // but the Input value will be nil. An error is only returned
// if there was an error reading the pipe, even if the length // if there was an error reading the pipe, even if the length
// of what was read is 0. // of what was read is 0.
func CaddyfileFromPipe(f *os.File) (Input, error) { func CorefileFromPipe(f *os.File) (Input, error) {
fi, err := f.Stat() fi, err := f.Stat()
if err == nil && fi.Mode()&os.ModeCharDevice == 0 { if err == nil && fi.Mode()&os.ModeCharDevice == 0 {
// Note that a non-nil error is not a problem. Windows // Note that a non-nil error is not a problem. Windows
@ -354,7 +354,7 @@ func CaddyfileFromPipe(f *os.File) (Input, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
return CaddyfileInput{ return CorefileInput{
Contents: confBody, Contents: confBody,
Filepath: f.Name(), Filepath: f.Name(),
}, nil }, nil
@ -365,20 +365,20 @@ func CaddyfileFromPipe(f *os.File) (Input, error) {
return nil, nil return nil, nil
} }
// Caddyfile returns the current Caddyfile // Corefile returns the current Corefile
func Caddyfile() Input { func Corefile() Input {
caddyfileMu.Lock() corefileMu.Lock()
defer caddyfileMu.Unlock() defer corefileMu.Unlock()
return caddyfile return corefile
} }
// Input represents a Caddyfile; its contents and file path // Input represents a Corefile; its contents and file path
// (which should include the file name at the end of the path). // (which should include the file name at the end of the path).
// If path does not apply (e.g. piped input) you may use // If path does not apply (e.g. piped input) you may use
// any understandable value. The path is mainly used for logging, // any understandable value. The path is mainly used for logging,
// error messages, and debugging. // error messages, and debugging.
type Input interface { type Input interface {
// Gets the Caddyfile contents // Gets the Corefile contents
Body() []byte Body() []byte
// Gets the path to the origin file // Gets the path to the origin file
@ -394,8 +394,8 @@ type Input interface {
// with Stop(). It just takes a normal Corefile as input. // with Stop(). It just takes a normal Corefile as input.
func TestServer(t *testing.T, corefile string) (*server.Server, error) { func TestServer(t *testing.T, corefile string) (*server.Server, error) {
cdyfile := CaddyfileInput{Contents: []byte(corefile)} crfile := CorefileInput{Contents: []byte(corefile)}
configs, err := loadConfigs(path.Base(cdyfile.Path()), bytes.NewReader(cdyfile.Body())) configs, err := loadConfigs(path.Base(crfile.Path()), bytes.NewReader(crfile.Body()))
if err != nil { if err != nil {
return nil, err return nil, err
} }

View file

@ -2,10 +2,10 @@ package core
/* /*
func TestCaddyStartStop(t *testing.T) { func TestCaddyStartStop(t *testing.T) {
caddyfile := "localhost:1984" corefile := "localhost:1984"
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
err := Start(CaddyfileInput{Contents: []byte(caddyfile)}) err := Start(CorefileInput{Contents: []byte(corefile)})
if err != nil { if err != nil {
t.Fatalf("Error starting, iteration %d: %v", i, err) t.Fatalf("Error starting, iteration %d: %v", i, err)
} }

View file

@ -23,7 +23,7 @@ func loadConfigsUpToIncludingTLS(filename string, input io.Reader) ([]server.Con
var configs []server.Config var configs []server.Config
// Each server block represents similar hosts/addresses, since they // Each server block represents similar hosts/addresses, since they
// were grouped together in the Caddyfile. // were grouped together in the Corefile.
serverBlocks, err := parse.ServerBlocks(filename, input, true) serverBlocks, err := parse.ServerBlocks(filename, input, true)
if err != nil { if err != nil {
return nil, nil, 0, err return nil, nil, 0, err
@ -304,12 +304,12 @@ func validDirective(d string) bool {
return false return false
} }
// DefaultInput returns the default Caddyfile input // DefaultInput returns the default Corefile input
// to use when it is otherwise empty or missing. // to use when it is otherwise empty or missing.
// It uses the default host and port and root. // It uses the default host and port and root.
func DefaultInput() CaddyfileInput { func DefaultInput() CorefileInput {
port := Port port := Port
return CaddyfileInput{ return CorefileInput{
Contents: []byte(fmt.Sprintf("%s:%s\nroot %s", Host, port, Root)), Contents: []byte(fmt.Sprintf("%s:%s\nroot %s", Host, port, Root)),
} }
} }

View file

@ -68,7 +68,7 @@ var directiveOrder = []directive{
{"proxy", setup.Proxy}, {"proxy", setup.Proxy},
} }
// RegisterDirective adds the given directive to caddy's list of directives. // RegisterDirective adds the given directive to CoreDNS's list of directives.
// Pass the name of a directive you want it to be placed after, // Pass the name of a directive you want it to be placed after,
// otherwise it will be placed at the bottom of the stack. // otherwise it will be placed at the bottom of the stack.
func RegisterDirective(name string, setup SetupFunc, after string) { func RegisterDirective(name string, setup SetupFunc, after string) {

View file

@ -57,24 +57,24 @@ func signalSuccessToParent() {
// signaled once; doing so more than once breaks whatever socket is // signaled once; doing so more than once breaks whatever socket is
// at fd 4 (the reason for this is still unclear - to reproduce, // at fd 4 (the reason for this is still unclear - to reproduce,
// call Stop() and Start() in succession at least once after a // call Stop() and Start() in succession at least once after a
// restart, then try loading first host of Caddyfile in the browser). // restart, then try loading first host of Corefile in the browser).
// Do not use this directly - call signalSuccessToParent instead. // Do not use this directly - call signalSuccessToParent instead.
var signalParentOnce sync.Once var signalParentOnce sync.Once
// caddyfileGob maps bind address to index of the file descriptor // corefileGob maps bind address to index of the file descriptor
// in the Files array passed to the child process. It also contains // in the Files array passed to the child process. It also contains
// the caddyfile contents and other state needed by the new process. // the corefile contents and other state needed by the new process.
// Used only during graceful restarts where a new process is spawned. // Used only during graceful restarts where a new process is spawned.
type caddyfileGob struct { type corefileGob struct {
ListenerFds map[string]uintptr ListenerFds map[string]uintptr
Caddyfile Input Corefile Input
OnDemandTLSCertsIssued int32 OnDemandTLSCertsIssued int32
} }
// IsRestart returns whether this process is, according // IsRestart returns whether this process is, according
// to env variables, a fork as part of a graceful restart. // to env variables, a fork as part of a graceful restart.
func IsRestart() bool { func IsRestart() bool {
return os.Getenv("CADDY_RESTART") == "true" return os.Getenv("COREDNS_RESTART") == "true"
} }
// writePidFile writes the process ID to the file at PidFile, if specified. // writePidFile writes the process ID to the file at PidFile, if specified.
@ -83,20 +83,20 @@ func writePidFile() error {
return ioutil.WriteFile(PidFile, pid, 0644) return ioutil.WriteFile(PidFile, pid, 0644)
} }
// CaddyfileInput represents a Caddyfile as input // CorefileInput represents a Corefile as input
// and is simply a convenient way to implement // and is simply a convenient way to implement
// the Input interface. // the Input interface.
type CaddyfileInput struct { type CorefileInput struct {
Filepath string Filepath string
Contents []byte Contents []byte
RealFile bool RealFile bool
} }
// Body returns c.Contents. // Body returns c.Contents.
func (c CaddyfileInput) Body() []byte { return c.Contents } func (c CorefileInput) Body() []byte { return c.Contents }
// Path returns c.Filepath. // Path returns c.Filepath.
func (c CaddyfileInput) Path() string { return c.Filepath } func (c CorefileInput) Path() string { return c.Filepath }
// IsFile returns true if the original input was a real file on the file system. // IsFile returns true if the original input was a real file on the file system.
func (c CaddyfileInput) IsFile() bool { return c.RealFile } func (c CorefileInput) IsFile() bool { return c.RealFile }

View file

@ -33,7 +33,7 @@ type Certificate struct {
// NotAfter is when the certificate expires. // NotAfter is when the certificate expires.
NotAfter time.Time NotAfter time.Time
// Managed certificates are certificates that Caddy is managing, // Managed certificates are certificates that CoreDNS is managing,
// as opposed to the user specifying a certificate and key file // as opposed to the user specifying a certificate and key file
// or directory and managing the certificate resources themselves. // or directory and managing the certificate resources themselves.
Managed bool Managed bool

View file

@ -301,7 +301,7 @@ var OnDemandIssuedCount = new(int32)
// maximum number of certificates that can be issued. // maximum number of certificates that can be issued.
// TODO: This applies globally, but we should probably make a server-specific // TODO: This applies globally, but we should probably make a server-specific
// way to keep track of these limits and counts, since it's specified in the // way to keep track of these limits and counts, since it's specified in the
// Caddyfile... // Corefile...
var onDemandMaxIssue int32 var onDemandMaxIssue int32
// failedIssuance is a set of names that we recently failed to get a // failedIssuance is a set of names that we recently failed to get a

View file

@ -1,5 +1,5 @@
// Package https facilitates the management of TLS assets and integrates // Package https facilitates the management of TLS assets and integrates
// Let's Encrypt functionality into Caddy with first-class support for // Let's Encrypt functionality into CoreDNS with first-class support for
// creating and renewing certificates automatically. It is designed to // creating and renewing certificates automatically. It is designed to
// configure sites for HTTPS by default. // configure sites for HTTPS by default.
package https package https

View file

@ -121,14 +121,14 @@ func newUser(email string) (User, error) {
// input. If userPresent is false, the operator will // input. If userPresent is false, the operator will
// NOT be prompted and an empty email may be returned. // NOT be prompted and an empty email may be returned.
func getEmail(cfg server.Config, userPresent bool) string { func getEmail(cfg server.Config, userPresent bool) string {
// First try the tls directive from the Caddyfile // First try the tls directive from the Corefile
leEmail := cfg.TLS.LetsEncryptEmail leEmail := cfg.TLS.LetsEncryptEmail
if leEmail == "" { if leEmail == "" {
// Then try memory (command line flag or typed by user previously) // Then try memory (command line flag or typed by user previously)
leEmail = DefaultEmail leEmail = DefaultEmail
} }
if leEmail == "" { if leEmail == "" {
// Then try to get most recent user email ~/.caddy/users file // Then try to get most recent user email ~/.coredns/users file
userDirs, err := ioutil.ReadDir(storage.Users()) userDirs, err := ioutil.ReadDir(storage.Users())
if err == nil { if err == nil {
var mostRecent os.FileInfo var mostRecent os.FileInfo

View file

@ -55,7 +55,7 @@ func (p *parser) begin() error {
} }
if p.eof { if p.eof {
// this happens if the Caddyfile consists of only // this happens if the Corefile consists of only
// a line of addresses and nothing else // a line of addresses and nothing else
return nil return nil
} }
@ -91,7 +91,7 @@ func (p *parser) addresses() error {
break break
} }
if tkn != "" { // empty token possible if user typed "" in Caddyfile if tkn != "" { // empty token possible if user typed "" in Corefile
// Trailing comma indicates another address will follow, which // Trailing comma indicates another address will follow, which
// may possibly be on the next line // may possibly be on the next line
if tkn[len(tkn)-1] == ',' { if tkn[len(tkn)-1] == ',' {

View file

@ -18,32 +18,32 @@ import (
) )
func init() { func init() {
gob.Register(CaddyfileInput{}) gob.Register(CorefileInput{})
} }
// Restart restarts the entire application; gracefully with zero // Restart restarts the entire application; gracefully with zero
// downtime if on a POSIX-compatible system, or forcefully if on // downtime if on a POSIX-compatible system, or forcefully if on
// Windows but with imperceptibly-short downtime. // Windows but with imperceptibly-short downtime.
// //
// The restarted application will use newCaddyfile as its input // The restarted application will use newCorefile as its input
// configuration. If newCaddyfile is nil, the current (existing) // configuration. If newCorefile is nil, the current (existing)
// Caddyfile configuration will be used. // Corefile configuration will be used.
// //
// Note: The process must exist in the same place on the disk in // Note: The process must exist in the same place on the disk in
// order for this to work. Thus, multiple graceful restarts don't // order for this to work. Thus, multiple graceful restarts don't
// work if executing with `go run`, since the binary is cleaned up // work if executing with `go run`, since the binary is cleaned up
// when `go run` sees the initial parent process exit. // when `go run` sees the initial parent process exit.
func Restart(newCaddyfile Input) error { func Restart(newCorefile Input) error {
log.Println("[INFO] Restarting") log.Println("[INFO] Restarting")
if newCaddyfile == nil { if newCorefile == nil {
caddyfileMu.Lock() corefileMu.Lock()
newCaddyfile = caddyfile newCorefile = corefile
caddyfileMu.Unlock() corefileMu.Unlock()
} }
// Get certificates for any new hosts in the new Caddyfile without causing downtime // Get certificates for any new hosts in the new Corefile without causing downtime
err := getCertsForNewCaddyfile(newCaddyfile) err := getCertsForNewCorefile(newCorefile)
if err != nil { if err != nil {
return errors.New("TLS preload: " + err.Error()) return errors.New("TLS preload: " + err.Error())
} }
@ -53,16 +53,16 @@ func Restart(newCaddyfile Input) error {
} }
// Tell the child that it's a restart // Tell the child that it's a restart
os.Setenv("CADDY_RESTART", "true") os.Setenv("COREDNS_RESTART", "true")
// Prepare our payload to the child process // Prepare our payload to the child process
cdyfileGob := caddyfileGob{ crfileGob := corefileGob{
ListenerFds: make(map[string]uintptr), ListenerFds: make(map[string]uintptr),
Caddyfile: newCaddyfile, Corefile: newCorefile,
OnDemandTLSCertsIssued: atomic.LoadInt32(https.OnDemandIssuedCount), OnDemandTLSCertsIssued: atomic.LoadInt32(https.OnDemandIssuedCount),
} }
// Prepare a pipe to the fork's stdin so it can get the Caddyfile // Prepare a pipe to the fork's stdin so it can get the Corefile
rpipe, wpipe, err := os.Pipe() rpipe, wpipe, err := os.Pipe()
if err != nil { if err != nil {
return err return err
@ -83,7 +83,7 @@ func Restart(newCaddyfile Input) error {
serversMu.Lock() serversMu.Lock()
for i, s := range servers { for i, s := range servers {
extraFiles = append(extraFiles, s.ListenerFd()) extraFiles = append(extraFiles, s.ListenerFd())
cdyfileGob.ListenerFds[s.Addr] = uintptr(4 + i) // 4 fds come before any of the listeners crfileGob.ListenerFds[s.Addr] = uintptr(4 + i) // 4 fds come before any of the listeners
} }
serversMu.Unlock() serversMu.Unlock()
@ -105,8 +105,8 @@ func Restart(newCaddyfile Input) error {
f.Close() f.Close()
} }
// Feed Caddyfile to the child // Feed Corefile to the child
err = gob.NewEncoder(wpipe).Encode(cdyfileGob) err = gob.NewEncoder(wpipe).Encode(crfileGob)
if err != nil { if err != nil {
return err return err
} }
@ -127,12 +127,12 @@ func Restart(newCaddyfile Input) error {
return Stop() return Stop()
} }
func getCertsForNewCaddyfile(newCaddyfile Input) error { func getCertsForNewCorefile(newCorefile Input) error {
// parse the new caddyfile only up to (and including) TLS // parse the new corefile only up to (and including) TLS
// so we can know what we need to get certs for. // so we can know what we need to get certs for.
configs, _, _, err := loadConfigsUpToIncludingTLS(path.Base(newCaddyfile.Path()), bytes.NewReader(newCaddyfile.Body())) configs, _, _, err := loadConfigsUpToIncludingTLS(path.Base(newCorefile.Path()), bytes.NewReader(newCorefile.Body()))
if err != nil { if err != nil {
return errors.New("loading Caddyfile: " + err.Error()) return errors.New("loading Corefile: " + err.Error())
} }
// first mark the configs that are qualified for managed TLS // first mark the configs that are qualified for managed TLS

View file

@ -2,15 +2,15 @@ package core
import "log" import "log"
// Restart restarts Caddy forcefully using newCaddyfile, // Restart restarts CoreDNS forcefully using newCorefile,
// or, if nil, the current/existing Caddyfile is reused. // or, if nil, the current/existing Corefile is reused.
func Restart(newCaddyfile Input) error { func Restart(newCorefile Input) error {
log.Println("[INFO] Restarting") log.Println("[INFO] Restarting")
if newCaddyfile == nil { if newCorefile == nil {
caddyfileMu.Lock() corefileMu.Lock()
newCaddyfile = caddyfile newCorefile = corefile
caddyfileMu.Unlock() corefileMu.Unlock()
} }
wg.Add(1) // barrier so Wait() doesn't unblock wg.Add(1) // barrier so Wait() doesn't unblock
@ -20,7 +20,7 @@ func Restart(newCaddyfile Input) error {
return err return err
} }
err = Start(newCaddyfile) err = Start(newCorefile)
if err != nil { if err != nil {
return err return err
} }

View file

@ -7,7 +7,7 @@ import (
"github.com/hashicorp/go-syslog" "github.com/hashicorp/go-syslog"
"github.com/miekg/coredns/middleware" "github.com/miekg/coredns/middleware"
caddylog "github.com/miekg/coredns/middleware/log" corednslog "github.com/miekg/coredns/middleware/log"
"github.com/miekg/coredns/server" "github.com/miekg/coredns/server"
"github.com/miekg/dns" "github.com/miekg/dns"
) )
@ -30,7 +30,7 @@ func Log(c *Controller) (middleware.Middleware, error) {
} else if rules[i].OutputFile == "stderr" { } else if rules[i].OutputFile == "stderr" {
writer = os.Stderr writer = os.Stderr
} else if rules[i].OutputFile == "syslog" { } else if rules[i].OutputFile == "syslog" {
writer, err = gsyslog.NewLogger(gsyslog.LOG_INFO, "LOCAL0", "caddy") writer, err = gsyslog.NewLogger(gsyslog.LOG_INFO, "LOCAL0", "coredns")
if err != nil { if err != nil {
return err return err
} }
@ -56,12 +56,12 @@ func Log(c *Controller) (middleware.Middleware, error) {
}) })
return func(next middleware.Handler) middleware.Handler { return func(next middleware.Handler) middleware.Handler {
return caddylog.Logger{Next: next, Rules: rules, ErrorFunc: server.DefaultErrorFunc} return corednslog.Logger{Next: next, Rules: rules, ErrorFunc: server.DefaultErrorFunc}
}, nil }, nil
} }
func logParse(c *Controller) ([]caddylog.Rule, error) { func logParse(c *Controller) ([]corednslog.Rule, error) {
var rules []caddylog.Rule var rules []corednslog.Rule
for c.Next() { for c.Next() {
args := c.RemainingArgs() args := c.RemainingArgs()
@ -88,37 +88,37 @@ func logParse(c *Controller) ([]caddylog.Rule, error) {
} }
if len(args) == 0 { if len(args) == 0 {
// Nothing specified; use defaults // Nothing specified; use defaults
rules = append(rules, caddylog.Rule{ rules = append(rules, corednslog.Rule{
NameScope: ".", NameScope: ".",
OutputFile: caddylog.DefaultLogFilename, OutputFile: corednslog.DefaultLogFilename,
Format: caddylog.DefaultLogFormat, Format: corednslog.DefaultLogFormat,
Roller: logRoller, Roller: logRoller,
}) })
} else if len(args) == 1 { } else if len(args) == 1 {
// Only an output file specified // Only an output file specified
rules = append(rules, caddylog.Rule{ rules = append(rules, corednslog.Rule{
NameScope: ".", NameScope: ".",
OutputFile: args[0], OutputFile: args[0],
Format: caddylog.DefaultLogFormat, Format: corednslog.DefaultLogFormat,
Roller: logRoller, Roller: logRoller,
}) })
} else { } else {
// Name scope, output file, and maybe a format specified // Name scope, output file, and maybe a format specified
format := caddylog.DefaultLogFormat format := corednslog.DefaultLogFormat
if len(args) > 2 { if len(args) > 2 {
switch args[2] { switch args[2] {
case "{common}": case "{common}":
format = caddylog.CommonLogFormat format = corednslog.CommonLogFormat
case "{combined}": case "{combined}":
format = caddylog.CombinedLogFormat format = corednslog.CombinedLogFormat
default: default:
format = args[2] format = args[2]
} }
} }
rules = append(rules, caddylog.Rule{ rules = append(rules, corednslog.Rule{
NameScope: dns.Fqdn(args[0]), NameScope: dns.Fqdn(args[0]),
OutputFile: args[1], OutputFile: args[1],
Format: format, Format: format,

View file

@ -48,28 +48,28 @@ func trapSignalsPosix() {
case syscall.SIGUSR1: case syscall.SIGUSR1:
log.Println("[INFO] SIGUSR1: Reloading") log.Println("[INFO] SIGUSR1: Reloading")
var updatedCaddyfile Input var updatedCorefile Input
caddyfileMu.Lock() corefileMu.Lock()
if caddyfile == nil { if corefile == nil {
// Hmm, did spawing process forget to close stdin? Anyhow, this is unusual. // Hmm, did spawing process forget to close stdin? Anyhow, this is unusual.
log.Println("[ERROR] SIGUSR1: no Corefile to reload (was stdin left open?)") log.Println("[ERROR] SIGUSR1: no Corefile to reload (was stdin left open?)")
caddyfileMu.Unlock() corefileMu.Unlock()
continue continue
} }
if caddyfile.IsFile() { if corefile.IsFile() {
body, err := ioutil.ReadFile(caddyfile.Path()) body, err := ioutil.ReadFile(corefile.Path())
if err == nil { if err == nil {
updatedCaddyfile = CaddyfileInput{ updatedCorefile = CorefileInput{
Filepath: caddyfile.Path(), Filepath: corefile.Path(),
Contents: body, Contents: body,
RealFile: true, RealFile: true,
} }
} }
} }
caddyfileMu.Unlock() corefileMu.Unlock()
err := Restart(updatedCaddyfile) err := Restart(updatedCorefile)
if err != nil { if err != nil {
log.Printf("[ERROR] SIGUSR1: %v", err) log.Printf("[ERROR] SIGUSR1: %v", err)
} }

16
main.go
View file

@ -84,13 +84,13 @@ func main() {
} }
// Get Corefile input // Get Corefile input
caddyfile, err := core.LoadCaddyfile(loadCaddyfile) corefile, err := core.LoadCorefile(loadCorefile)
if err != nil { if err != nil {
mustLogFatal(err) mustLogFatal(err)
} }
// Start your engines // Start your engines
err = core.Start(caddyfile) err = core.Start(corefile)
if err != nil { if err != nil {
mustLogFatal(err) mustLogFatal(err)
} }
@ -112,11 +112,11 @@ func mustLogFatal(args ...interface{}) {
log.Fatal(args...) log.Fatal(args...)
} }
func loadCaddyfile() (core.Input, error) { func loadCorefile() (core.Input, error) {
// Try -conf flag // Try -conf flag
if conf != "" { if conf != "" {
if conf == "stdin" { if conf == "stdin" {
return core.CaddyfileFromPipe(os.Stdin) return core.CorefileFromPipe(os.Stdin)
} }
contents, err := ioutil.ReadFile(conf) contents, err := ioutil.ReadFile(conf)
@ -124,7 +124,7 @@ func loadCaddyfile() (core.Input, error) {
return nil, err return nil, err
} }
return core.CaddyfileInput{ return core.CorefileInput{
Contents: contents, Contents: contents,
Filepath: conf, Filepath: conf,
RealFile: true, RealFile: true,
@ -134,13 +134,13 @@ func loadCaddyfile() (core.Input, error) {
// command line args // command line args
if flag.NArg() > 0 { if flag.NArg() > 0 {
confBody := core.Host + ":" + core.Port + "\n" + strings.Join(flag.Args(), "\n") confBody := core.Host + ":" + core.Port + "\n" + strings.Join(flag.Args(), "\n")
return core.CaddyfileInput{ return core.CorefileInput{
Contents: []byte(confBody), Contents: []byte(confBody),
Filepath: "args", Filepath: "args",
}, nil }, nil
} }
// Caddyfile in cwd // Corefile in cwd
contents, err := ioutil.ReadFile(core.DefaultConfigFile) contents, err := ioutil.ReadFile(core.DefaultConfigFile)
if err != nil { if err != nil {
if os.IsNotExist(err) { if os.IsNotExist(err) {
@ -148,7 +148,7 @@ func loadCaddyfile() (core.Input, error) {
} }
return nil, err return nil, err
} }
return core.CaddyfileInput{ return core.CorefileInput{
Contents: contents, Contents: contents,
Filepath: core.DefaultConfigFile, Filepath: core.DefaultConfigFile,
RealFile: true, RealFile: true,

View file

@ -12,12 +12,12 @@ func BenchmarkParseInsert(b *testing.B) {
} }
/* /*
var testDir = filepath.Join(os.TempDir(), "caddy_testdir") var testDir = filepath.Join(os.TempDir(), "coredns_testdir")
var ErrCustom = errors.New("Custom Error") var ErrCustom = errors.New("Custom Error")
// testFiles is a map with relative paths to test files as keys and file content as values. // testFiles is a map with relative paths to test files as keys and file content as values.
// The map represents the following structure: // The map represents the following structure:
// - $TEMP/caddy_testdir/ // - $TEMP/coredns_testdir/
// '-- file1.html // '-- file1.html
// '-- dirwithindex/ // '-- dirwithindex/
// '---- index.html // '---- index.html

View file

@ -31,7 +31,7 @@ proxy from to... {
* `from` is the base path to match for the request to be proxied. * `from` is the base path to match for the request to be proxied.
* `to` is the destination endpoint to proxy to. At least one is required, but multiple may be specified. * `to` is the destination endpoint to proxy to. At least one is required, but multiple may be specified.
* `policy` is the load balancing policy to use; applies only with multiple backends. May be one of random, least_conn, or round_robin. Default is random. * `policy` is the load balancing policy to use; applies only with multiple backends. May be one of random, least_conn, or round_robin. Default is random.
* `fail_timeout` specifies how long to consider a backend as down after it has failed. While it is down, requests will not be routed to that backend. A backend is "down" if Caddy fails to communicate with it. The default value is 10 seconds ("10s"). * `fail_timeout` specifies how long to consider a backend as down after it has failed. While it is down, requests will not be routed to that backend. A backend is "down" if CoreDNS fails to communicate with it. The default value is 10 seconds ("10s").
* `max_fails` is the number of failures within fail_timeout that are needed before considering a backend to be down. If 0, the backend will never be marked as down. Default is 1. * `max_fails` is the number of failures within fail_timeout that are needed before considering a backend to be down. If 0, the backend will never be marked as down. Default is 1.
* `health_check` will check path (on port) on each backend. If a backend returns a status code of 200-399, then that backend is healthy. If it doesn't, the backend is marked as unhealthy for duration and no requests are routed to it. If this option is not provided then health checks are disabled. The default duration is 10 seconds ("10s"). * `health_check` will check path (on port) on each backend. If a backend returns a status code of 200-399, then that backend is healthy. If it doesn't, the backend is marked as unhealthy for duration and no requests are routed to it. If this option is not provided then health checks are disabled. The default duration is 10 seconds ("10s").
* `ignored_names...` is a space-separated list of paths to exclude from proxying. Requests that match any of these paths will be passed thru. * `ignored_names...` is a space-separated list of paths to exclude from proxying. Requests that match any of these paths will be passed thru.