-
Notifications
You must be signed in to change notification settings - Fork 178
/
generator.go
273 lines (242 loc) · 8.24 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
package generator
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"log"
"net"
"regexp"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"github.com/lucaslorentz/caddy-docker-proxy/plugin/v2/caddyfile"
"github.com/lucaslorentz/caddy-docker-proxy/plugin/v2/config"
"github.com/lucaslorentz/caddy-docker-proxy/plugin/v2/docker"
)
// 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
dockerClient docker.Client
dockerUtils docker.Utils
ingressNetworks map[string]bool
swarmIsAvailable bool
swarmIsAvailableTime time.Time
}
// CreateGenerator creates a new generator
func CreateGenerator(dockerClient 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),
dockerClient: dockerClient,
dockerUtils: dockerUtils,
}
}
// GenerateCaddyfile generates a caddy file config from docker metadata
func (g *CaddyfileGenerator) GenerateCaddyfile() ([]byte, string, []string) {
var caddyfileBuffer bytes.Buffer
var logsBuffer bytes.Buffer
if g.ingressNetworks == nil {
ingressNetworks, err := g.getIngressNetworks()
if err == nil {
g.ingressNetworks = ingressNetworks
} else {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
}
}
if time.Since(g.swarmIsAvailableTime) > swarmAvailabilityCacheInterval {
g.checkSwarmAvailability(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 {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
} else {
block, err := caddyfile.Unmarshal(dat)
if err != nil {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
} else {
caddyfileBlock.Merge(block)
}
}
} else {
logsBuffer.WriteString("[INFO] Skipping default Caddyfile because no path is set\n")
}
// Add Caddyfile from swarm configs
if g.swarmIsAvailable {
configs, err := g.dockerClient.ConfigList(context.Background(), types.ConfigListOptions{})
if err == nil {
for _, config := range configs {
if _, hasLabel := config.Spec.Labels[g.options.LabelPrefix]; hasLabel {
fullConfig, _, err := g.dockerClient.ConfigInspectWithRaw(context.Background(), config.ID)
if err != nil {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
} else {
block, err := caddyfile.Unmarshal(fullConfig.Spec.Data)
if err != nil {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
} else {
caddyfileBlock.Merge(block)
}
}
}
}
} else {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
}
} else {
logsBuffer.WriteString("[INFO] Skipping configs because swarm is not available\n")
}
// Add containers
containers, err := g.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, &logsBuffer, false)
if err != nil {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
} 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, &logsBuffer)
if err == nil {
caddyfileBlock.Merge(containerCaddyfile)
} else {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
}
}
} else {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
}
// Add services
if g.swarmIsAvailable {
services, err := g.dockerClient.ServiceList(context.Background(), types.ServiceListOptions{})
if err == nil {
for _, service := range services {
if _, isControlledServer := service.Spec.Labels[g.options.ControlledServersLabel]; isControlledServer {
ips, err := g.getServiceTasksIps(&service, &logsBuffer, false)
if err != nil {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
} else {
for _, ip := range ips {
if g.options.ControllerNetwork == nil || g.options.ControllerNetwork.Contains(net.ParseIP(ip)) {
controlledServers = append(controlledServers, ip)
}
}
}
}
serviceCaddyfile, err := g.getServiceCaddyfile(&service, &logsBuffer)
if err == nil {
caddyfileBlock.Merge(serviceCaddyfile)
} else {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
}
}
} else {
logsBuffer.WriteString(fmt.Sprintf("[ERROR] %v\n", err.Error()))
}
} else {
logsBuffer.WriteString("[INFO] Skipping services because swarm is not available\n")
}
// 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
logsBuffer.Write(processLogs)
}
if len(caddyfileContent) == 0 {
caddyfileContent = []byte("# Empty caddyfile")
}
if g.options.Mode&config.Server == config.Server {
controlledServers = append(controlledServers, "localhost")
}
return caddyfileContent, logsBuffer.String(), controlledServers
}
func (g *CaddyfileGenerator) checkSwarmAvailability(isFirstCheck bool) {
info, err := g.dockerClient.Info(context.Background())
if err == nil {
newSwarmIsAvailable := info.Swarm.LocalNodeState == swarm.LocalNodeStateActive
if isFirstCheck || newSwarmIsAvailable != g.swarmIsAvailable {
log.Printf("[INFO] Swarm is available: %v\n", newSwarmIsAvailable)
}
g.swarmIsAvailable = newSwarmIsAvailable
} else {
log.Printf("[ERROR] Swarm availability check failed: %v\n", err.Error())
g.swarmIsAvailable = false
}
}
func (g *CaddyfileGenerator) getIngressNetworks() (map[string]bool, error) {
ingressNetworks := map[string]bool{}
if len(g.options.IngressNetworks) > 0 {
networks, err := g.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
}
log.Printf("[INFO] Caddy ContainerID: %v\n", containerID)
container, err := g.dockerClient.ContainerInspect(context.Background(), containerID)
if err != nil {
return nil, err
}
for _, network := range container.NetworkSettings.Networks {
networkInfo, err := g.dockerClient.NetworkInspect(context.Background(), network.NetworkID, types.NetworkInspectOptions{})
if err != nil {
return nil, err
}
if networkInfo.Ingress {
continue
}
ingressNetworks[network.NetworkID] = true
}
}
log.Printf("[INFO] IngressNetworksMap: %v\n", 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
}