-
Notifications
You must be signed in to change notification settings - Fork 0
/
pm2-apps.js
executable file
·267 lines (223 loc) · 6.75 KB
/
pm2-apps.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
#!/usr/bin/env node
/*
TODO
====
1. add nodepath, then following are relative.
1. add v2 & v3 path to config.json
2. change config.pmapp to use runpath/puredir/appid
3. add runpath to config.json.
*/
function jsonParse(data){
try {return JSON.parse(data)}
catch(e){
console.error(e);
process.exit(2);
}
}
function jsonString(data){
try {return JSON.stringify(data,null,2)}
catch(e){return e}
}
var cl = console.log;
function cj(obj){if(obj) console.log(jsonString(obj))}
var pm2 = require('pm2');
var fs = require('fs');
var path = __dirname+'/json';
var readline = require('readline');
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
function write(siteid,data){
var jsdata = JSON.stringify({apps:[data.puremfg,data.vwlt]},null,2);
fs.writeFileSync('json/'+siteid+'.json',jsdata, 'utf8');
}
function connect(cb){
pm2.connect(false,function(err) {
if (err) {
pm2.disconnect();
cj({"error":true,"msg":err});
process.exit(2);
} else cb({"error":false,"msg":"success."})
})
}
function maxport(){
var mport=3000, sport=800;
var sites = module.exports.getAll();
for(var i in sites){
var site = sites[i];
if(site.appid=='puremfg') if(site.env.PORT > mport) mport=parseInt(site.env.PORT);
}
mport += 1; sport += (mport-3000);
return({'mport':mport,'sport':sport});
}
module.exports = {
dbconor:{
host: "localhost",
user:"root",
pwd:null,
engine: "MYSQL",
pooling: true,
acquireTimeout: 30,
},
defaults: {
max_restarts:3,
min_uptime: '1m',
node_args: ["--expose-gc"]
},
conf: require('./config.json'),
data: null,
add: function(){
var mex = module.exports;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('\nSite & Database Name : ',function(siteid){
if(!siteid) return rl.close();
else siteid = siteid.toLowerCase();
rl.question('MYDB ROOT Password : ',function(pwd){
mex.dbconor.pwd = pwd;
if(!pwd) return rl.close();
rl.question('Pure Version (2/3) : ',function(ver){
if(!(/2|3/).test(ver)) return rl.close();
mex.conf.vars.pmapp = mex.conf.vars['pmapp'+ver];
rl.question('Enter Site Args : ',function(args){
rl.close();
// Start
if(args){
args.split(/,| /).map(function(e){
var bits = e.split('=');
cl(bits);
mex.conf.vars[bits[0]] = bits[1];
})
}
var ports = maxport();
// append additional data to config.json.vars
mex.conf.vars['port'] = parseInt(ports.mport);
mex.conf.vars['vwport'] = parseInt(ports.sport);
mex.conf.vars['siteid'] = siteid;
mex.conf.vars['dbname'] = siteid.toUpperCase();
var jstr = JSON.stringify(mex.conf.apps,null,1);
// loop thru vars & replace tokens in conf.apps
for(var x in mex.conf.vars){
var val = mex.conf.vars[x];
if(typeof(val)=='string') val = val.replace(new RegExp('%nodedir%','g'),mex.conf.vars.nodedir);
jstr = jstr.replace(new RegExp('%'+x+'%','g'),val);
}
mex.data = JSON.parse(jstr);
write(siteid,mex.data);
cl('SUCCESS:',path+'/'+siteid+'.json file created.');
cl('\n========');
cl('TO START:','pm2 start '+path+'/'+siteid+'.json');
});
// default editable common list.
mex.conf.vars.grpid = siteid;
var comarg = []; ['tzoset','mode','grpid'].map(function(e){comarg.push(e+'='+mex.conf.vars[e])})
rl.write(comarg.join(','));
});
});
});
return '';
},
kill: function(){
connect(function(res) {
pm2.killDaemon(function(err) {
pm2.disconnect();
if(err) cj(err);
else cj({"error":false,"msg":"success."})
})
})
},
/* startup all enabled engines */
start: function(site){
connect(function(res) {
if(site) var sites = module.exports.getSite(site);
else var sites = module.exports.getAll();
pm2.start(sites,function(err,res) {
pm2.disconnect();
if (err) {
cj(err);
process.exit(2);
}
res.map(function(a){
cj(a.pm2_env.pm_id+' - '+a.pm2_env.name+' > '+a.pm2_env.status);
})
})
});
},
/* write file to path */
putFile: function(fname,data){
try {
fs.writeFileSync(path+'/'+fname, jsonString(jsonParse(data)), 'utf8');
return ({error:false});
} catch(err){
return ({error:true,msg:err});
}
},
/* retrieve a file by FILENAME, returns array.*/
getFile: function(file){
if(file.endsWith('.json')) {
var app = jsonParse(fs.readFileSync(path+'/'+file, 'utf8'));
if(app.apps && Array.isArray(app.apps)) return app.apps;
else return [app];
} else return [];
},
/* get by SITEID, returns array */
getSite: function(siteid){
var site=[]; module.exports.getAll().map(function(e){
if(e.env.SITEID==siteid) site.push(e);
});
return site;
},
/* get by GROUP, returns array */
getGroup: function(grpid){
var group=[]; module.exports.getAll().map(function(e){
if(e.env.GRPID==grpid) group.push(e);
});
return group;
},
/* get by HOSTNAME, returns object */
getHost: function(host){
return module.exports.getAll(true)[host] || {};
},
/* get all from json FOLDER, array or object */
getAll: function(asobj){
if(asobj) var apps={}; else var apps=[];
function add(a,file){
a._filename = file;
if(a.name != 'template' && !a.disabled) {
for(var key in module.exports.defaults){
a[key] = module.exports.defaults[key];
}
// if(a.env.DBSA) a.env.DBSA.host = "localhost";
if(asobj) apps[a.name]=a;
else apps.push(a);
}
}
fs.readdirSync(path).forEach(function(file) {
module.exports.getFile(file).map(function(e){
add(e,file);
})
});
return apps;
}
}
// compatability.
module.exports.getall = module.exports.getAll;
/*
DEBUG COMMAND LINE
getAll
getHost www.puremfg.net
getGroup oms
start
kill
*/
if(require.main === module){
var args = process.argv.slice(2);
var me = module.exports;
if(args.length && me[args[0]]){
if(args.length==2) cj(me[args[0]](args[1]));
else if(args.length==3) cj(me[args[0]](args[1],args[2]));
else cj(me[args[0]]());
} else console.log('Bad command:' + args[0]);
}