-
Notifications
You must be signed in to change notification settings - Fork 21
/
setup.go
104 lines (92 loc) · 1.99 KB
/
setup.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package pdsql
import (
"github.com/glebarez/sqlite"
"github.com/wenerme/coredns-pdsql/pdnsmodel"
"log"
"github.com/coredns/caddy"
"github.com/coredns/coredns/core/dnsserver"
"github.com/coredns/coredns/plugin"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func init() {
caddy.RegisterPlugin("pdsql", caddy.Plugin{
ServerType: "dns",
Action: setup,
})
}
func setup(c *caddy.Controller) error {
backend := PowerDNSGenericSQLBackend{}
c.Next()
if !c.NextArg() {
return plugin.Error("pdsql", c.ArgErr())
}
dialect := c.Val()
if !c.NextArg() {
return plugin.Error("pdsql", c.ArgErr())
}
arg := c.Val()
var dialector gorm.Dialector
switch dialect {
case "sqlite":
fallthrough
case "sqlite3":
dialector = sqlite.Open(arg)
case "pg":
fallthrough
case "postgresql":
fallthrough
case "postgres":
dialector = postgres.New(postgres.Config{
DSN: arg,
})
case "mysql":
dialector = mysql.Open(arg)
default:
return plugin.Error("pdsql", c.Errf("unsupported dialect %v", dialect))
}
db, err := gorm.Open(dialector)
if err != nil {
return err
}
backend.DB = db
for c.NextBlock() {
x := c.Val()
switch x {
case "debug":
args := c.RemainingArgs()
for _, v := range args {
switch v {
case "db":
backend.DB = backend.DB.Debug()
}
}
backend.Debug = true
log.Println(Name, "enable log", args)
case "auto-migrate":
// currently only use records table
if err := backend.AutoMigrate(); err != nil {
return err
}
case "driver": // todo
case "dialect": // todo
case "dsn": // todo
default:
return plugin.Error("pdsql", c.Errf("unexpected '%v' command", x))
}
}
if c.NextArg() {
return plugin.Error("pdsql", c.ArgErr())
}
dnsserver.
GetConfig(c).
AddPlugin(func(next plugin.Handler) plugin.Handler {
backend.Next = next
return backend
})
return nil
}
func (pdb PowerDNSGenericSQLBackend) AutoMigrate() error {
return pdb.DB.AutoMigrate(&pdnsmodel.Record{}, &pdnsmodel.Domain{})
}