artdaq_node_server  v1_00_09
 All Classes Namespaces Files Variables Pages
db_module.js
1 // db_module.js : Server-side bindings for DB Display module
2 // Author: Eric Flumerfelt, FNAL RSI
3 // Last Modified: October 30, 2015
4 //
5 
6 // Node.js framework "includes"
7 // ReSharper disable PossiblyUnassignedProperty
8 // ReSharper disable InconsistentNaming
9 var Emitter = require("events").EventEmitter;
10 var fs = require("fs");
11 var stream = require("stream");
12 var child_process = require("child_process");
13 var Utils = require("./Utils");
14 var Connector = require("./DBConnector");
15 var path_module = require("path");
16 var db = new Emitter();
17 // ReSharper restore InconsistentNaming
18 // ReSharper restore PossiblyUnassignedProperty
19 
20 var DefaultColumns = [
21  {
22  name: "name",
23  type: "string",
24  editable: false,
25  display: true
26  },
27  {
28  name: "value",
29  type: "string",
30  editable: true,
31  display: true
32  },
33  {
34  name: "annotation",
35  title: "User Comment",
36  type: "string",
37  editable: true,
38  display: true
39  },
40  {
41  name: "comment",
42  type: "comment",
43  editable: false,
44  display: false
45  },
46  {
47  name: "type",
48  type: "string",
49  editable: false,
50  display: false
51  },
52  {
53  name: "values",
54  type: "array",
55  editable: false,
56  display: false
57  }, {
58  name: "children",
59  type: "array",
60  editable: false,
61  display: false
62  }
63 ];
64 
65 var MakeDbConfig = function (configFile) {
66  var defaultConfig = {
67  dbprovider: "filesystem"
68  , configNameFilter: "*"
69  , baseDir: process.env.ARTDAQ_DATABASE_URI ? process.env["ARTDAQ_DATABASE_URI"] : ""
70  , mongoConfig: {
71  dbUser: "anonymous"
72  , dbHost: "localhost"
73  , dbPort: 27017
74  }
75  , instanceName: configFile.instanceName ? configFile.instanceName : "test_db"
76  };
77 
78  if (defaultConfig.baseDir.indexOf("filesystemdb://") === 0) {
79  console.log("Parsing filesystemdb URI: " + defaultConfig.baseDir);
80  defaultConfig.baseDir = defaultConfig.baseDir.replace("filesystemdb://", "").replace(/\/$/, "");
81  var tempArr = defaultConfig.baseDir.split('/');
82  defaultConfig.instanceName = tempArr.splice(-1);
83  defaultConfig.baseDir = tempArr.slice(0,-1).join('/');
84  } else if (defaultConfig.baseDir.indexOf("mongodb://") === 0) {
85  console.log("Parsing mongodb URI: " + defaultConfig.baseDir);
86  var matches = defaultConfig.baseDir.match(/mongodb:\/\/(?:([^@:]*)(?::([^@]*))?@)?([^:]*):([0-9]+)\/([^/]*)\/?/);
87  defaultConfig.baseDir = "";
88  defaultConfig.dbprovider = "mongo";
89  console.log(JSON.stringify(matches, null, 4));
90  defaultConfig.mongoConfig.dbUser = matches[1] ? matches[1] : "";
91  var pass = matches[2];
92  if (pass !== null && pass !== undefined) {
93  fs.writeFileSync(".dbpasswd", pass);
94  }
95  defaultConfig.mongoConfig.dbHost = matches[3];
96  defaultConfig.mongoConfig.dbPort = matches[4];
97  defaultConfig.instanceName = matches[5];
98  }
99 
100  if (defaultConfig.baseDir === "") {
101  defaultConfig.baseDir = process.env["ARTDAQ_DATABASE_DIR"];
102  }
103 
104  console.log("DBConfig: " + JSON.stringify(defaultConfig, null, 4));
105  return defaultConfig;
106 };
107 
108 function GetFileBase(configName, collection, entity) {
109  return path_module.join(configName, collection, entity + ".gui.json");
110 }
111 
112 function GetTempFilePath(configName, collection, entity, dirs) {
113  var filebase = GetFileBase(configName, collection, entity);
114 
115  if (!fs.existsSync(path_module.join(dirs.tmp, configName))) fs.mkdirSync(path_module.join(dirs.tmp, configName));
116  if (!fs.existsSync(path_module.join(dirs.tmp, configName, collection))) fs.mkdirSync(path_module.join(dirs.tmp, configName, collection));
117  return path_module.join(dirs.tmp, filebase);
118 }
119 
120 function GetFilePath(configName, collection, entity, dirs, dbOnly) {
121  var filebase = GetFileBase(configName, collection, entity);
122  console.log("GetFilePath: filebase is " + filebase + ", dirs: " + JSON.stringify(dirs, null, 4));
123  if (!dbOnly && fs.existsSync(path_module.join(dirs.tmp, filebase))) {
124  return path_module.join(dirs.tmp, filebase);
125  }
126 
127  if (!fs.existsSync(path_module.join(dirs.db, configName))) fs.mkdirSync(path_module.join(dirs.db, configName));
128  if (!fs.existsSync(path_module.join(dirs.db, configName, collection))) fs.mkdirSync(path_module.join(dirs.db, configName, collection));
129  return path_module.join(dirs.db, filebase);
130 }
131 
137 function LoadFile(fileInfo, dirs, dbConfig) {
138  console.log("LoadFile: fileInfo: " + JSON.stringify(fileInfo, null, 4) + ", dirs: " + JSON.stringify(dirs, null, 4) + ", dbConfig: " + JSON.stringify(dbConfig, null, 4));
139  var output = {
140  data: {}
141  , filePath: ""
142  , entity: ""
143  , collection: ""
144  , configName: ""
145  };
146 
147  output.entity = fileInfo.query.filter["entities.name"];
148  output.collection = fileInfo.query.collection;
149  output.configName = fileInfo.query.filter["configurations.name"];
150 
151  console.log("File info: " + JSON.stringify(fileInfo, null, 4));
152  output.filePath = GetFilePath(output.configName, output.collection, output.entity, dirs, true);
153 
154  if (!fs.existsSync(output.filePath)) {
155  console.log("Loading file from database");
156  output.data = Connector.RunLoadQuery(dbConfig, fileInfo.query);
157  console.log("Writing file " + output.filePath);
158  fs.writeFileSync(output.filePath, JSON.stringify(output.data, null, 4));
159  } else {
160  output.data = JSON.parse("" + fs.readFileSync(output.filePath));
161  }
162  console.log("File Data: " + JSON.stringify(output, null, 4));
163  console.log("Done Loading file");
164  return output;
165 }
166 
178 function FetchFile(fileInfo, dataFormat, dbdirectory, dbConfig) {
179  console.log("FetchFile: fileInfo: " + JSON.stringify(fileInfo, null, 4) + ", dataFormat: " + dataFormat + ", dbDirectory: " + dbdirectory);
180  var fileName = path_module.join(fileInfo.collection + "_" + fileInfo.name + "_" + fileInfo.version);
181  if (dataFormat === "fhicl") {
182  fileName += ".fcl";
183  } else if (dataFormat === "gui") {
184  fileName += ".gui.json";
185  } else {
186  fileName += ".json";
187  }
188  var filePath = path_module.join(dbdirectory, fileName);
189  var query = {
190  filter: {
191  "entities.name": fileInfo.name,
192  version: fileInfo.version
193  },
194  collection: fileInfo.collection,
195  configurable_entity: fileInfo.name,
196  dbprovider: dbConfig.dbprovider,
197  operation: "load",
198  dataformat: dataFormat
199  };
200  var fhiclData = Connector.RunLoadQuery(dbConfig, query, true);
201  fs.writeFileSync(filePath, JSON.stringify(fhiclData, null, 4));
202 
203  var stat = fs.statSync(filePath);
204  return { fileName: fileName, filePath: filePath, size: stat.size }
205 };
206 
207 function MakeColumns(rowIn, index, columns, columnGroups, group) {
208  //console.log("MakeColumns: rowIn: " + JSON.stringify(rowIn,null,4) + ", index: " + index + ", columns: " + JSON.stringify(columns,null,4) + ", columnGroups: " + JSON.stringify(columnGroups,null,4) + ", group: " + group);
209  var rowOut = {
210  children: []
211  };
212 
213  for (var p in rowIn) {
214  if (rowIn.hasOwnProperty(p)) {
215  var value = rowIn[p];
216  if (value !== Object(value) && Utils.ContainsName(columns, p, "name") < 0) {
217  columns.push({ name: p, type: "string", editable: true, display: true, columnGroup: group });
218  rowOut[p] = value;
219  } else if (value === Object(value)) {
220  var res;
221  if (Utils.ContainsName(columnGroups, p, "name") < 0) {
222  columnGroups.push({ name: "" + p, text: "" + p, parentGroup: group });
223  }
224  if (value.constructor === Array) {
225  for (var i in value) {
226  if (value.hasOwnProperty(i)) {
227  res = MakeColumns(value[i], index + "." + i, columns, columnGroups, p);
228  columns = res.columns;
229  columnGroups = res.columnGroups;
230  res.row.name = rowIn.name + "/" + p + "___" + i;
231  res.row.index = index + "." + i;
232  rowOut.children.push(res.row);
233  }
234  }
235  } else {
236  res = MakeColumns(value, index, columns, columnGroups, p);
237  columns = res.columns;
238  columnGroups = res.columnGroups;
239  for (var pp in res.row) {
240  if (res.row.hasOwnProperty(pp)) {
241  rowOut[pp] = res.row[pp];
242  }
243  }
244 
245  }
246  } else {
247  rowOut[p] = value;
248  }
249  }
250  }
251  if (rowOut.children.length === 0) delete rowOut.children;
252  else if (Utils.ContainsName(columns, "children", "name") < 0) { columns.push({ name: "children", type: "array", editable: false, display: false }); }
253 
254  return { row: rowOut, columns: columns, columnGroups: columnGroups };
255 }
256 
263 function ParseSequence(sequence, name) {
264  console.log("ParseSequence: sequence: " + JSON.stringify(sequence, null, 4) + ", name: " + name);
265  var children = [];
266  var hasTable = false;
267  var rows = [];
268  var columns = [];
269  var columnGroups = [];
270  columns.push({ name: "index", type: "number", editable: false, display: true, columnGroup: name });
271  columns.push({ name: "name", type: "string", editable: false, display: true, columnGroup: name });
272  //console.log("SEQUENCE BEFORE: " + JSON.stringify(sequence,null,4));
273  for (var i = 0; i < sequence.length; ++i) {
274  if (sequence[i] === Object(sequence[i])) {
275  // Is an Object or Array
276  if (sequence[i].constructor === Array) {
277  // Is an array
278  var arr = ParseSequence(sequence[i], name + "___" + i);
279  if (arr.children !== undefined && arr.children.length > 0) {
280  children.push({ name: name + "___" + i, children: arr.children });
281  rows.push({ index: i, name: name + "___" + i, children: arr.children });
282  if (Utils.ContainsName(columns, "children", "name") < 0) {
283  columns.push({ name: "children", type: "array", editable: false, display: false });
284  }
285  }
286  if (arr.rows !== undefined && arr.rows.length > 0) {
287  if (arr.hasTable) {
288  hasTable = true;
289  }
290  for (var r in arr.rows) {
291  if (arr.rows.hasOwnProperty(r)) {
292  rows.push(arr.rows[r]);
293  }
294  }
295  for (var c in arr.columns) {
296  if (arr.columns.hasOwnProperty(c) && Utils.ContainsName(columns, arr.columns[c].name, "name") < 0) {
297  columns.push(arr.columns[c]);
298  }
299  }
300  }
301  } else {
302  // We need to make a new table
303  hasTable = true;
304  console.log("Parsing as table: " + JSON.stringify(sequence[i], null, 4));
305  if (!sequence[i].hasOwnProperty("name") || sequence[i].name.length === 0) {
306  sequence[i].name = name + "___" + i;
307  }
308  if (Utils.ContainsName(columnGroups, name, "name") < 0) {
309  columnGroups.push({ name: "" + name, text: "" + name });
310  }
311  var res = MakeColumns(sequence[i], i, columns, columnGroups, name);
312  res.row.index = i;
313  rows.push(res.row);
314  columns = res.columns;
315  columnGroups = res.columnGroups;
316  }
317  } else {
318  var vname = name + "___" + i;
319  var value = sequence[i];
320  children.push({ name: vname, value: value });
321  rows.push({ index: i, name: vname, value: value });
322  if (Utils.ContainsName(columns, "value", "name") < 0) {
323  columns.push({ name: "value", type: "string", editable: true, display: true, columnGroup: name });
324  }
325  }
326  }
327  var comment = sequence.comment ? sequence.comment : " ";
328 
329  if (hasTable) {
330  var table = {
331  name: name
332  , comment: comment
333  , type: "table"
334  , isSequence: true
335  , table: {
336  rows: rows
337  , columns: columns
338  , columnGroups: columnGroups
339  }
340  };
341  console.log("\nParseSequence returning table: " + JSON.stringify(table, null, 4));
342  return table;
343  } else {
344  var output = { name: name, comment: comment, children: children };
345  console.log("\nParseSequence returning: " + JSON.stringify(output, null, 4));
346  return output;
347  }
348 };
349 
356 function ParseFhiclTable(table, sub) {
357  console.log("ParseFhiclTable: table: " + JSON.stringify(table, null, 4) + ", sub: " + sub);
358  var children = [];
359  var subtables = [];
360  var hasSubtables = false;
361  var comment = table.comment ? table.comment : " ";
362  //console.log("Table name is " + name);
363 
364  for (var e in table.children) {
365  if (table.children.hasOwnProperty(e)) {
366  var element = table.children[e];
367  if (element.type === "table" && element.isSequence) {
368  element.type = "sequence";
369  }
370  //console.log("Element: " + JSON.stringify(element,null,4));
371  switch (element.type) {
372  case "table":
373  //console.log("Parsing table " + e);
374  hasSubtables = true;
375  children.push(ParseFhiclTable(element, 1));
376  break;
377  case "sequence":
378  children.push(ParseSequence(element.children, element.name));
379  break;
380  case "number":
381  case "string":
382  case "bool":
383  children.push(element);
384  break;
385  default:
386  console.log("Unknown type " + element.type + " encountered!");
387  break;
388  }
389  }
390  }
391 
392  var obj = { name: table.name, hasSubtables: hasSubtables, children: children, subtables: subtables, type: "table", comment: comment, columns: DefaultColumns };
393  if (sub === 0 || sub === undefined) {
394  //console.log("Returning: " + JSON.stringify(obj,null,4));
395  }
396  return obj;
397 };
398 
399 function FindConfigs(configNameFilter, dbConfig) {
400  console.log("\nFindConfigs: Request for Named Configurations received");
401  var configsOutput = { Success: false, data: {}, configs: {} };
402  try {
403  var configs = Connector.RunGetConfigsQuery(dbConfig).search;
404  console.log("CONFIGS: " + JSON.stringify(configs));
405  for (var conf in configs) {
406  if (configs.hasOwnProperty(conf)) {
407  var config = configs[conf];
408  if (config.name.search(configNameFilter) >= 0) {
409  var prefix = config.name;
410  var configNumber = 0;
411  var matches = config.name.match(/(.*?)[_\-]*(\d*)$/);
412  if (matches) {
413  if(matches.length > 1) prefix = matches[1];
414  if(matches.length > 2) configNumber = parseInt(matches[2]);
415  }
416 
417  if (!configsOutput.data.hasOwnProperty(prefix)) {
418  configsOutput.data[prefix] = [];
419  }
420 
421  configsOutput.data[prefix].push({ version: configNumber, data: JSON.stringify(config.query), name: config.name });
422  configsOutput.configs[config.name] = config.query;
423  }
424  }
425  }
426  if (configsOutput.data.length === 0) {
427  configsOutput.data["null"] = {version: 0, data: ""};
428  configsOutput.configs[configNameFilter] = {};
429  }
430  configsOutput.Success = true;
431  } catch (e) {
432  console.log("Exception caught: " + e.name + ": " + e.message);
433  }
434  console.log("NamedConfigs complete");
435  return configsOutput;
436 }
437 
438 function FindInstances(dbConfig) {
439  console.log("FindInstances: Request for Database Instances received");
440  var instancesOutput = { Success: false, data: [] };
441  instancesOutput.data.push("<option value=\"NONE\">Create New Database Instance</option>");
442  try {
443  var dbs = Connector.RunListDatabasesQuery(dbConfig, {}).search;
444  for (var db in dbs) {
445  if (dbs.hasOwnProperty(db)) {
446  instancesOutput.data.push("<option value=" + dbs[db].name + ">" + dbs[db].name + "</option>");
447  }
448  }
449  instancesOutput.Success = true;
450  } catch (e) {
451  console.log("Exception caught: " + e.name + ": " + e.message);
452  }
453  console.log("FindInstances complete");
454  return instancesOutput;
455 }
456 
464 function LoadConfigFiles(configName, dirs, query, dbConfig) {
465  console.log("LoadConfigFiles: configName: " + configName + ", dirs: " + JSON.stringify(dirs, null, 4) + ", query: " + JSON.stringify(query, null, 4));
466  var retval = {
467  collections: {},
468  Success: false
469  };
470  var error = false;
471  var configFiles = [];
472  var e;
473  try {
474  configFiles = Connector.RunBuildFilterQuery(dbConfig, configName, query).search;
475  } catch (e) {
476  error = true;
477  console.log("Exception occurred: " + e.name + ": " + e.message);
478  }
479  if (!error) {
480  try {
481  for (var file in configFiles) {
482  if (configFiles.hasOwnProperty(file)) {
483  console.log("File info: " + JSON.stringify(configFiles[file], null, 4));
484  var entity = LoadFile(configFiles[file], dirs, dbConfig).entity;
485  var collection = configFiles[file].query.collection;
486  if (!retval.collections.hasOwnProperty(collection)) {
487  retval.collections[collection] = {
488  name: collection
489  , files: []
490  };
491  }
492  console.log("Adding " + entity + " to output list");
493  retval.collections[collection].files.push(entity);
494  }
495  }
496  retval.Success = true;
497  } catch (e) {
498  console.log("Exception occurred: " + e.name + ": " + e.message);
499  }
500  }
501  return retval;
502 };
503 
504 function SearchFile(fileData, searchKey) {
505  console.log("\nSearching for " + searchKey + " in object " + JSON.stringify(fileData, null, 4));
506  var retval = { name: fileData.name, children: [], columns: fileData.columns };
507  for (var ii in fileData.children) {
508  if (fileData.children.hasOwnProperty(ii)) {
509  var child = fileData.children[ii];
510  console.log("Key name: " + child.name);
511  if (child.name.indexOf(searchKey) !== -1) {
512  console.log("Adding child to output");
513  retval.children.push(child);
514  } else if (child.children && child.children.length > 0) {
515  console.log("Searching child's children");
516  var table = SearchFile(child, searchKey);
517  if (table.children.length > 0) {
518  retval.children.push(table);
519  }
520  }
521  }
522  }
523  console.log("\nSearchFile returning " + JSON.stringify(retval, null, 4));
524  return retval;
525 }
526 
527 function SearchConfigFiles(searchKey, configName, dirs, dbConfig) {
528  console.log("\nSearchConfigFiles: keySearch: " + searchKey + ", configName: " + configName + ", dirs: " + JSON.stringify(dirs, null, 4));
529  var retval = {
530  collectionsTemp: {},
531  collections: [],
532  columns: DefaultColumns,
533  Success: false
534  };
535  var error = false;
536  var configFiles = [];
537  var query = FindConfigs(configName, dbConfig).configs[configName];
538  var e;
539  try {
540  configFiles = Connector.RunBuildFilterQuery(dbConfig, configName, query).search;
541  } catch (e) {
542  error = true;
543  console.log("Exception occurred: " + e.name + ": " + e.message);
544  }
545  if (!error) {
546  try {
547  for (var file in configFiles) {
548  if (configFiles.hasOwnProperty(file)) {
549  console.log("File info: " + JSON.stringify(configFiles[file], null, 4));
550  var entity = LoadFile(configFiles[file], dirs, dbConfig).entity;
551  var collection = configFiles[file].query.collection;
552  if (!retval.collectionsTemp.hasOwnProperty(collection)) {
553  retval.collectionsTemp[collection] = {
554  name: collection
555  , children: []
556  };
557  }
558  var fileData = GetData(configName, collection, entity, dirs);
559  fileData.name = entity;
560  var fileMatches = SearchFile(fileData, searchKey);
561  if (fileMatches.children.length > 0) {
562  console.log("Adding " + entity + " to output list");
563  retval.collectionsTemp[collection].children.push(fileMatches);
564  }
565  }
566  }
567  retval.Success = true;
568  } catch (e) {
569  console.log("Exception occurred: " + e.name + ": " + e.message);
570  }
571  }
572 
573  for (var ii in retval.collectionsTemp) {
574  if (retval.collectionsTemp.hasOwnProperty(ii)) {
575  retval.collections.push(retval.collectionsTemp[ii]);
576  }
577  }
578  delete retval.collectionsTemp;
579  console.log("\nSearchConfigFiles returning: " + JSON.stringify(retval, null, 4));
580  return retval;
581 }
582 
595 function GetData(configName, collectionName, entity, dirs) {
596  console.log("GetData: configName: " + configName + ", collectionName: " + collectionName + ", entity: " + entity + ", dirs: " + JSON.stringify(dirs, null, 4));
597  var fileName = GetFilePath(configName, collectionName, entity, dirs, false);
598  if (!fs.existsSync(fileName)) { throw { name: "FileNotFoundException", message: "The requested file was not found" }; }
599  var jsonFile = JSON.parse("" + fs.readFileSync(fileName));
600  var jsonBase = ParseFhiclTable({ children: jsonFile.document.converted.guidata, name: entity }, 0);
601 
602  return jsonBase;
603 };
604 
605 function ReplaceByPath(obj, pathArr, data) {
606  console.log("Utils.ReplaceByPath: obj: " + JSON.stringify(obj, null, 4) + ", pathArr: " + JSON.stringify(pathArr, null, 4) + ", data: " + JSON.stringify(data, null, 4));
607  if (pathArr.length === 0 && (!obj.name || obj.name === data.name)) {
608  if (data.column && data.value) {
609  obj[data.column] = data.value;
610  } else if (data.type) {
611  for (var i in data) {
612  if (data.hasOwnProperty(i)) {
613  obj[i] = data[i];
614  }
615  }
616  }
617  return obj;
618  }
619 
620  var thisName = pathArr.shift();
621  var index = -1;
622  if (obj.type === "table") {
623  index = Utils.ContainsName(obj.children, thisName, "name");
624  } else if (obj.type === "sequence") {
625  index = thisName.slice(thisName.indexOf("___") + 3);
626  }
627  //console.log("Index is " + index + " (thisName: " + thisName + ", obj.children: " + JSON.stringify(obj.children,null,4) + ")");
628  obj.children[index] = ReplaceByPath(obj.children[index], pathArr, data);
629  return obj;
630 }
631 
641 function UpdateTable(configName, tablePath, data, dirs) {
642  console.log("UpdateTable: tablePath:" + tablePath + ", configName: " + configName + ", data: " + JSON.stringify(data, null, 4) + ", dirs: " + JSON.stringify(dirs, null, 4));
643  var tableArray = tablePath.split('/');
644  var collection = tableArray.shift();
645  var entity = tableArray.shift();
646  var fileName = GetFilePath(configName, collection, entity, dirs, false);
647  if (!fs.existsSync(fileName)) { throw { name: "FileNotFoundException", message: "The requested file: \"" + fileName + "\" was not found" }; }
648  console.log("Reading from file " + fileName);
649  var jsonFile = JSON.parse("" + fs.readFileSync(fileName));
650  var oldFile = jsonFile.document.converted.guidata;
651 
652  var curName = tableArray.shift();
653  var dataIdx = Utils.ContainsName(oldFile, curName, "name");
654  if (dataIdx < 0) {
655  console.log("Cannot find data in file!");
656  return;
657  }
658  var oldData = oldFile[dataIdx];
659  console.log("oldData: " + JSON.stringify(oldData, null, 4));
660  ReplaceByPath(oldData, tableArray, data);
661 
662  jsonFile.document.converted.guidata[dataIdx] = oldData;
663  console.log("After replacement, table data is " + JSON.stringify(oldData, null, 4));
664 
665  var filePath = GetTempFilePath(configName, collection, entity, dirs);
666  console.log("Writing to file " + filePath);
667  fs.writeFileSync(filePath, JSON.stringify(jsonFile, null, 4));
668 };
669 
677 function DiscardWorkingDir(dirs) {
678  console.log("Deleting existing trash dir (if any)");
679  Utils.ExecSync("rm -rf " + dirs.trash);
680  console.log("DiscardWorkingDir: Moving db temp to TRASH: mv " + dirs.db + " " + dirs.trash);
681  Utils.ExecSync("mv " + dirs.db + " " + dirs.trash);
682  console.log("DiscardWorkingDir: Moving temp files to TRASH: mv " + dirs.tmp + "/* " + dirs.trash);
683  Utils.ExecSync("mv " + dirs.tmp + "/* " + dirs.trash);
684  console.log("DiscardWorkingDir: Deleting temp directory: rmdir " + dirs.tmp);
685  Utils.ExecSync("rmdir " + dirs.tmp);
686 };
687 
700 function SaveConfigurationChanges(oldConfig, newConfig, files, dirs, dbConfig) {
701  console.log("Saving Configuration Changes, oldConfig: " + oldConfig + ", newConfig: " + newConfig + ", files: " + JSON.stringify(files, null, 4) + ", dirs: " + JSON.stringify(dirs, null, 4));
702  var fileInfo = Connector.RunBuildFilterQuery(dbConfig, oldConfig).search;
703 
704  var f;
705  for (f in files) {
706  if (files.hasOwnProperty(f)) {
707  console.log("Current file information: " + JSON.stringify(files[f], null, 4));
708  var collectionName = files[f].collection;
709  var entities = files[f].entities;
710  var entity = files[f].entity ? files[f].entity : "notprovided";
711  var version = files[f].version;
712  var thisFileInfo = {};
713  for (var fi in fileInfo) {
714  if (fileInfo.hasOwnProperty(fi)) {
715  if (collectionName === fileInfo[fi].query.collection && Utils.ContainsString(entities, fileInfo[fi].query.filter["entities.name"]) != -1) {
716  console.log("Matched file information to Document: " + JSON.stringify(fileInfo[fi], null, 4));
717  thisFileInfo = fileInfo[fi];
718  entity = fileInfo[fi].query.filter["entities.name"];
719  fileInfo.splice(fi, 1);
720  }
721  }
722  }
723 
724  console.log("Getting metadata from original and changed files");
725  var modified = GetFilePath(oldConfig, collectionName, entity, dirs, false);
726  var newMetadata = ReadFileMetadata(dirs, thisFileInfo, dbConfig);
727  //if (newMetadata.version === version) {
728  // version = Utils.Uniquify(version);
729  //}
730  newMetadata.version = version;
731  console.log("newMetadata: " + JSON.stringify(newMetadata, null, 4));
732 
733  console.log("Checking metadata version strings");
734  while (VersionExists(entity, collectionName, newMetadata.version, dbConfig)) {
735  console.log("Inferring new version string...");
736  version = Utils.Uniquify(newMetadata.version);
737  console.log("Changing version from " + newMetadata.version + " to " + version);
738  newMetadata.version = version;
739  console.log("OK");
740  }
741  console.log("Prepending changelog");
742  newMetadata.changelog = files[f].changelog + newMetadata.changelog;
743 
744  console.log("Writing new metadata to file");
745  if (WriteFileMetadata(newMetadata, modified)) {
746 
747  console.log("Running store query");
748  var data = "" + fs.readFileSync(modified);
749  console.log("Writing " + data + " to database");
750  Connector.RunStoreQuery(dbConfig, data, collectionName, newMetadata.version, entity, "gui", newConfig);
751  } else {
752  console.log("ERROR: Could not find file " + modified);
753  console.log("Please check if it exists.");
754  }
755  }
756  }
757 
758  console.log("Running addconfig for unmodified files: " + JSON.stringify(fileInfo, null, 4));
759  for (f in fileInfo) {
760  if (fileInfo.hasOwnProperty(f)) {
761  var unmodifiedVersion = GetVersion(fileInfo[f], dirs, dbConfig);
762  Connector.RunAddConfigQuery(dbConfig, newConfig, unmodifiedVersion, fileInfo[f].query.collection, { name: fileInfo[f].query.filter["entities.name"] });
763  }
764  }
765 
766  DiscardWorkingDir(dirs);
767 };
768 
777 function CreateNewConfiguration(configName, configData, dbConfig) {
778  console.log("CreateNewConfigration: configName: " + configName + ", configData: " + JSON.stringify(configData, null, 4));
779  var query = {
780  operations: []
781  };
782 
783  for (var d in configData.entities) {
784  if (configData.entities.hasOwnProperty(d)) {
785  var entityData = configData.entities[d];
786  console.log("Entity: " + JSON.stringify(entityData, null, 4));
787  query.operations.push({
788  filter: { version: entityData.version, "entities.name": entityData.name },
789  configuration: configName,
790  collection: entityData.collection,
791  dbprovider: dbConfig.dbprovider,
792  operation: "addconfig",
793  dataformat: "gui"
794  });
795  }
796  }
797 
798  Connector.RunNewConfigQuery(dbConfig, query);
799 };
800 
807 function ReadConfigurationMetadata(configName, dirs, dbConfig) {
808  console.log("ReadConfigurationMetadata: configname: " + configName + ", dirs: " + JSON.stringify(dirs, null, 4));
809 
810  var data = Connector.RunBuildFilterQuery(dbConfig, configName ).search;
811 
812  var metadata = {
813  entities: []
814  };
815  for (var i in data) {
816  if (data.hasOwnProperty(i)) {
817  console.log("Loading metadata: File " + i + " of " + data.length);
818  var version = GetVersion(data[i], dirs, dbConfig);
819  metadata.entities.push({ name: data[i].query.filter["entities.name"], file: data[i].name + "_" + data[i].query.collection, version: version, collection: data[i].query.collection });
820  }
821  }
822 
823  console.log("Returning entity list: " + JSON.stringify(metadata.entities, null, 4));
824  return metadata;
825 };
826 
835 function GetVersion(query, dirs, dbConfig) {
836  console.log("\"GetVersion\": {\"query\":" + JSON.stringify(query, null, 4) + ", \"dirs\":" + JSON.stringify(dirs, null, 4) + "},");
837  var ver = LoadFile(query, dirs, dbConfig).data.version;
838  console.log("GetVersion Returning " + ver);
839  return ver;
840 };
841 
851 function ReadFileMetadata(dirs, query, dbConfig) {
852  console.log("ReadFileMetadata: query=" + JSON.stringify(query, null, 4) + ", dirs=" + JSON.stringify(dirs, null, 4) + ", dbConfig: " + JSON.stringify(dbConfig, null, 4));
853 
854  var jsonFile = LoadFile(query, dirs, dbConfig).data;
855  if (jsonFile.changelog === undefined) {
856  jsonFile.changelog = "";
857  }
858  var metadata = {
859  entities: jsonFile.entities,
860  bookkeeping: jsonFile.bookkeeping,
861  aliases: jsonFile.aliases,
862  configurations: jsonFile.configurations,
863  version: jsonFile.version,
864  changelog: jsonFile.changelog,
865  collection: query.query.collection
866  };
867 
868  console.log("ReadFileMetadata returning: " + JSON.stringify(metadata, null, 4));
869  return metadata;
870 };
871 
878 function WriteFileMetadata(newMetadata, fileName) {
879  console.log("WriteFileMetadata: newMetadata=" + JSON.stringify(newMetadata, null, 4) + ", fileName=" + fileName);
880 
881  console.log("Reading file: " + fileName);
882  if (!fs.existsSync(fileName)) return false;
883  var jsonFile = JSON.parse("" + fs.readFileSync(fileName));
884 
885 
886  console.log("Setting fields: " + JSON.stringify(newMetadata, null, 4));
887  jsonFile.configurable_entity = newMetadata.configurable_entity;
888  jsonFile.bookkeeping = newMetadata.bookkeeping;
889  jsonFile.aliases = newMetadata.aliases;
890  jsonFile.configurations = newMetadata.configurations;
891  jsonFile.version = newMetadata.version;
892  jsonFile.document.converted.changelog = newMetadata.changelog;
893 
894  console.log("Writing data to file");
895  //console.log("fileName: " + fileName + ", metadata: " + JSON.stringify(jsonFile,null,4));
896  fs.writeFileSync(fileName, JSON.stringify(jsonFile, null, 4));
897 
898  return true;
899 };
900 
906 function GetDirectories(userId, dbConfig) {
907  console.log("GetDirectories: userid=" + userId);
908  if (dbConfig.baseDir === "" || !dbConfig.baseDir) {
909  dbConfig.baseDir = process.env["HOME"] + "/databases";
910  console.log("WARNING: ARTDAQ_DATABASE_DATADIR not set. Using $HOME/databases instead!!!");
911  }
912 
913  if (!fs.existsSync(dbConfig.baseDir)) {
914  console.log("ERROR: Base Directory " +dbConfig.baseDir + " doesn't exist!!!");
915  throw { name: "BaseDirectoryMissingException", message: "ERROR: Base Directory doesn't exist!!!" };
916  }
917  if (!fs.existsSync(path_module.join(dbConfig.baseDir, "db"))) {
918  fs.mkdirSync(path_module.join(dbConfig.baseDir, "db"));
919  }
920  if (!fs.existsSync(path_module.join(dbConfig.baseDir, "tmp"))) {
921  fs.mkdirSync(path_module.join(dbConfig.baseDir, "tmp"));
922  }
923  if (!fs.existsSync(path_module.join(dbConfig.baseDir, "TRASH"))) {
924  fs.mkdirSync(path_module.join(dbConfig.baseDir, "TRASH"));
925  }
926 
927  // ReSharper disable UseOfImplicitGlobalInFunctionScope
928  var db = path_module.join(dbConfig.baseDir, "db", userId);
929  var tmp = path_module.join(dbConfig.baseDir, "tmp", userId);
930  var trash = path_module.join(dbConfig.baseDir, "TRASH", userId);
931  // ReSharper restore UseOfImplicitGlobalInFunctionScope
932 
933  if (!fs.existsSync(db)) {
934  fs.mkdirSync(db);
935  }
936  if (!fs.existsSync(tmp)) {
937  fs.mkdirSync(tmp);
938  }
939  if (!fs.existsSync(trash)) {
940  fs.mkdirSync(trash);
941  }
942 
943  return { db: db, tmp: tmp, trash: trash };
944 };
945 
954 function VersionExists(entity, collection, version, dbConfig) {
955  console.log("\"VersionExists\": { version:\"" + version + "\", entity:" + JSON.stringify(entity, null, 4) + ", collection: \"" + collection + "\"}");
956  var query = {
957  filter: {
958  "entities.name": entity
959  },
960  collection: collection,
961  dbprovider: dbConfig.dbprovider,
962  operation: "findversions",
963  dataformat: "gui"
964  };
965  var vers = Connector.RunGetVersionsQuery(dbConfig, query).search;
966  console.log("Search returned: " + JSON.stringify(vers, null, 4));
967  return Utils.ContainsName(vers, version, "name") >= 0;
968 };
969 
974 function Lock() {
975  console.log("Lock");
976  if (fs.existsSync("/tmp/node_db_lockfile")) {
977  if (Date.now() - fs.fstatSync("/tmp/node_db_lockfile").ctime.getTime() > 1000) {
978  console.log("Stale Lockfile detected, deleting...");
979  return Unlock();
980  } else {
981  console.log("Lockfile detected and is not stale, aborting...");
982  }
983  return false;
984  }
985 
986  fs.writeFileSync("/tmp/node_db_lockfile", "locked");
987  return true;
988 }
989 
994 function Unlock() {
995  console.log("Unlock");
996  fs.unlinkSync("/tmp/node_db_lockfile");
997  return true;
998 }
999 
1000 // POST calls
1001 db.RO_GetData = function (post, dbConfig) {
1002  console.log("RO_GetData: " + JSON.stringify(post, null, 4));
1003  var ret = { Success: false, data: {} };
1004  try {
1005  ret.data = GetData(post.configName, post.collection, post.entity, GetDirectories(post.user, dbConfig));
1006  ret.Success = true;
1007  } catch (e) {
1008  console.log("Exception occurred: " + e.name + ": " + e.message);
1009  }
1010 
1011  console.log("GetData complete");
1012  return ret;
1013 };
1014 
1015 db.RW_MakeNewConfig = function (post, dbConfig) {
1016  if (Lock()) {
1017  console.log("RW_MakeNewConfig: Request to make new configuration received: " + JSON.stringify(post, null, 4));
1018  var res = { Success: false };
1019  var error = false;
1020  var e;
1021  try {
1022  var configs = Connector.RunGetConfigsQuery(dbConfig).search;
1023  if (!Utils.ValidatePath(post.name)) {
1024  console.log("Invalid name detected!");
1025  error = true;
1026  }
1027  while (Utils.ContainsName(configs, post.name, "name") >= 0) {
1028  console.log("Inferring new configuration name");
1029  post.name = Utils.Uniquify(post.name);
1030  }
1031  } catch (e) {
1032  error = true;
1033  console.log("Exception occurred: " + e.name + ": " + e.message);
1034  }
1035  if (!error) {
1036  console.log("Creating Configuration");
1037  try {
1038  CreateNewConfiguration(post.name, JSON.parse(post.config), dbConfig);
1039  res.Success = true;
1040  } catch (e) {
1041  console.log("Exception occurred: " + e.name + ": " + e.message);
1042  }
1043  }
1044  Unlock();
1045  console.log("MakeNewConfig completed");
1046  return res;
1047  }
1048  return null;
1049 };
1050 
1051 db.RW_saveConfig = function (post, dbConfig) {
1052  if (Lock()) {
1053  console.log("RW_saveConfig: Request to save configuration recieved. Configuration data: " + JSON.stringify(post, null, 4));
1054  var res = { Success: false };
1055  var error = false;
1056  var e;
1057  try {
1058  console.log("Checking for unique Configuration name");
1059  var configs = Connector.RunGetConfigsQuery(dbConfig).search;
1060  if (!Utils.ValidatePath(post.newConfigName) || Utils.ContainsName(configs, post.oldConfigName, "name") < 0) {
1061  console.log("Invalid name detected!");
1062  error = true;
1063  }
1064  while (Utils.ContainsName(configs, post.newConfigName, "name") >= 0) {
1065  console.log("Inferring new configuration name");
1066  post.newConfigName = Utils.Uniquify(post.newConfigName);
1067  }
1068  } catch (e) {
1069  error = true;
1070  console.log("Exception occurred: " + e.name + ": " + e.message);
1071  }
1072  if (!error) {
1073  try {
1074  console.log("Updating Configuration Files");
1075  SaveConfigurationChanges(post.oldConfigName, post.newConfigName, post.files, GetDirectories(post.user, dbConfig), dbConfig);
1076  res.Success = true;
1077  } catch (e) {
1078  console.log("Exception occurred: " + e.name + ": " + e.message);
1079  }
1080  }
1081  Unlock();
1082  console.log("SaveConfig completed");
1083  return res;
1084  }
1085  return null;
1086 };
1087 
1088 db.RO_LoadNamedConfig = function (post, dbConfig) {
1089  console.log("RO_LoadNamedConfig: Request for configuration with name \"" + post.configName + "\" and search query \"" + post.query + "\" received.");
1090  if (post.query.length === 0 || post.configName === "No Configurations Found") {
1091  return { collections: [] };
1092  }
1093  return LoadConfigFiles(post.configName, GetDirectories(post.user, dbConfig), JSON.parse(post.query), dbConfig);
1094 };
1095 
1096 db.RW_discardConfig = function (post, dbConfig) {
1097  console.log("RW_discardConfig: Discarding configuration with parameters: " + JSON.stringify(post, null, 4));
1098  DiscardWorkingDir(GetDirectories(post.user, dbConfig));
1099  return { Success: true };
1100 };
1101 
1102 db.RO_AddOrUpdate = function (post, dbConfig) {
1103  console.log("RO_AddOrUpdate: Request to update table row recieved: " + JSON.stringify(post, null, 4));
1104  UpdateTable(post.configName, post.table, post.row, GetDirectories(post.user, dbConfig));
1105  return { Success: true };
1106 }
1107 
1108 db.RO_Update = function (post, dbConfig) {
1109  console.log("RO_Update: Request to update table received: " + JSON.stringify(post, null, 4));
1110  UpdateTable(post.configName, post.table, { id: post.id, name: post.name, column: post.column, value: post.value }, GetDirectories(post.user, dbConfig));
1111  console.log("Update Complete");
1112  return { Success: true };
1113 };
1114 
1115 db.RO_LoadConfigMetadata = function (post, dbConfig) {
1116  console.log("RO_LoadConfigMetadata: Request to load configuration metadata received: " + JSON.stringify(post, null, 4) + ", dbConfig: " + JSON.stringify(dbConfig, null, 4));
1117  var ret = { Success: false, data: {} };
1118  try {
1119  ret.data = ReadConfigurationMetadata(post.configName, GetDirectories(post.user, dbConfig), dbConfig);
1120  ret.Success = true;
1121  } catch (e) {
1122  console.log("Exception caught: " + e.name + ": " + e.message);
1123  }
1124  console.log("LoadConfigMetadata complete");
1125  return ret;
1126 };
1127 
1128 db.RO_LoadFileMetadata = function (post, dbConfig) {
1129  console.log("RO_LoadFileMetadata: Request to load file metadata received: " + JSON.stringify(post, null, 4));
1130  var ret = { Success: false, data: {} };
1131  var dirs = GetDirectories(post.user, dbConfig);
1132  var error = false;
1133  var query = {};
1134  var e;
1135  try {
1136  var search = Connector.RunBuildFilterQuery(dbConfig, post.configName).search;
1137  for (var s in search) {
1138  if (search.hasOwnProperty(s)) {
1139  if (search[s].query.collection === post.collection && search[s].query.filter["entities.name"] === post.entity) {
1140  query = search[s];
1141  }
1142  }
1143  }
1144  } catch (e) {
1145  error = true;
1146  console.log("Exception caught: " + e.name + ": " + e.message);
1147  }
1148  if (!error) {
1149  try {
1150  ret.data = ReadFileMetadata(dirs, query, dbConfig);
1151  ret.Success = true;
1152  } catch (e) {
1153  console.log("Exception caught: " + e.name + ": " + e.message);
1154  }
1155  }
1156  console.log("LoadFileMetadata complete");
1157  return ret;
1158 };
1159 
1160 db.RW_UploadConfigurationFile = function (post, dbConfig) {
1161  if (Lock()) {
1162  console.log("RW_UploadConfigurationFile: Recieved request to upload file: " + JSON.stringify(post, null, 4));
1163  var e;
1164  var error = false;
1165  var ret = { Success: false };
1166  try {
1167  while (VersionExists(post.entity, post.collection, post.version, dbConfig)) {
1168  console.log("Version already exists. Running uniquifier...");
1169  post.version = Utils.Uniquify(post.version);
1170  }
1171  } catch (e) {
1172  error = true;
1173  console.log("Exception caught: " + e.name + ": " + e.message);
1174  }
1175 
1176  if (!error) {
1177  console.log("Running store fhicl query");
1178  try {
1179  Connector.RunStoreQuery(dbConfig, post.file, post.collection, post.version, post.entity, post.type);
1180  ret.Success = true;
1181  } catch (e) {
1182  console.log("Exception caught: " + e.name + ": " + e.message);
1183  }
1184  }
1185  Unlock();
1186  console.log("UploadConfigurationFile complete");
1187  return ret;
1188  }
1189  return null;
1190 };
1191 
1192 db.RO_DownloadConfigurationFile = function (post, dbConfig) {
1193  console.log("RO_DownloadConfigurationFile: Request to download file(s) received: " + JSON.stringify(post, null, 4));
1194  var dirs = GetDirectories(post.user, dbConfig);
1195  var configObj = JSON.parse(post.config);
1196  try {
1197  if (configObj.entities.length === 1) {
1198  console.log("Single file mode: Fetching file...");
1199  var fileInfo = FetchFile(configObj.entities[0], post.type, dirs.db, dbConfig);
1200 
1201  var fclhdrs = {
1202  'Content-Type': 'text/plain',
1203  'Content-Length': fileInfo.size,
1204  'Content-Disposition': 'attachment filename=' + fileInfo.fileName
1205  }
1206  console.log("Headers: " + JSON.stringify(fclhdrs, null, 4) + ", fileInfo: " + JSON.stringify(fileInfo, null, 4));
1207 
1208  var fclStream = fs.createReadStream(fileInfo.filePath);
1209  db.emit("stream", fclStream, fclhdrs, 200);
1210  } else if (configObj.entities.length > 1) {
1211  var args = ['cz'];
1212  for (var e in configObj.entities) {
1213  if (configObj.entities.hasOwnProperty(e)) {
1214  args.push(FetchFile(configObj.entities[e], post.type, dirs.db, dbConfig).fileName);
1215  }
1216  }
1217  var fileName = post.tarFileName + ".tar.gz";
1218  var tarhdrs = {
1219  'Content-Type': "application/x-gzip",
1220  'Content-Disposition': 'attachment filename=' + fileName
1221  }
1222 
1223  console.log("Spawning: tar " + args.join(" "));
1224  var tar = child_process.spawn("tar", args, { cwd: dirs.db, stdio: [0, 'pipe', 0] });
1225  db.emit("stream", tar.stdout, tarhdrs, 200);
1226 
1227  }
1228  } catch (err) {
1229  console.log("Exception caught: " + err.name + ": " + err.message);
1230 
1231  var s = new stream.Readable();
1232  s._read = function noop() { };
1233  s.push("ERROR");
1234  s.push(null);
1235 
1236  var errhdrs = {
1237  'Content-Type': 'text/plain'
1238  }
1239  db.emit("stream", s, errhdrs, 500);
1240  }
1241  //Stream emit has its own 'end', no return value necessary
1242 };
1243 
1244 db.RO_NamedConfigs = function (post, dbConfig) {
1245  console.log("RO_NamedConfigs: Request for Named Configurations received");
1246  var filter = "" + post.configFilter;
1247  return FindConfigs(filter, dbConfig);
1248 };
1249 
1250 db.RW_updateDbConfig = function (post, dbConfig) {
1251  console.log("RW_updateDbConfig: Request to update module configuration received: " + JSON.stringify(post, null, 4));
1252  var output = { Success: false };
1253  if (fs.existsSync(post.baseDir) && (post.dbprovider === "filesystem" || post.dbprovider === "mongo")) {
1254  if (dbConfig.baseDir !== post.baseDir) {
1255  dbConfig.baseDir = post.baseDir;
1256  db.emit("message", { name: "db", target: "baseDir", data: post.baseDir });
1257  }
1258  if (dbConfig.dbprovider !== post.dbprovider) {
1259  dbConfig.dbprovider = post.dbprovider;
1260  db.emit("message", { name: "db", target: "dbprovider", data: post.dbprovider });
1261  }
1262  if (dbConfig.instanceName !== post.instanceName) {
1263  dbConfig.instanceName = post.instanceName;
1264  db.emit("message", { name: "db", target: "instanceName", data: post.instanceName });
1265  }
1266  console.log("DB Config is now: " + JSON.stringify(dbConfig, null, 4));
1267  output.Success = true;
1268  }
1269  return output;
1270 }
1271 
1272 db.RO_SearchLoadedConfig = function (post, dbConfig) {
1273  console.log("RO_SearchLoadedConfig: Searching for keys containing name \"" + post.searchKey + "\" from configuration name \"" + post.configName + "\" received.");
1274  if (post.configName === "No Configurations Found") {
1275  return { Success: false, collections: [] };
1276  }
1277  return SearchConfigFiles(post.searchKey, post.configName, GetDirectories(post.user, dbConfig), dbConfig);
1278 }
1279 
1280 db.RW_makeNewDBInstance = function (post, dbConfig) {
1281  console.log("RW_makeNewDBInstance: Creating new database instance \"" + post.name + "\".");
1282  dbConfig.instanceName = post.name;
1283  return { Success: true };
1284 }
1285 
1286 db.RW_AddEntityToFile = function (post, dbConfig) {
1287  console.log("RW_AddEntityToFile: request to add entity name \"" + post.name + "\" to configuration file " + post.configName + "/" + post.collection + "/" + post.entity);
1288  return { Success: true };
1289 }
1290 
1291 // GET calls
1292 db.GET_EntitiesAndVersions = function (dbConfig) {
1293  console.log("GET_EntitiesAndVersions: Request for current Entities and Versions received");
1294  var output = {
1295  Success: false,
1296  collections: []
1297  };
1298  try {
1299  var entities = Connector.RunGetEntitiesQuery(dbConfig).search;
1300  console.log("Returned entities: " + JSON.stringify(entities, null, 4));
1301  for (var ent in entities) {
1302  if (entities.hasOwnProperty(ent)) {
1303  var entity = entities[ent];
1304  var versions = Connector.RunGetVersionsQuery(dbConfig, entity.query);
1305  if (Utils.ContainsName(output.collections, entity.query.collection, "name") < 0) {
1306  output.collections.push({ name: entity.query.collection, entities: [] });
1307  }
1308 
1309  var index = Utils.ContainsName(output.collections, entity.query.collection, "name");
1310 
1311  var entityObj = {
1312  collection: entity.query.collection,
1313  name: entity.name,
1314  versions: versions
1315  };
1316  output.collections[index].entities.push(entityObj);
1317  }
1318  }
1319  output.Success = true;
1320  } catch (e) {
1321  console.log("Exception caught: " + e.name + ": " + e.message);
1322  }
1323  console.log("EntitiesAndVersions complete");
1324  return output;
1325 };
1326 
1327 db.GET_getDbConfig = function (dbConfig) {
1328  console.log("GET_getDbConfig Request for Database Module Configuration received");
1329 
1330  var instances = FindInstances(dbConfig);
1331  var output = {
1332  Success: true,
1333  baseDir: dbConfig.baseDir,
1334  dbprovider: dbConfig.dbprovider,
1335  instanceName: dbConfig.instanceName,
1336  data: instances.data
1337  };
1338  return output;
1339 }
1340 
1341 // Serverbase Module definition
1342 db.MasterInitFunction = function (workerData, config) {
1343  var dbConfig = MakeDbConfig(config);
1344  workerData["db"] = dbConfig;
1345  GetDirectories("", dbConfig);
1346 };
1347 
1348 module.exports = function (moduleHolder) {
1349  moduleHolder["db"] = db;
1350 };