forked from lucaslorentz/caddy-docker-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.go
287 lines (252 loc) · 9.03 KB
/
generator.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
package generator
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"regexp"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"github.com/xlp/caddy-docker-proxy/v2/caddyfile"
"github.com/xlp/caddy-docker-proxy/v2/config"
"github.com/xlp/caddy-docker-proxy/v2/docker"
"go.uber.org/zap"
)
// DefaultLabelPrefix for caddy labels in docker
const DefaultLabelPrefix = "caddy"
const swarmAvailabilityCacheInterval = 1 * time.Minute
// CaddyfileGenerator generates caddyfile from docker configuration
type CaddyfileGenerator struct {
options *config.Options
labelRegex *regexp.Regexp
dockerClients []docker.Client
dockerUtils docker.Utils
ingressNetworks map[string]bool
swarmIsAvailable []bool
swarmIsAvailableTime time.Time
}
// CreateGenerator creates a new generator
func CreateGenerator(dockerClients []docker.Client, dockerUtils docker.Utils, options *config.Options) *CaddyfileGenerator {
var labelRegexString = fmt.Sprintf("^%s(_\\d+)?(\\.|$)", options.LabelPrefix)
return &CaddyfileGenerator{
options: options,
labelRegex: regexp.MustCompile(labelRegexString),
dockerClients: dockerClients,
swarmIsAvailable: make([]bool, len(dockerClients)),
dockerUtils: dockerUtils,
}
}
// GenerateCaddyfile generates a caddy file config from docker metadata
func (g *CaddyfileGenerator) GenerateCaddyfile(logger *zap.Logger) ([]byte, []string) {
var caddyfileBuffer bytes.Buffer
if g.ingressNetworks == nil {
ingressNetworks, err := g.getIngressNetworks(logger)
if err == nil {
g.ingressNetworks = ingressNetworks
} else {
logger.Error("Failed to get ingress networks", zap.Error(err))
}
}
if time.Since(g.swarmIsAvailableTime) > swarmAvailabilityCacheInterval {
g.checkSwarmAvailability(logger, time.Time.IsZero(g.swarmIsAvailableTime))
g.swarmIsAvailableTime = time.Now()
}
caddyfileBlock := caddyfile.CreateContainer()
controlledServers := []string{}
// Add caddyfile from path
if g.options.CaddyfilePath != "" {
dat, err := ioutil.ReadFile(g.options.CaddyfilePath)
if err != nil {
logger.Error("Failed to read Caddyfile", zap.String("path", g.options.CaddyfilePath), zap.Error(err))
} else {
block, err := caddyfile.Unmarshal(dat)
if err != nil {
logger.Error("Failed to parse Caddyfile", zap.String("path", g.options.CaddyfilePath), zap.Error(err))
} else {
caddyfileBlock.Merge(block)
}
}
} else {
logger.Debug("Skipping default Caddyfile because no path is set")
}
for i, dockerClient := range g.dockerClients {
// Add Caddyfile from swarm configs
if g.swarmIsAvailable[i] {
configs, err := dockerClient.ConfigList(context.Background(), types.ConfigListOptions{})
if err == nil {
for _, config := range configs {
if _, hasLabel := config.Spec.Labels[g.options.LabelPrefix]; hasLabel {
fullConfig, _, err := dockerClient.ConfigInspectWithRaw(context.Background(), config.ID)
if err != nil {
logger.Error("Failed to inspect Swarm Config", zap.String("config", config.Spec.Name), zap.Error(err))
} else {
block, err := caddyfile.Unmarshal(fullConfig.Spec.Data)
if err != nil {
logger.Error("Failed to parse Swarm Config caddyfile format", zap.String("config", config.Spec.Name), zap.Error(err))
} else {
caddyfileBlock.Merge(block)
}
}
}
}
} else {
logger.Error("Failed to get Swarm configs", zap.Error(err))
}
} else {
logger.Debug("Skipping swarm config caddyfiles because swarm is not available")
}
// Add containers
containers, err := dockerClient.ContainerList(context.Background(), types.ContainerListOptions{})
if err == nil {
for _, container := range containers {
if _, isControlledServer := container.Labels[g.options.ControlledServersLabel]; isControlledServer {
ips, err := g.getContainerIPAddresses(&container, logger, false)
if err != nil {
logger.Error("Failed to get Container IPs", zap.String("container", container.ID), zap.Error(err))
} else {
for _, ip := range ips {
if g.options.ControllerNetwork == nil || g.options.ControllerNetwork.Contains(net.ParseIP(ip)) {
controlledServers = append(controlledServers, ip)
}
}
}
}
containerCaddyfile, err := g.getContainerCaddyfile(&container, logger)
if err == nil {
caddyfileBlock.Merge(containerCaddyfile)
} else {
logger.Error("Failed to get Container Caddyfile", zap.String("container", container.ID), zap.Error(err))
}
}
} else {
logger.Error("Failed to get ContainerList", zap.Error(err))
}
// Add services
if g.swarmIsAvailable[i] {
services, err := dockerClient.ServiceList(context.Background(), types.ServiceListOptions{})
if err == nil {
for _, service := range services {
logger.Debug("Swarm service", zap.String("service", service.Spec.Name))
if _, isControlledServer := service.Spec.Labels[g.options.ControlledServersLabel]; isControlledServer {
ips, err := g.getServiceTasksIps(&service, logger, false)
if err != nil {
logger.Error("Failed to get Swarm service IPs", zap.String("service", service.Spec.Name), zap.Error(err))
} else {
for _, ip := range ips {
if g.options.ControllerNetwork == nil || g.options.ControllerNetwork.Contains(net.ParseIP(ip)) {
controlledServers = append(controlledServers, ip)
}
}
}
}
// caddy. labels based config
serviceCaddyfile, err := g.getServiceCaddyfile(&service, logger)
if err == nil {
caddyfileBlock.Merge(serviceCaddyfile)
} else {
logger.Error("Failed to get Swarm service caddyfile", zap.String("service", service.Spec.Name), zap.Error(err))
}
}
} else {
logger.Error("Failed to get Swarm services", zap.Error(err))
}
} else {
logger.Debug("Skipping swarm services because swarm is not available")
}
}
// Write global blocks first
globalCaddyfile := caddyfile.CreateContainer()
for _, block := range caddyfileBlock.Children {
if block.IsGlobalBlock() {
globalCaddyfile.AddBlock(block)
caddyfileBlock.Remove(block)
}
}
caddyfileBuffer.Write(globalCaddyfile.Marshal())
// Write remaining blocks
caddyfileBuffer.Write(caddyfileBlock.Marshal())
caddyfileContent := caddyfileBuffer.Bytes()
if g.options.ProcessCaddyfile {
processCaddyfileContent, processLogs := caddyfile.Process(caddyfileContent)
caddyfileContent = processCaddyfileContent
if len(processLogs) > 0 {
logger.Info("Process Caddyfile", zap.ByteString("logs", processLogs))
}
}
if len(caddyfileContent) == 0 {
caddyfileContent = []byte("# Empty caddyfile")
}
if g.options.Mode&config.Server == config.Server {
controlledServers = append(controlledServers, "localhost")
}
return caddyfileContent, controlledServers
}
func (g *CaddyfileGenerator) checkSwarmAvailability(logger *zap.Logger, isFirstCheck bool) {
for i, dockerClient := range g.dockerClients {
info, err := dockerClient.Info(context.Background())
if err == nil {
newSwarmIsAvailable := info.Swarm.LocalNodeState == swarm.LocalNodeStateActive
if isFirstCheck || newSwarmIsAvailable != g.swarmIsAvailable[i] {
logger.Info("Swarm is available", zap.Bool("new", newSwarmIsAvailable))
}
g.swarmIsAvailable[i] = newSwarmIsAvailable
} else {
logger.Error("Swarm availability check failed", zap.Error(err))
g.swarmIsAvailable[i] = false
}
}
}
func (g *CaddyfileGenerator) getIngressNetworks(logger *zap.Logger) (map[string]bool, error) {
ingressNetworks := map[string]bool{}
for _, dockerClient := range g.dockerClients {
if len(g.options.IngressNetworks) > 0 {
networks, err := dockerClient.NetworkList(context.Background(), types.NetworkListOptions{})
if err != nil {
return nil, err
}
for _, dockerNetwork := range networks {
if dockerNetwork.Ingress {
continue
}
for _, ingressNetwork := range g.options.IngressNetworks {
if dockerNetwork.Name == ingressNetwork {
ingressNetworks[dockerNetwork.ID] = true
}
}
}
} else {
containerID, err := g.dockerUtils.GetCurrentContainerID()
if err != nil {
return nil, err
}
logger.Info("Caddy ContainerID", zap.String("ID", containerID))
container, err := dockerClient.ContainerInspect(context.Background(), containerID)
if err != nil {
return nil, err
}
for _, network := range container.NetworkSettings.Networks {
networkInfo, err := dockerClient.NetworkInspect(context.Background(), network.NetworkID, types.NetworkInspectOptions{})
if err != nil {
return nil, err
}
if networkInfo.Ingress {
continue
}
ingressNetworks[network.NetworkID] = true
}
}
}
logger.Info("IngressNetworksMap", zap.String("ingres", fmt.Sprintf("%v", ingressNetworks)))
return ingressNetworks, nil
}
func (g *CaddyfileGenerator) filterLabels(labels map[string]string) map[string]string {
filteredLabels := map[string]string{}
for label, value := range labels {
if g.labelRegex.MatchString(label) {
filteredLabels[label] = value
}
}
return filteredLabels
}