-
Notifications
You must be signed in to change notification settings - Fork 0
/
traefik.js
81 lines (68 loc) · 1.7 KB
/
traefik.js
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
const Docker = require('dockerode')
const isIp = require('is-ip')
let interval = null
const docker = new Docker()
let dockerError = false
async function update() {
const table = {}
let dockerHost = null
try {
dockerHost = await docker.getConfig().modem.host
} catch (err) {
if (!dockerError) {
console.error('❌ error docker connection:', err.message.replace('connect ENOENT ', ''))
dockerError = true
}
return table
}
if (dockerHost == null || !(isIp(dockerHost))) {
dockerHost = '127.0.0.1'
}
let containerList = []
try {
containerList = await docker.listContainers()
if (dockerError) {
console.log('🐋 docker connected:', dockerHost)
dockerError = false
}
} catch (err) {
if (!dockerError) {
console.error('❌ error docker connection:', err.message.replace('connect ENOENT ', ''))
dockerError = true
}
}
containerList.forEach(({ Labels }) => {
Object.keys(Labels)
.filter((label) => label.startsWith('traefik.http.routers') && label.endsWith('.rule'))
.forEach((label) => {
const rule = Labels[label]
const host = [...rule.matchAll(/Host\(`([\d\w.-]+?)`\)/g)]
host.forEach((h) => {
if (h[1]) table[h[1]] = dockerHost
})
})
})
return table
}
async function init(refreshTime = 10000) {
let table = await update()
interval = setInterval(async () => {
table = await update()
}, refreshTime)
const resolver = {
close() {
clearInterval(interval)
interval = null
},
resolve(name) {
if (table[name]) {
return table[name]
}
return null
},
}
return resolver
}
module.exports = {
init,
}