[TIC-Web] Apply generic resource pooling
[archive/20170607/tools/tic.git] / controller / dbquery.js
1 'use strict';
2
3 var mariaSql = require('mariasql');
4 var JL = require('jsnlog').JL;
5 var logger = JL('dbquery.js');
6 var _ = require('lodash');
7
8 // var sequelize = require('./dbpool');
9 var dbpool = require('./dbpool');
10
11 var pool = new dbpool({});
12 // function fnCallback() {};
13 // setInterval(function () {
14 //     pool.query('show tables', {});
15 //     console.log(process.memoryUsage());
16 // }, 1000);
17
18 process.on('exit', function () {
19     pool.drain(function () {
20         pool.clear();
21     });
22 });
23
24 /**
25  * Client
26  */
27 var mariaSqlClient;
28
29 var NO_DATA = 0;
30
31 /**
32  * mariadb
33  */
34 var mariadb = mariadb || {};
35
36 mariadb.queries = {
37     'addJob': [
38         'insert into tic_job ',
39         '(job_status, job_deleted, job_hasksfile, job_updater, job_uptime, job_register, job_regtime) ',
40         'values ("READY", false, false, "tic", now(), "tic", now());'
41     ],
42     'getJobById': [
43         'select tic_job.job_id job_id, ',
44             'tic_job.job_status job_status, ',
45             'tic_job.job_image_id job_image_id, ',
46             'tic_image.image_name job_image_name, ',
47             'tic_image.image_size job_image_size, ',
48             'tic_job.job_hasksfile job_hasksfile, ',
49             'tic_job.job_uptime job_uptime ',
50         'from tic_job ',
51         'left join tic_image on tic_job.job_image_id = tic_image.image_id ',
52         'where tic_job.job_deleted = false ',
53         'and job_id = <%= strJobId %>;'
54     ],
55     'getJobsTotalCount': [
56         'select count(job_id) as total_count ',
57         'from tic_job ',
58         'where job_deleted = false;'
59     ],
60     'getJobsAllList': [
61         'select tic_job.job_id job_id, ',
62             'tic_job.job_status job_status, ',
63             'tic_job.job_image_id job_image_id, ',
64             'tic_image.image_name job_image_name, ',
65             'tic_image.image_size job_image_size, ',
66             'tic_job.job_hasksfile job_hasksfile, ',
67             'tic_job.job_ks job_ks, ',
68             'tic_job.job_arch job_arch, ',
69             'tic_job.job_uptime job_uptime ',
70         'from tic_job ',
71         'left join tic_image on tic_job.job_image_id = tic_image.image_id ',
72         'where tic_job.job_deleted = false ',
73         'order by job_id desc ',
74         'limit <%= startNum %> , 10;'
75     ],
76     'getImagesAllList': [
77         'select tic_job.job_image_id image_id, ',
78             'tic_job.job_id image_job_id, ',
79             'tic_image.image_name image_name, ',
80             'tic_image.image_size image_size, ',
81             'tic_job.job_hasksfile image_hasksfile, ',
82             'tic_job.job_ks image_ks, ',
83             'tic_job.job_arch image_arch, ',
84             'tic_job.job_status image_status, ',
85             'tic_job.job_uptime image_uptime ',
86         'from tic_job inner join tic_image ',
87         'where tic_job.job_image_id = tic_image.image_id ',
88         'and tic_job.job_deleted = false ',
89         'order by tic_job.job_id desc ',
90         'limit <%= startNum %> , 10;'
91     ],
92     'getImagesTotalCount': [
93         'select count(image_id) as total_count ',
94         'from tic_image;',
95     ],
96     'addImage': [
97         'insert into tic_image ',
98         '(',
99             'image_type, ',
100             'image_name, ',
101             'image_size',
102         ') ',
103         'values (',
104             '"<%= imageType %>", ',
105             '"<%= imageName %>", ',
106             '"<%= imageSize %>"',
107         ');'
108     ],
109     'getUser': [
110         'select user_email, user_group ',
111         'from tic_user ',
112         'where user_email = "<%= userEmail %>" and user_password = "<%= userPassword %>" ',
113         'limit 1;'
114     ],
115     'hasUser': [
116         'select count(user_id) as count ',
117         'from tic_user ',
118         'where user_email = "<%= userEmail %>";'
119     ]
120 };
121
122 mariadb.doQuery = function doQuery(queryString) {
123     return pool.query(queryString, []);
124 };
125
126 /**
127  * JOBS
128  */
129 /**
130  * Edit the Job By Id
131  */
132 mariadb.editJob = function editJob(req, res) {
133     var queryString, strJobId, reqParam,
134     job_status, job_deleted, job_hasksfile, job_image_id, job_ks, job_arch;
135
136     function onSuccess(rows) {
137         logger.info('editJob.success');
138         res.json(rows.result);
139     }
140
141     strJobId = req.params.id;
142     reqParam = req.body;
143     job_status = reqParam.job_status;
144     job_deleted = reqParam.job_deleted;
145     job_hasksfile = reqParam.job_hasksfile;
146     job_image_id = reqParam.job_image_id;
147     job_ks = reqParam.job_ks;
148     job_arch = reqParam.job_arch;
149
150     queryString = 'update tic_job set';
151     if (job_image_id) {
152         queryString += ' job_image_id = "' + job_image_id + '",';
153     }
154     if (job_status) {
155         queryString += ' job_status = "' + job_status + '",';
156     }
157     if (job_deleted) {
158         queryString += ' job_deleted = ' + job_deleted + ',';
159     }
160     if (job_hasksfile) {
161         queryString += ' job_hasksfile = ' + job_hasksfile + ',';
162     }
163     if (job_ks) {
164         queryString += ' job_ks = "' + job_ks + '",';
165     }
166     if (job_arch) {
167         queryString += ' job_arch = "' + job_arch + '",';
168     }
169     queryString += ' job_updater = "tic",';
170     queryString += ' job_uptime = now()';
171     queryString += ' where job_id = ' + strJobId + ';';
172
173     logger.info('editJob: query = ' + queryString);
174
175     // call
176     this.doQuery(queryString).then(onSuccess);
177 };
178
179 /**
180  * Add The New Job
181  */
182 mariadb.addJob = function addJob(req, res) {
183     var queryString;
184
185     function onSuccess(rows) {
186         logger.info('addJob.success: {job_id: ' + rows.result.info.insertId + '}');
187         res.json({
188             job_id: rows.result.info.insertId
189         });
190     }
191
192     queryString = _.join(this.queries['addJob'], '');
193
194     logger.info('addJob: query = ' + queryString);
195
196     // call
197     this.doQuery(queryString).then(onSuccess);
198 };
199
200 /**
201  * Get The Job By ID
202  */
203 mariadb.getJobById = function getJobById(req, res) {
204     var queryString, strJobId;
205
206     function onSuccess(rows) {
207         res.json(rows.result);
208     }
209
210     strJobId = req.params.id;
211
212     queryString = _.template(_.join(this.queries['getJobById'], ''))({
213         strJobId: strJobId
214     });
215
216     logger.info('getJobById: query = ' + queryString);
217
218     // call
219     this.doQuery(queryString).then(onSuccess);
220 };
221
222 /**
223  * Get Total Count of Job
224  */
225 mariadb.getJobsTotalCount = function getJobsTotalCount(req, res) {
226     var queryString;
227
228     function onSuccess(rows) {
229         res.json(rows.result);
230     }
231
232     queryString = _.join(this.queries['getJobsTotalCount'], '');
233
234     logger.info('getJobsTotalCount: query = ' + queryString);
235
236     // call
237     this.doQuery(queryString).then(onSuccess);
238 };
239
240 /**
241  * Get All Jobs
242  */
243 mariadb.getJobsAllList = function getJobsAllList(req, res) {
244     var queryString, reqParam, pageNum, startNum;
245
246     function onSuccess(rows) {
247         res.json(rows.result);
248     }
249
250     // strNum
251     reqParam = req.body;
252     pageNum = reqParam.pageNum;
253     startNum = (pageNum - 1) * 10;
254
255     queryString = _.template(_.join(this.queries['getJobsAllList'], ''))({
256         startNum: startNum
257     });
258
259     logger.info('getJobsAllList: query = ' + queryString);
260
261     // call
262     this.doQuery(queryString).then(onSuccess);
263 };
264
265
266 /**
267  * IAMGES
268  */
269
270 /**
271  * Get All Images
272  */
273 mariadb.getImagesAllList = function getImagesAllList(req, res) {
274     var queryString, reqParam, pageNum, startNum;
275
276     function onSuccess(rows) {
277         res.json(rows.result);
278     }
279
280     // strNum
281     reqParam = req.body;
282     pageNum = reqParam.pageNum;
283     startNum = (pageNum - 1) * 10;
284
285     queryString = _.template(_.join(this.queries['getImagesAllList'], ''))({
286         startNum: startNum
287     });
288
289     logger.info('getImagesAllList: query = ' + queryString);
290
291     // call
292     this.doQuery(queryString).then(onSuccess);
293 };
294
295 /**
296  * Get Total Count of Job
297  */
298 mariadb.getImagesTotalCount = function getImagesTotalCount(req, res) {
299     var queryString;
300
301     function onSuccess(rows) {
302         res.json(rows.result);
303     }
304
305     queryString = _.join(this.queries['getImagesTotalCount'], '');
306
307     logger.info('getImagesTotalCount: query = ' + queryString);
308
309     // call
310     this.doQuery(queryString).then(onSuccess);
311     
312     
313 };
314
315 /**
316  * Add The New Image
317  */
318 mariadb.addImage = function addImage (req, res) {
319     var queryString, paramObj;
320
321     function onSuccess(rows) {
322         var result = rows.result;
323         logger.info('addJob: result = {image_id: ' + result.info.insertId + '}');
324         res.json({
325             image_id: result.info.insertId
326         });
327     }
328
329     paramObj = req.body;
330
331     queryString = _.template(_.join(this.queries['addImage'], ''))({
332         imageType: paramObj.image_type,
333         imageName: paramObj.image_name,
334         imageSize: paramObj.image_size
335     });
336
337     logger.info('addJob: query = ' + queryString);
338
339     // call
340     this.doQuery(queryString).then(onSuccess);
341 };
342
343
344 mariadb.editImage = function editImage(req, res) {
345     var queryString, strJobId, reqParam,
346     job_status, job_deleted, job_hasksfile, job_image_id;
347
348     function onSuccess(rows) {
349         logger.info('editJob.success');
350         res.json(rows.result);
351     }
352
353     strJobId = req.params.id;
354     reqParam = req.body;
355     job_status = reqParam.job_status;
356     job_deleted = reqParam.job_deleted;
357     job_hasksfile = reqParam.job_hasksfile;
358     job_image_id = reqParam.job_image_id;
359
360     queryString = 'update tic_job set';
361     if (job_image_id) {
362         queryString += ' job_image_id = "' + job_image_id + '",';
363     }
364     if (job_status) {
365         queryString += ' job_status = "' + job_status + '",';
366     }
367     if (job_deleted) {
368         queryString += ' job_deleted = ' + job_deleted + ',';
369     }
370     if (job_hasksfile) {
371         queryString += ' job_hasksfile = ' + job_hasksfile + ',';
372     }
373     queryString += ' job_updater = "tic",';
374     queryString += ' job_uptime = now()';
375     queryString += ' where job_id = ' + strJobId + ';';
376
377     logger.info('editJob: query = ' + queryString);
378
379     // call
380     this.doQuery(queryString).then(onSuccess);
381 };
382
383
384 /**
385  * User
386  */
387
388 /**
389  * @method getUser
390  * @param json object { email, password }
391  * @desc get user information
392  */
393 mariadb.getUser = function getUser(query, success, error) {
394     function onSuccess(rows) {
395         var resultObj = {
396             data: null
397         };
398         if (rows && rows.result && rows.result.length !== NO_DATA) {
399             resultObj.data = rows.result[0];
400         }
401         success(resultObj);
402     }
403
404     var queryString = _.template(_.join(this.queries['getUser'], ''))({
405         userEmail: query.email,
406         userPassword: query.password
407     });
408
409     logger.info('getUser: query = ' + queryString);
410
411     // call
412     this.doQuery(queryString).then(onSuccess);
413 };
414
415 /**
416  * @method hasUser
417  * @param json object { email }
418  * @desc user check
419  */
420 mariadb.hasUser = function hasUser(query, success, error) {
421     function onSuccess(err, rows) {
422         if (err) {
423             logger.error(err);
424             error(error);
425         } else {
426             success(rows);
427         }
428     }
429
430     var queryString = _.template(_.join(this.queries['hasUser'], ''))({
431         userEmail: query.email
432     });
433
434     logger.info('hasUser: query = ' + queryString);
435
436     // call
437     this.doQuery(queryString).then(onSuccess);
438 };
439
440 /**
441  * DB
442  */
443 /**
444  * Connect
445  */
446 mariadb.connectToClient = function connectToClient() {
447     return new Promise(function (resolve, reject) {
448         // connect
449         mariaSqlClient.connect(function (err) {
450             if (err) {
451                 logger.error('connection error');
452                 logger.error(err);
453                 throw err;
454             }
455             logger.info('connection success');
456         });
457     });
458 };
459
460 /**
461  * Create the Client
462  */
463 mariadb.createClient = function createClient() {
464     return new Promise(function (resolve, reject) {
465         logger.info('create client');
466
467         var mariaSqlConfig;
468
469         // config
470         mariaSqlConfig = {
471             host: '127.0.0.1',
472             user: 'tic',
473             password: 'tic',
474             db: 'pdk',
475             timeout: 60000,
476             trace: true
477         }
478
479         // create
480         mariaSqlClient = new mariaSql(mariaSqlConfig);
481         resolve();
482     });
483 };
484
485 /**
486  * Initialize
487  */
488 mariadb.init = function init() {
489     logger.info('init');
490
491     var self = this;
492     self.createClient()
493     .then(self.connectToClient);
494 };
495
496 // mariadb.init();
497
498 module.exports = mariadb;