-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtask.worker.js
75 lines (71 loc) · 3.29 KB
/
task.worker.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
import { CronJob } from 'cron';
import * as fs from 'node:fs/promises';
import { $ } from 'bun';
import os from 'node:os';
import lib from './lib/lib.js'
self.onmessage = (event) => {
var db = lib.sqlite(os.homedir() + "/.brook.db", { wal: true })
async function task() {
var l = db.query(`select * from task`).all()
for (var i = 0; i < l.length; i++) {
var v = l[i]
try {
await fs.rm("/tmp/_", { recursive: true, force: true })
if (v.password) {
await $`sshexec -s '${v.server}' -u '${v.user}' -p '${v.password}' --download '${v.serverlog_path}' --to '/tmp/_' --timeout 600`
}
if (v.sshkey) {
await fs.writeFile('/tmp/sshkey', v.sshkey)
await $`sshexec -s '${v.server}' -u '${v.user}' -k /tmp/sshkey --download '${v.serverlog_path}' --to '/tmp/_' --timeout 600`
}
var m = {}
var s = (await fs.readFile("/tmp/_", { encoding: 'utf8' })).trim()
if (!s) {
continue
}
s.split("\n").map(v => JSON.parse(v)).forEach(v => {
if (v.bytes && v.user) {
if (!m[v.user]) m[v.user] = 0
m[v.user] += parseInt(v.bytes)
}
})
await db.transaction(async function() {
for (var user in m) {
db.query("update user set traffic_now=traffic_now+? where id=?").run(parseInt(m[user] / 1024 / 1024), user)
await lib.setImmediatePromise()
}
})
if (v.password) {
await $`sshexec -s '${v.server}' -u '${v.user}' -p '${v.password}' --download '${v.pid_path}' --to '/tmp/_' --timeout 60`
}
if (v.sshkey) {
await $`sshexec -s '${v.server}' -u '${v.user}' -k /tmp/sshkey --download '${v.pid_path}' --to '/tmp/_' --timeout 60`
}
var s = (await fs.readFile("/tmp/_", { encoding: 'utf8' })).trim()
if (v.user == "root") {
if (v.password) {
await $`sshexec -s '${v.server}' -u '${v.user}' -p '${v.password}' -c 'kill -USR1 ${s}' --timeout 60`
}
if (v.sshkey) {
await $`sshexec -s '${v.server}' -u '${v.user}' -k /tmp/sshkey -c 'kill -USR1 ${s}' --timeout 60`
}
}
if (v.user != "root") {
if (v.password) {
await $`sshexec -s '${v.server}' -u '${v.user}' -p '${v.password}' --sudo -c 'kill -USR1 ${s}' --timeout 60`
}
if (v.sshkey) {
await $`sshexec -s '${v.server}' -u '${v.user}' -k /tmp/sshkey --sudo -c 'kill -USR1 ${s}' --timeout 60`
}
}
} catch (e) {
console.log(new Date(), e)
}
}
setTimeout(task, 60 * 60 * 1000)
}
setTimeout(task, 60 * 60 * 1000)
new CronJob('0 0 0 1 * *', function() {
db.query(`update user set traffic_now=0`).run()
}, null, true, 'utc');
}