coredns/plugin/log/setup.go
Miek Gieben 004c5fca9d
all: simply registering plugins (#3287)
Abstract the caddy call and make it simpler.

See #3261 for some part of the discussion.

Go from:

~~~ go
func init() {
       caddy.RegisterPlugin("any", caddy.Plugin{
               ServerType: "dns",
               Action:     setup,
       })
}
~~~

To:

~~~ go
func init() { plugin.Register("any", setup) }
~~~

This requires some external documents in coredns.io to be updated as
well; the old way still works, so it's backwards compatible.

Signed-off-by: Miek Gieben <miek@miek.nl>
2019-09-20 08:02:30 +01:00

108 lines
2.3 KiB
Go

package log
import (
"strings"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"github.com/coredns/coredns/plugin/pkg/replacer"
"github.com/coredns/coredns/plugin/pkg/response"
"github.com/caddyserver/caddy"
"github.com/miekg/dns"
)
func init() { plugin.Register("log", setup) }
func setup(c *caddy.Controller) error {
rules, err := logParse(c)
if err != nil {
return plugin.Error("log", err)
}
dnsserver.GetConfig(c).AddPlugin(func(next plugin.Handler) plugin.Handler {
return Logger{Next: next, Rules: rules, repl: replacer.New()}
})
return nil
}
func logParse(c *caddy.Controller) ([]Rule, error) {
var rules []Rule
for c.Next() {
args := c.RemainingArgs()
length := len(rules)
switch len(args) {
case 0:
// Nothing specified; use defaults
rules = append(rules, Rule{
NameScope: ".",
Format: DefaultLogFormat,
Class: make(map[response.Class]struct{}),
})
case 1:
rules = append(rules, Rule{
NameScope: dns.Fqdn(args[0]),
Format: DefaultLogFormat,
Class: make(map[response.Class]struct{}),
})
default:
// Name scopes, and maybe a format specified
format := DefaultLogFormat
if strings.Contains(args[len(args)-1], "{") {
switch args[len(args)-1] {
case "{common}":
format = CommonLogFormat
case "{combined}":
format = CombinedLogFormat
default:
format = args[len(args)-1]
}
args = args[:len(args)-1]
}
for _, str := range args {
rules = append(rules, Rule{
NameScope: dns.Fqdn(str),
Format: format,
Class: make(map[response.Class]struct{}),
})
}
}
// Class refinements in an extra block.
classes := make(map[response.Class]struct{})
for c.NextBlock() {
switch c.Val() {
// class followed by combinations of all, denial, error and success.
case "class":
classesArgs := c.RemainingArgs()
if len(classesArgs) == 0 {
return nil, c.ArgErr()
}
for _, c := range classesArgs {
cls, err := response.ClassFromString(c)
if err != nil {
return nil, err
}
classes[cls] = struct{}{}
}
default:
return nil, c.ArgErr()
}
}
if len(classes) == 0 {
classes[response.All] = struct{}{}
}
for i := len(rules) - 1; i >= length; i-- {
rules[i].Class = classes
}
}
return rules, nil
}