-
Notifications
You must be signed in to change notification settings - Fork 480
/
crontab.js
302 lines (255 loc) · 8.32 KB
/
crontab.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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*jshint esversion: 6*/
//load database
var Datastore = require('nedb');
var path = require("path");
exports.db_folder = process.env.CRON_DB_PATH === undefined ? path.join(__dirname, "crontabs") : process.env.CRON_DB_PATH;
console.log("Cron db path: " + exports.db_folder);
exports.log_folder = path.join(exports.db_folder, 'logs');
exports.env_file = path.join(exports.db_folder, 'env.db');
exports.crontab_db_file = path.join(exports.db_folder, 'crontab.db');
var db = new Datastore({ filename: exports.crontab_db_file});
var cronPath = "/tmp";
if(process.env.CRON_PATH !== undefined) {
console.log(`Path to crond files set using env variables ${process.env.CRON_PATH}`);
cronPath = process.env.CRON_PATH;
}
db.loadDatabase(function (err) {
if (err) throw err; // no hope, just terminate
});
var exec = require('child_process').exec;
var fs = require('fs');
var cron_parser = require("cron-parser");
var cronstrue = require('cronstrue/i18n');
var humanCronLocate = process.env.HUMANCRON ?? "en"
if (!fs.existsSync(exports.log_folder)){
fs.mkdirSync(exports.log_folder);
}
crontab = function(name, command, schedule, stopped, logging, mailing){
var data = {};
data.name = name;
data.command = command;
data.schedule = schedule;
if(stopped !== null) {
data.stopped = stopped;
}
data.timestamp = (new Date()).toString();
data.logging = logging;
if (!mailing)
mailing = {};
data.mailing = mailing;
return data;
};
exports.create_new = function(name, command, schedule, logging, mailing){
var tab = crontab(name, command, schedule, false, logging, mailing);
tab.created = new Date().valueOf();
tab.saved = false;
db.insert(tab);
};
exports.update = function(data){
var tab = crontab(data.name, data.command, data.schedule, null, data.logging, data.mailing);
tab.saved = false;
db.update({_id: data._id}, tab);
};
exports.status = function(_id, stopped){
db.update({_id: _id},{$set: {stopped: stopped, saved: false}});
};
exports.remove = function(_id){
db.remove({_id: _id}, {});
};
// Iterates through all the crontab entries in the db and calls the callback with the entries
exports.crontabs = function(callback){
db.find({}).sort({ created: -1 }).exec(function(err, docs){
for(var i=0; i<docs.length; i++){
if(docs[i].schedule == "@reboot")
docs[i].next = "Next Reboot";
else
try {
docs[i].human = cronstrue.toString(docs[i].schedule, { locale: humanCronLocate });
docs[i].next = cron_parser.parseExpression(docs[i].schedule).next().toString();
} catch(err) {
console.error(err);
docs[i].next = "invalid";
}
}
callback(docs);
});
};
exports.get_crontab = function(_id, callback) {
db.find({_id: _id}).exec(function(err, docs){
callback(docs[0]);
});
};
exports.runjob = function(_id) {
db.find({_id: _id}).exec(function(err, docs){
let res = docs[0];
let env_vars = exports.get_env()
let crontab_job_string_command = make_command(res)
crontab_job_string_command = add_env_vars(env_vars, crontab_job_string_command)
console.log("Running job")
console.log("ID: " + _id)
console.log("Original command: " + res.command)
console.log("Executed command: " + crontab_job_string_command)
exec(crontab_job_string_command, function(error, stdout, stderr){
if (error) {
console.log(error)
}
});
});
};
make_command = function(tab) {
var crontab_job_string = "";
let stderr = path.join(cronPath, tab._id + ".stderr");
let stdout = path.join(cronPath, tab._id + ".stdout");
let log_file = path.join(exports.log_folder, tab._id + ".log");
let log_file_stdout = path.join(exports.log_folder, tab._id + ".stdout.log");
var crontab_job_string_command = tab.command
if(crontab_job_string_command[crontab_job_string_command.length-1] != ";") { // add semicolon
crontab_job_string_command +=";";
}
crontab_job_string = crontab_job_string_command
crontab_job_string = "{ " + crontab_job_string + " }"
// write stdout to file
crontab_job_string = "(" + crontab_job_string + " | tee " + stdout + ")"
// write stderr to file
crontab_job_string = "(" + crontab_job_string + " 3>&1 1>&2 2>&3 | tee " + stderr + ") 3>&1 1>&2 2>&3"
crontab_job_string = "(" + crontab_job_string + ")"
if (tab.logging && tab.logging == "true") {
crontab_job_string += "; if test -f " + stderr +
"; then date >> \"" + log_file + "\"" +
"; cat " + stderr + " >> \"" + log_file + "\"" +
"; fi";
crontab_job_string += "; if test -f " + stdout +
"; then date >> \"" + log_file_stdout + "\"" +
"; cat " + stdout + " >> \"" + log_file_stdout + "\"" +
"; fi";
}
if (tab.hook) {
crontab_job_string += "; if test -f " + stdout +
"; then " + tab.hook + " < " + stdout +
"; fi";
}
if (tab.mailing && JSON.stringify(tab.mailing) != "{}"){
crontab_job_string += "; /usr/local/bin/node " + __dirname + "/bin/crontab-ui-mailer.js " + tab._id + " " + stdout + " " + stderr;
}
return crontab_job_string;
}
add_env_vars = function(env_vars, command) {
console.log("env vars");
console.log(env_vars)
if (env_vars)
return "(" + env_vars.replace(/\s*\n\s*/g,' ').trim() + "; (" + command + "))";
return command;
}
// Set actual crontab file from the db
exports.set_crontab = function(env_vars, callback) {
exports.crontabs( function(tabs){
var crontab_string = "";
if (env_vars) {
crontab_string += env_vars;
crontab_string += "\n";
}
tabs.forEach(function(tab){
if(!tab.stopped) {
crontab_string += tab.schedule
crontab_string += " "
crontab_string += make_command(tab)
crontab_string += "\n";
}
});
fs.writeFile(exports.env_file, env_vars, function(err) {
if (err) {
console.error(err);
callback(err);
}
// In docker we're running as the root user, so we need to write the file as root and not crontab
var fileName = process.env.CRON_IN_DOCKER !== undefined ? "root" : "crontab";
fs.writeFile(path.join(cronPath, fileName), crontab_string, function(err) {
if (err) {
console.error(err);
return callback(err);
}
exec("crontab " + path.join(cronPath, fileName), function(err) {
if (err) {
console.error(err);
return callback(err);
}
else {
db.update({},{$set: {saved: true}}, {multi: true});
callback();
}
});
});
});
});
};
exports.get_backup_names = function(){
var backups = [];
fs.readdirSync(exports.db_folder).forEach(function(file){
// file name begins with backup
if(file.indexOf("backup") === 0){
backups.push(file);
}
});
let backup_date = (backup_name) => {
let T = backup_name.split("backup")[1];
return new Date(T.substring(0, T.length-3)).valueOf();
}
backups.sort((a, b) => backup_date(b) - backup_date(a));
return backups;
};
exports.backup = (callback) => {
fs.copyFile(exports.crontab_db_file, path.join(exports.db_folder, 'backup ' + (new Date()).toString().replace("+", " ") + '.db'), (err) => {
if (err) {
console.error(err);
return callback(err);
}
callback();
});
};
exports.restore = function(db_name){
fs.createReadStream(path.join(exports.db_folder, db_name)).pipe(fs.createWriteStream(exports.crontab_db_file));
db.loadDatabase(); // reload the database
};
exports.reload_db = function(){
db.loadDatabase();
};
exports.get_env = function(){
if (fs.existsSync(exports.env_file)) {
return fs.readFileSync(exports.env_file , 'utf8').replace("\n", "\n");
}
return "";
};
exports.import_crontab = function(){
exec("crontab -l", function(error, stdout, stderr){
var lines = stdout.split("\n");
var namePrefix = new Date().getTime();
lines.forEach(function(line, index){
line = line.replace(/\t+/g, ' ');
var regex = /^((\@[a-zA-Z]+\s+)|(([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)\s+))/;
var command = line.replace(regex, '').trim();
var schedule = line.replace(command, '').trim();
var is_valid = false;
try { is_valid = cron_parser.parseString(line).expressions.length > 0; } catch (e){}
if(command && schedule && is_valid){
var name = namePrefix + '_' + index;
db.findOne({ command: command, schedule: schedule }, function(err, doc) {
if(err) {
throw err;
}
if(!doc){
exports.create_new(name, command, schedule, null);
}
else{
doc.command = command;
doc.schedule = schedule;
exports.update(doc);
}
});
}
});
});
};
exports.autosave_crontab = function(callback) {
let env_vars = exports.get_env();
exports.set_crontab(env_vars, callback);
};