-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
190 lines (172 loc) · 4.92 KB
/
index.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
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
import createDebug from 'debug'
import writeAtomically from 'write-file-atomic'
import {writeFile as fsWriteFile} from 'node:fs/promises'
import debounce from 'lodash.debounce'
import {connectToEtcd} from './lib/etcd.js'
import {
mapEtcdEntriesToDbs,
mapEtcdEntriesToPgbouncerIni,
mapEtcdEntriesToUserlistTxt,
} from './lib/map.js'
import {GenerationError} from './lib/generation-error.js'
import {connectToPgbouncer} from './lib/reload-pg.js'
const LINUX_DEFAULT_CONFIG_BASE_DIR = '/etc/pgbouncer'
const debug = createDebug('pgbouncer-etcd-adapter')
const debugWatcher = createDebug('pgbouncer-etcd-adapter:watcher')
const writeFileAndLog = async (writeFile, file, data) => {
try {
await writeFile(file, data)
debug('successfully written', file)
} catch (err) {
debug('failed to write to', file, err)
throw err
}
}
const defaultOnGenerationFailed = ({error}) => {
console.error('failed to generate pgbouncer config:', error)
}
const defaultOnWatcherDisconnected = () => {
console.warn('pgbouncer etcd watcher disconnected')
}
const defaultOnWatcherConnected = () => {
console.info('pgbouncer etcd watcher (re)connected')
}
const defaultOnWatcherError = ({error}) => {
console.error('pgbouncer etcd watcher error:', error)
}
const generatePgbouncerConfigFromEtc = async (opt = {}) => {
opt = {
etcdPrefix: 'pgbouncer.',
writeAtomically: true,
watch: false,
// delay generation to handle bursts of etcd writes, 0 to disable
debounce: 200,
pathToPgbouncerIni: LINUX_DEFAULT_CONFIG_BASE_DIR + '/pgbouncer.ini',
pathToUserlistTxt: LINUX_DEFAULT_CONFIG_BASE_DIR + '/userlist.txt',
reloadPgbouncer: true,
onGenerationFailed: defaultOnGenerationFailed,
onConfigWritten: () => {},
onPgbouncerReloaded: () => {},
onWatcherDisconnected: defaultOnWatcherDisconnected,
onWatcherConnected: defaultOnWatcherConnected,
onWatcherError: defaultOnWatcherError,
...opt,
}
debug('options', opt)
const {
etcdPrefix,
pathToPgbouncerIni,
pathToUserlistTxt,
onGenerationFailed,
onConfigWritten,
onPgbouncerReloaded,
onWatcherDisconnected,
onWatcherConnected,
onWatcherError,
} = opt
const _etcd = await connectToEtcd()
const etcd = _etcd.namespace(etcdPrefix)
const {
reloadPgbouncerViaSql,
} = opt.reloadPgbouncer
? await connectToPgbouncer({
onPgbouncerReloaded,
})
: {
reloadPgbouncerViaSql: () => {},
}
let previousPgbouncerIni = null
let previousUserlistTxt = null
const generateConfig = async (reportGenFailed = true) => {
debug('regenerating config')
let etcdEntries = null
let dbs = null
let pgbouncerIni = null
let userlistTxt = null
try {
etcdEntries = await etcd.getAll().strings()
debug('etcd entries', etcdEntries)
dbs = mapEtcdEntriesToDbs(etcdEntries)
pgbouncerIni = mapEtcdEntriesToPgbouncerIni(etcdEntries)
userlistTxt = mapEtcdEntriesToUserlistTxt(etcdEntries)
} catch (err) {
if (reportGenFailed && (err instanceof GenerationError)) {
const ev = {
error: err,
etcdEntries,
}
onGenerationFailed(ev)
return;
}
throw err
}
const _write = opt.writeAtomically ? writeAtomically : fsWriteFile
const writeTasks = []
const pgbouncerIniHasChanged = pgbouncerIni !== previousPgbouncerIni
if (pgbouncerIniHasChanged) {
debug('pgbouncer.ini has changed')
writeTasks.push(writeFileAndLog(_write, pathToPgbouncerIni, pgbouncerIni))
}
const userlistTxtHasChanged = userlistTxt !== previousUserlistTxt
if (userlistTxtHasChanged) {
debug('userlist.txt has changed')
writeTasks.push(writeFileAndLog(_write, pathToUserlistTxt, userlistTxt))
}
await Promise.all(writeTasks)
const ev = {
pgbouncerIniWritten: pgbouncerIniHasChanged,
userlistTxtWritten: userlistTxtHasChanged,
}
onConfigWritten(ev)
await reloadPgbouncerViaSql(dbs)
}
await generateConfig(false)
if (opt.watch) {
// Note: `.prefix('')` is necessary for it to work.
const watcher = await etcd.watch().prefix('').create()
watcher.on('disconnected', () => {
debugWatcher('disconnected')
onWatcherDisconnected()
})
watcher.on('connected', (_) => {
debugWatcher('connected')
onWatcherConnected()
})
watcher.on('error', (err) => {
debugWatcher('error', err)
onWatcherError({
error: err,
})
})
await new Promise((_, reject) => {
const _gen = () => {
// todo: this doesn't take promise resolution settling time into account – use p-debounce instead?
generateConfig()
.catch(reject)
}
const gen = opt.debounce !== 0
? debounce(_gen, opt.debounce)
: _gen
watcher.on('put', ({key, value: val}) => {
if (debugWatcher.enabled) {
debugWatcher('watch: put', key.toString(), val.toString())
}
gen()
})
watcher.on('delete', ({key}) => {
if (debugWatcher.enabled) {
debugWatcher('watch: delete', key.toString())
}
gen()
})
})
}
const generator = {
generate: generateConfig,
}
return generator
}
export {
generatePgbouncerConfigFromEtc,
GenerationError,
}