-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcompactDaemon.js
More file actions
215 lines (202 loc) · 5.96 KB
/
compactDaemon.js
File metadata and controls
215 lines (202 loc) · 5.96 KB
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
const { promisify } = require("util");
const os = require("os");
const redis = require("redis");
const assert = require("assert");
const axios = require("axios").default;
const { wrappedRun } = require("./entryPoint");
const { CouchStorage } = require("./couchStorage");
const { COUCHDB_USER, COUCHDB_PASSWORD, COUCHDB_PROTO, PLAYER_SERVERS, REDIS_HOST, REDIS_PASSWORD } = require("./env");
async function withRetry(func, num = 5, retryInterval = 5000) {
// eslint-disable-next-line no-constant-condition
while (true) {
try {
return await func();
} catch (e) {
console.log(e);
if (num <= 0 || e.status === 403) {
throw e;
}
console.log(`Retrying (${num})`);
await new Promise((r) => setTimeout(r, Math.random() * retryInterval));
}
num--;
}
}
Promise.allSettled =
Promise.allSettled ||
((promises) =>
Promise.all(
promises.map((p) =>
p
.then((v) => ({
status: "fulfilled",
value: v,
}))
.catch((e) => ({
status: "rejected",
reason: e,
}))
)
));
async function compact({ dbName }) {
const m = /^p(\d+)_0*(\d+)$/.exec(dbName);
assert(m);
const [, mode] = m;
const URL_BASE = `${COUCHDB_PROTO}://${COUCHDB_USER}:${COUCHDB_PASSWORD}@${PLAYER_SERVERS[mode]}`;
const s = new CouchStorage({
uri: `${URL_BASE}/${dbName}`,
skipSetup: true,
});
await withRetry(() => axios.put(`${URL_BASE}/${dbName}/_revs_limit`, "1"));
await withRetry(() => s._db.compact({ interval: 200 }));
for (const view of ["basic", "extended"]) {
await withRetry(() => axios.post(`${URL_BASE}/${dbName}/_compact/${view}`, {}));
await new Promise((res) => setTimeout(res, 200));
while (
(await withRetry(() => axios.get(`${URL_BASE}/${dbName}/_design/${view}/_info`))).data.view_index
.compact_running !== false
) {
await new Promise((res) => setTimeout(res, 200));
}
}
s._db.close().catch(() => {});
await new Promise((res) => setTimeout(res, 500));
}
function getCPUInfo() {
const cpus = os.cpus();
let user = 0;
let nice = 0;
let sys = 0;
let idle = 0;
let irq = 0;
for (const cpu in cpus) {
if (!cpus.hasOwnProperty(cpu)) continue;
user += cpus[cpu].times.user;
nice += cpus[cpu].times.nice;
sys += cpus[cpu].times.sys;
irq += cpus[cpu].times.irq;
idle += cpus[cpu].times.idle;
}
const total = user + nice + sys + idle + irq;
return {
idle: idle,
total: total,
};
}
async function main() {
const redisClientRaw = redis.createClient({
host: REDIS_HOST,
password: REDIS_PASSWORD,
retry_unfulfilled_commands: true,
});
const redisClient = {
zrevrange: promisify(redisClientRaw.zrevrange.bind(redisClientRaw)),
zrem: promisify(redisClientRaw.zrem.bind(redisClientRaw)),
del: promisify(redisClientRaw.del.bind(redisClientRaw)),
sadd: promisify(redisClientRaw.sadd.bind(redisClientRaw)),
rename: promisify(redisClientRaw.rename.bind(redisClientRaw)),
};
const running = {};
function getNumRunning() {
return (
Object.keys(running)
.map((x) => running[x])
.reduce((a, b) => a + b, 0) || 0
);
}
let concurrency = 1;
let onComplete = null;
let cpuInfo = getCPUInfo();
let lastIdleCheck = new Date().getTime();
let downCooldown = 0;
let upCooldown = 0;
function doCompact(dbName, force) {
const m = /^p(\d+)_0*(\d+)$/.exec(dbName);
assert(m);
const [, mode] = m;
const server = PLAYER_SERVERS[mode];
if (running[server] && !force) {
return false;
}
running[server] = (running[server] || 0) + 1;
console.log(dbName);
Promise.all([
redisClient.zrem("compactQueue", dbName),
redisClient.sadd("compactIgnore", dbName),
compact({ dbName }),
])
.then(() => {
running[server]--;
if (!running[server]) {
delete running[server];
}
onComplete();
})
.catch((e) => {
console.error(e);
process.exit(1);
});
return true;
}
for (;;) {
const ts = new Date().getTime();
if (ts - lastIdleCheck >= 1000) {
const newCpuInfo = getCPUInfo();
const idlePercent = (newCpuInfo.idle - cpuInfo.idle) / (newCpuInfo.total - cpuInfo.total);
lastIdleCheck = ts;
cpuInfo = newCpuInfo;
if (upCooldown > 0) {
upCooldown--;
}
if (downCooldown > 0) {
downCooldown--;
}
if (idlePercent < 0.32 + concurrency * 0.08) {
if (concurrency > 1 && downCooldown <= 0) {
concurrency--;
downCooldown = 2;
upCooldown = 10;
console.log("Concurrency:", concurrency);
}
} else if (idlePercent > 0.8) {
if (concurrency < Math.min(Math.floor(idlePercent * 10) + 1, 7) && upCooldown <= 0) {
if (getNumRunning() < concurrency) {
setTimeout(() => onComplete(), 1100);
} else {
concurrency++;
upCooldown = 10;
downCooldown = 0;
console.log("Concurrency:", concurrency);
}
}
}
}
const items = await redisClient.zrevrange("compactQueue", 0, 100);
if (!items.length) {
await redisClient.rename("compactQueueAlt", "compactQueue").catch(() => {});
await redisClient.del("compactIgnore");
await new Promise((res) => setTimeout(res, 5000));
continue;
}
const droppedItems = [];
await new Promise((resolve) => {
onComplete = resolve;
while (getNumRunning() < concurrency && items.length) {
const dbName = items.shift();
if (!doCompact(dbName)) {
droppedItems.push(dbName);
continue;
}
}
assert(getNumRunning());
while (getNumRunning() < concurrency && droppedItems.length) {
const dbName = droppedItems.shift();
doCompact(dbName, true);
}
});
}
}
if (require.main === module) {
wrappedRun(main);
}
// vim: sw=2:ts=2:expandtab:fdm=syntax