00001
00002
00003
00004
00005
00006
00007
00008
00009 var Emitter = require("events").EventEmitter;
00010 var fs = require("fs");
00011 var stream = require("stream");
00012 var child_process = require("child_process");
00013 var Utils = require("./Utils");
00014 var Connector = require("./DBConnector");
00015 var path_module = require("path");
00016 var db = new Emitter();
00017
00018
00019
00020 var DefaultColumns = [
00021 {
00022 name: "name",
00023 type: "string",
00024 editable: false,
00025 display: true
00026 },
00027 {
00028 name: "value",
00029 type: "string",
00030 editable: true,
00031 display: true
00032 },
00033 {
00034 name: "annotation",
00035 title: "User Comment",
00036 type: "string",
00037 editable: true,
00038 display: true
00039 },
00040 {
00041 name: "comment",
00042 type: "comment",
00043 editable: false,
00044 display: false
00045 },
00046 {
00047 name: "type",
00048 type: "string",
00049 editable: false,
00050 display: false
00051 },
00052 {
00053 name: "values",
00054 type: "array",
00055 editable: false,
00056 display: false
00057 }, {
00058 name: "children",
00059 type: "array",
00060 editable: false,
00061 display: false
00062 }
00063 ];
00064
00065 var MakeDbConfig = function (configFile) {
00066 var defaultConfig = {
00067 dbprovider: "filesystem"
00068 , configNameFilter: "*"
00069 , baseDir: process.env.ARTDAQ_DATABASE_URI ? process.env["ARTDAQ_DATABASE_URI"] : ""
00070 , mongoConfig: {
00071 dbUser: "anonymous"
00072 , dbHost: "localhost"
00073 , dbPort: 27017
00074 }
00075 , instanceName: configFile.instanceName ? configFile.instanceName : "test_db"
00076 };
00077
00078 if (defaultConfig.baseDir.indexOf("filesystemdb://") === 0) {
00079 console.log("Parsing filesystemdb URI: " + defaultConfig.baseDir);
00080 defaultConfig.baseDir = defaultConfig.baseDir.replace("filesystemdb://", "").replace(/\/$/, "");
00081 var tempArr = defaultConfig.baseDir.split('/');
00082 defaultConfig.instanceName = tempArr.splice(-1);
00083 defaultConfig.baseDir = tempArr.slice(0,-1).join('/');
00084 } else if (defaultConfig.baseDir.indexOf("mongodb://") === 0) {
00085 console.log("Parsing mongodb URI: " + defaultConfig.baseDir);
00086 var matches = defaultConfig.baseDir.match(/mongodb:\/\/(?:([^@:]*)(?::([^@]*))?@)?([^:]*):([0-9]+)\/([^/]*)\/?/);
00087 defaultConfig.baseDir = "";
00088 defaultConfig.dbprovider = "mongo";
00089 console.log(JSON.stringify(matches, null, 4));
00090 defaultConfig.mongoConfig.dbUser = matches[1] ? matches[1] : "";
00091 var pass = matches[2];
00092 if (pass !== null && pass !== undefined) {
00093 fs.writeFileSync(".dbpasswd", pass);
00094 }
00095 defaultConfig.mongoConfig.dbHost = matches[3];
00096 defaultConfig.mongoConfig.dbPort = matches[4];
00097 defaultConfig.instanceName = matches[5];
00098 }
00099
00100 if (defaultConfig.baseDir === "") {
00101 defaultConfig.baseDir = process.env["ARTDAQ_DATABASE_DIR"];
00102 }
00103
00104 console.log("DBConfig: " + JSON.stringify(defaultConfig, null, 4));
00105 return defaultConfig;
00106 };
00107
00108 function GetFileBase(configName, collection, entity) {
00109 return path_module.join(configName, collection, entity + ".gui.json");
00110 }
00111
00112 function GetTempFilePath(configName, collection, entity, dirs) {
00113 var filebase = GetFileBase(configName, collection, entity);
00114
00115 if (!fs.existsSync(path_module.join(dirs.tmp, configName))) fs.mkdirSync(path_module.join(dirs.tmp, configName));
00116 if (!fs.existsSync(path_module.join(dirs.tmp, configName, collection))) fs.mkdirSync(path_module.join(dirs.tmp, configName, collection));
00117 return path_module.join(dirs.tmp, filebase);
00118 }
00119
00120 function GetFilePath(configName, collection, entity, dirs, dbOnly) {
00121 var filebase = GetFileBase(configName, collection, entity);
00122 console.log("GetFilePath: filebase is " + filebase + ", dirs: " + JSON.stringify(dirs, null, 4));
00123 if (!dbOnly && fs.existsSync(path_module.join(dirs.tmp, filebase))) {
00124 return path_module.join(dirs.tmp, filebase);
00125 }
00126
00127 if (!fs.existsSync(path_module.join(dirs.db, configName))) fs.mkdirSync(path_module.join(dirs.db, configName));
00128 if (!fs.existsSync(path_module.join(dirs.db, configName, collection))) fs.mkdirSync(path_module.join(dirs.db, configName, collection));
00129 return path_module.join(dirs.db, filebase);
00130 }
00131
00137 function LoadFile(fileInfo, dirs, dbConfig) {
00138 console.log("LoadFile: fileInfo: " + JSON.stringify(fileInfo, null, 4) + ", dirs: " + JSON.stringify(dirs, null, 4) + ", dbConfig: " + JSON.stringify(dbConfig, null, 4));
00139 var output = {
00140 data: {}
00141 , filePath: ""
00142 , entity: ""
00143 , collection: ""
00144 , configName: ""
00145 };
00146
00147 output.entity = fileInfo.query.filter["entities.name"];
00148 output.collection = fileInfo.query.collection;
00149 output.configName = fileInfo.query.filter["configurations.name"];
00150
00151 console.log("File info: " + JSON.stringify(fileInfo, null, 4));
00152 output.filePath = GetFilePath(output.configName, output.collection, output.entity, dirs, true);
00153
00154 if (!fs.existsSync(output.filePath)) {
00155 console.log("Loading file from database");
00156 output.data = Connector.RunLoadQuery(dbConfig, fileInfo.query);
00157 console.log("Writing file " + output.filePath);
00158 fs.writeFileSync(output.filePath, JSON.stringify(output.data, null, 4));
00159 } else {
00160 output.data = JSON.parse("" + fs.readFileSync(output.filePath));
00161 }
00162 console.log("File Data: " + JSON.stringify(output, null, 4));
00163 console.log("Done Loading file");
00164 return output;
00165 }
00166
00178 function FetchFile(fileInfo, dataFormat, dbdirectory, dbConfig) {
00179 console.log("FetchFile: fileInfo: " + JSON.stringify(fileInfo, null, 4) + ", dataFormat: " + dataFormat + ", dbDirectory: " + dbdirectory);
00180 var fileName = path_module.join(fileInfo.collection + "_" + fileInfo.name + "_" + fileInfo.version);
00181 if (dataFormat === "fhicl") {
00182 fileName += ".fcl";
00183 } else if (dataFormat === "gui") {
00184 fileName += ".gui.json";
00185 } else {
00186 fileName += ".json";
00187 }
00188 var filePath = path_module.join(dbdirectory, fileName);
00189 var query = {
00190 filter: {
00191 "entities.name": fileInfo.name,
00192 version: fileInfo.version
00193 },
00194 collection: fileInfo.collection,
00195 configurable_entity: fileInfo.name,
00196 dbprovider: dbConfig.dbprovider,
00197 operation: "load",
00198 dataformat: dataFormat
00199 };
00200 var fhiclData = Connector.RunLoadQuery(dbConfig, query, true);
00201 fs.writeFileSync(filePath, JSON.stringify(fhiclData, null, 4));
00202
00203 var stat = fs.statSync(filePath);
00204 return { fileName: fileName, filePath: filePath, size: stat.size }
00205 };
00206
00207 function MakeColumns(rowIn, index, columns, columnGroups, group) {
00208 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);
00209 var rowOut = {
00210 children: []
00211 };
00212
00213 for (var p in rowIn) {
00214 if (rowIn.hasOwnProperty(p)) {
00215 var value = rowIn[p];
00216 if (value !== Object(value) && Utils.ContainsName(columns, p, "name") < 0) {
00217 columns.push({ name: p, type: "string", editable: true, display: true, columnGroup: group });
00218 rowOut[p] = value;
00219 } else if (value === Object(value)) {
00220 var res;
00221 if (Utils.ContainsName(columnGroups, p, "name") < 0) {
00222 columnGroups.push({ name: "" + p, text: "" + p, parentGroup: group });
00223 }
00224 if (value.constructor === Array) {
00225 for (var i in value) {
00226 if (value.hasOwnProperty(i)) {
00227 res = MakeColumns(value[i], index + "." + i, columns, columnGroups, p);
00228 columns = res.columns;
00229 columnGroups = res.columnGroups;
00230 res.row.name = rowIn.name + "/" + p + "___" + i;
00231 res.row.index = index + "." + i;
00232 rowOut.children.push(res.row);
00233 }
00234 }
00235 } else {
00236 res = MakeColumns(value, index, columns, columnGroups, p);
00237 columns = res.columns;
00238 columnGroups = res.columnGroups;
00239 for (var pp in res.row) {
00240 if (res.row.hasOwnProperty(pp)) {
00241 rowOut[pp] = res.row[pp];
00242 }
00243 }
00244
00245 }
00246 } else {
00247 rowOut[p] = value;
00248 }
00249 }
00250 }
00251 if (rowOut.children.length === 0) delete rowOut.children;
00252 else if (Utils.ContainsName(columns, "children", "name") < 0) { columns.push({ name: "children", type: "array", editable: false, display: false }); }
00253
00254 return { row: rowOut, columns: columns, columnGroups: columnGroups };
00255 }
00256
00263 function ParseSequence(sequence, name) {
00264 console.log("ParseSequence: sequence: " + JSON.stringify(sequence, null, 4) + ", name: " + name);
00265 var children = [];
00266 var hasTable = false;
00267 var rows = [];
00268 var columns = [];
00269 var columnGroups = [];
00270 columns.push({ name: "index", type: "number", editable: false, display: true, columnGroup: name });
00271 columns.push({ name: "name", type: "string", editable: false, display: true, columnGroup: name });
00272 columns.push({ name: "type", type: "string", editable: false, display: false, columnGroup: name });
00273 columns.push({ name: "comment", type: "string", editable: false, display: false, columnGroup: name });
00274 console.log("SEQUENCE BEFORE: " + JSON.stringify(sequence,null,4));
00275 for (var i = 0; i < sequence.length; ++i) {
00276 if (sequence[i] === Object(sequence[i])) {
00277
00278 if (sequence[i].constructor === Array) {
00279
00280 var arr = ParseSequence(sequence[i], name + "___" + i);
00281 if (arr.children !== undefined && arr.children.length > 0) {
00282 children.push({ name: name + "___" + i, children: arr.children });
00283 rows.push({ index: i, name: name + "___" + i, children: arr.children });
00284 if (Utils.ContainsName(columns, "children", "name") < 0) {
00285 columns.push({ name: "children", type: "array", editable: false, display: false });
00286 }
00287 }
00288 if (arr.rows !== undefined && arr.rows.length > 0) {
00289 if (arr.hasTable) {
00290 hasTable = true;
00291 }
00292 for (var r in arr.rows) {
00293 if (arr.rows.hasOwnProperty(r)) {
00294 rows.push(arr.rows[r]);
00295 }
00296 }
00297 for (var c in arr.columns) {
00298 if (arr.columns.hasOwnProperty(c) && Utils.ContainsName(columns, arr.columns[c].name, "name") < 0) {
00299 columns.push(arr.columns[c]);
00300 }
00301 }
00302 }
00303 } else {
00304
00305 hasTable = true;
00306 console.log("Parsing as table: " + JSON.stringify(sequence[i], null, 4));
00307 if (!sequence[i].hasOwnProperty("name") || sequence[i].name.length === 0 || sequence[i].name == i) {
00308 sequence[i].name = name + "___" + i;
00309 }
00310 if (Utils.ContainsName(columnGroups, name, "name") < 0) {
00311 columnGroups.push({ name: "" + name, text: "" + name });
00312 }
00313 var res = MakeColumns(sequence[i], i, columns, columnGroups, name);
00314 res.row.index = i;
00315 rows.push(res.row);
00316 columns = res.columns;
00317 columnGroups = res.columnGroups;
00318 }
00319 } else {
00320 var vname = name + "___" + i;
00321 var value = sequence[i];
00322 children.push({ name: vname, value: value });
00323 rows.push({ index: i, name: vname, value: value });
00324 if (Utils.ContainsName(columns, "value", "name") < 0) {
00325 columns.push({ name: "value", type: "string", editable: true, display: true, columnGroup: name });
00326 }
00327 }
00328 }
00329 var comment = sequence.comment ? sequence.comment : " ";
00330
00331 if (hasTable) {
00332 var table = {
00333 name: name
00334 , comment: comment
00335 , type: "table"
00336 , isSequence: true
00337 , table: {
00338 rows: rows
00339 , columns: columns
00340 , columnGroups: columnGroups
00341 }
00342 };
00343 console.log("\nParseSequence returning table: " + JSON.stringify(table, null, 4));
00344 return table;
00345 } else {
00346 var output = { name: name, comment: comment, children: children };
00347 console.log("\nParseSequence returning: " + JSON.stringify(output, null, 4));
00348 return output;
00349 }
00350 };
00351
00358 function ParseFhiclTable(table, sub) {
00359 console.log("ParseFhiclTable: table: " + JSON.stringify(table, null, 4) + ", sub: " + sub);
00360 var children = [];
00361 var subtables = [];
00362 var hasSubtables = false;
00363 var comment = table.comment ? table.comment : " ";
00364
00365
00366 for (var e in table.children) {
00367 if (table.children.hasOwnProperty(e)) {
00368 var element = table.children[e];
00369 if (element.type === "table" && element.isSequence) {
00370 element.type = "sequence";
00371 }
00372
00373 switch (element.type) {
00374 case "table":
00375
00376 hasSubtables = true;
00377 children.push(ParseFhiclTable(element, 1));
00378 break;
00379 case "sequence":
00380 children.push(ParseSequence(element.children, element.name));
00381 break;
00382 case "number":
00383 case "string":
00384 case "string_unquoted":
00385 case "string_doublequoted":
00386 case "string_singlequoted":
00387 case "bool":
00388 children.push(element);
00389 break;
00390 default:
00391 console.log("Unknown type " + element.type + " encountered!");
00392 break;
00393 }
00394 }
00395 }
00396
00397 var obj = { name: table.name, hasSubtables: hasSubtables, children: children, subtables: subtables, type: "table", comment: comment, columns: DefaultColumns };
00398 if (sub === 0 || sub === undefined) {
00399
00400 }
00401 return obj;
00402 };
00403
00404 function FindConfigs(configNameFilter, dbConfig) {
00405 console.log("\nFindConfigs: Request for Named Configurations received");
00406 var configsOutput = { Success: false, data: {}, configs: {} };
00407 try {
00408 var configs = Connector.RunGetConfigsQuery(dbConfig).search;
00409 console.log("CONFIGS: " + JSON.stringify(configs));
00410 for (var conf in configs) {
00411 if (configs.hasOwnProperty(conf)) {
00412 var config = configs[conf];
00413 if (config.name.search(configNameFilter) >= 0) {
00414 var prefix = config.name;
00415 var configNumber = 0;
00416 var matches = config.name.match(/(.*?)[_\-]*(\d*)$/);
00417 if (matches) {
00418 if(matches.length > 1) prefix = matches[1];
00419 if(matches.length > 2) configNumber = parseInt(matches[2]);
00420 }
00421
00422 if (!configsOutput.data.hasOwnProperty(prefix)) {
00423 configsOutput.data[prefix] = [];
00424 }
00425
00426 configsOutput.data[prefix].push({ version: configNumber, data: JSON.stringify(config.query), name: config.name });
00427 configsOutput.configs[config.name] = config.query;
00428 }
00429 }
00430 }
00431 if (configsOutput.data.length === 0) {
00432 configsOutput.data["null"] = {version: 0, data: ""};
00433 configsOutput.configs[configNameFilter] = {};
00434 }
00435 configsOutput.Success = true;
00436 } catch (e) {
00437 console.log("Exception caught: " + e.name + ": " + e.message);
00438 }
00439 console.log("NamedConfigs complete");
00440 return configsOutput;
00441 }
00442
00443 function FindInstances(dbConfig) {
00444 console.log("FindInstances: Request for Database Instances received");
00445 var instancesOutput = { Success: false, data: [] };
00446 instancesOutput.data.push("<option value=\"NONE\">Create New Database Instance</option>");
00447 try {
00448 var dbs = Connector.RunListDatabasesQuery(dbConfig, {}).search;
00449 for (var db in dbs) {
00450 if (dbs.hasOwnProperty(db)) {
00451 instancesOutput.data.push("<option value=" + dbs[db].name + ">" + dbs[db].name + "</option>");
00452 }
00453 }
00454 instancesOutput.Success = true;
00455 } catch (e) {
00456 console.log("Exception caught: " + e.name + ": " + e.message);
00457 }
00458 console.log("FindInstances complete");
00459 return instancesOutput;
00460 }
00461
00469 function LoadConfigFiles(configName, dirs, query, dbConfig) {
00470 console.log("LoadConfigFiles: configName: " + configName + ", dirs: " + JSON.stringify(dirs, null, 4) + ", query: " + JSON.stringify(query, null, 4));
00471 var retval = {
00472 collections: {},
00473 Success: false
00474 };
00475 var error = false;
00476 var configFiles = [];
00477 var e;
00478 try {
00479 configFiles = Connector.RunBuildFilterQuery(dbConfig, configName, query).search;
00480 } catch (e) {
00481 error = true;
00482 console.log("Exception occurred: " + e.name + ": " + e.message);
00483 }
00484 if (!error) {
00485 try {
00486 for (var file in configFiles) {
00487 if (configFiles.hasOwnProperty(file)) {
00488 console.log("File info: " + JSON.stringify(configFiles[file], null, 4));
00489 var entity = LoadFile(configFiles[file], dirs, dbConfig).entity;
00490 var collection = configFiles[file].query.collection;
00491 if (!retval.collections.hasOwnProperty(collection)) {
00492 retval.collections[collection] = {
00493 name: collection
00494 , files: []
00495 };
00496 }
00497 console.log("Adding " + entity + " to output list");
00498 retval.collections[collection].files.push(entity);
00499 }
00500 }
00501 retval.Success = true;
00502 } catch (e) {
00503 console.log("Exception occurred: " + e.name + ": " + e.message);
00504 }
00505 }
00506 return retval;
00507 };
00508
00509 function SearchFile(fileData, searchKey) {
00510 console.log("\nSearching for " + searchKey + " in object " + JSON.stringify(fileData, null, 4));
00511 var retval = { name: fileData.name, children: [], columns: fileData.columns };
00512 for (var ii in fileData.children) {
00513 if (fileData.children.hasOwnProperty(ii)) {
00514 var child = fileData.children[ii];
00515 console.log("Key name: " + child.name);
00516 if (child.name.indexOf(searchKey) !== -1) {
00517 console.log("Adding child to output");
00518 retval.children.push(child);
00519 } else if (child.children && child.children.length > 0) {
00520 console.log("Searching child's children");
00521 var table = SearchFile(child, searchKey);
00522 if (table.children.length > 0) {
00523 retval.children.push(table);
00524 }
00525 }
00526 }
00527 }
00528 console.log("\nSearchFile returning " + JSON.stringify(retval, null, 4));
00529 return retval;
00530 }
00531
00532 function SearchConfigFiles(searchKey, configName, dirs, dbConfig) {
00533 console.log("\nSearchConfigFiles: keySearch: " + searchKey + ", configName: " + configName + ", dirs: " + JSON.stringify(dirs, null, 4));
00534 var retval = {
00535 collectionsTemp: {},
00536 collections: [],
00537 columns: DefaultColumns,
00538 Success: false
00539 };
00540 var error = false;
00541 var configFiles = [];
00542 var query = FindConfigs(configName, dbConfig).configs[configName];
00543 var e;
00544 try {
00545 configFiles = Connector.RunBuildFilterQuery(dbConfig, configName, query).search;
00546 } catch (e) {
00547 error = true;
00548 console.log("Exception occurred: " + e.name + ": " + e.message);
00549 }
00550 if (!error) {
00551 try {
00552 for (var file in configFiles) {
00553 if (configFiles.hasOwnProperty(file)) {
00554 console.log("File info: " + JSON.stringify(configFiles[file], null, 4));
00555 var entity = LoadFile(configFiles[file], dirs, dbConfig).entity;
00556 var collection = configFiles[file].query.collection;
00557 if (!retval.collectionsTemp.hasOwnProperty(collection)) {
00558 retval.collectionsTemp[collection] = {
00559 name: collection
00560 , children: []
00561 };
00562 }
00563 var fileData = GetData(configName, collection, entity, dirs);
00564 fileData.name = entity;
00565 var fileMatches = SearchFile(fileData, searchKey);
00566 if (fileMatches.children.length > 0) {
00567 console.log("Adding " + entity + " to output list");
00568 retval.collectionsTemp[collection].children.push(fileMatches);
00569 }
00570 }
00571 }
00572 retval.Success = true;
00573 } catch (e) {
00574 console.log("Exception occurred: " + e.name + ": " + e.message);
00575 }
00576 }
00577
00578 for (var ii in retval.collectionsTemp) {
00579 if (retval.collectionsTemp.hasOwnProperty(ii)) {
00580 retval.collections.push(retval.collectionsTemp[ii]);
00581 }
00582 }
00583 delete retval.collectionsTemp;
00584 console.log("\nSearchConfigFiles returning: " + JSON.stringify(retval, null, 4));
00585 return retval;
00586 }
00587
00600 function GetData(configName, collectionName, entity, dirs) {
00601 console.log("GetData: configName: " + configName + ", collectionName: " + collectionName + ", entity: " + entity + ", dirs: " + JSON.stringify(dirs, null, 4));
00602 var fileName = GetFilePath(configName, collectionName, entity, dirs, false);
00603 if (!fs.existsSync(fileName)) { throw { name: "FileNotFoundException", message: "The requested file was not found" }; }
00604 var jsonFile = JSON.parse("" + fs.readFileSync(fileName));
00605 var jsonBase = ParseFhiclTable({ children: jsonFile.document.converted.guidata, name: entity }, 0);
00606
00607 return jsonBase;
00608 };
00609
00610 function ReplaceByPath(obj, pathArr, data) {
00611 console.log("ReplaceByPath: obj: " + JSON.stringify(obj, null, 4) + ", pathArr: " + JSON.stringify(pathArr, null, 4) + ", data: " + JSON.stringify(data, null, 4));
00612 if (pathArr.length === 0 && (!obj.name || obj.name === data.name || obj.name === data.name.slice(data.name.indexOf("___") + 3))) {
00613 if (data.column && data.value) {
00614 obj[data.column] = data.value;
00615 } else if (data.type) {
00616 for (var i in data) {
00617 if (data.hasOwnProperty(i)) {
00618 obj[i] = data[i];
00619 }
00620 }
00621 }
00622 return obj;
00623 }
00624
00625 var thisName = pathArr.shift();
00626 var index = -1;
00627 if (obj.type === "table") {
00628 index = Utils.ContainsName(obj.children, thisName, "name");
00629 } else if (obj.type === "sequence") {
00630 index = thisName.slice(thisName.indexOf("___") + 3);
00631 }
00632 console.log("Index is " + index + " (thisName: " + thisName + ", obj.children: " + JSON.stringify(obj.children,null,4) + ")");
00633 obj.children[index] = ReplaceByPath(obj.children[index], pathArr, data);
00634 return obj;
00635 }
00636
00646 function UpdateTable(configName, tablePath, data, dirs) {
00647 console.log("UpdateTable: tablePath:" + tablePath + ", configName: " + configName + ", data: " + JSON.stringify(data, null, 4) + ", dirs: " + JSON.stringify(dirs, null, 4));
00648 var tableArray = tablePath.split('/');
00649 var collection = tableArray.shift();
00650 var entity = tableArray.shift();
00651 var fileName = GetFilePath(configName, collection, entity, dirs, false);
00652 if (!fs.existsSync(fileName)) { throw { name: "FileNotFoundException", message: "The requested file: \"" + fileName + "\" was not found" }; }
00653 console.log("Reading from file " + fileName);
00654 var jsonFile = JSON.parse("" + fs.readFileSync(fileName));
00655 var oldFile = jsonFile.document.converted.guidata;
00656
00657 var curName = tableArray.shift();
00658 var dataIdx = Utils.ContainsName(oldFile, curName, "name");
00659 if (dataIdx < 0) {
00660 console.log("Cannot find data in file!");
00661 return;
00662 }
00663 var oldData = oldFile[dataIdx];
00664 console.log("oldData: " + JSON.stringify(oldData, null, 4));
00665 ReplaceByPath(oldData, tableArray, data);
00666
00667 jsonFile.document.converted.guidata[dataIdx] = oldData;
00668 console.log("After replacement, table data is " + JSON.stringify(oldData, null, 4));
00669
00670 var filePath = GetTempFilePath(configName, collection, entity, dirs);
00671 console.log("Writing to file " + filePath);
00672 fs.writeFileSync(filePath, JSON.stringify(jsonFile, null, 4));
00673 };
00674
00682 function DiscardWorkingDir(dirs) {
00683 console.log("Deleting existing trash dir (if any)");
00684 Utils.ExecSync("rm -rf " + dirs.trash);
00685 console.log("DiscardWorkingDir: Moving db temp to TRASH: mv " + dirs.db + " " + dirs.trash);
00686 Utils.ExecSync("mv " + dirs.db + " " + dirs.trash);
00687 console.log("DiscardWorkingDir: Moving temp files to TRASH: mv " + dirs.tmp + "/* " + dirs.trash);
00688 Utils.ExecSync("mv " + dirs.tmp + "/* " + dirs.trash);
00689 console.log("DiscardWorkingDir: Deleting temp directory: rmdir " + dirs.tmp);
00690 Utils.ExecSync("rmdir " + dirs.tmp);
00691 };
00692
00705 function SaveConfigurationChanges(oldConfig, newConfig, files, dirs, dbConfig) {
00706 console.log("Saving Configuration Changes, oldConfig: " + oldConfig + ", newConfig: " + newConfig + ", files: " + JSON.stringify(files, null, 4) + ", dirs: " + JSON.stringify(dirs, null, 4));
00707 var fileInfo = Connector.RunBuildFilterQuery(dbConfig, oldConfig).search;
00708
00709 var f;
00710 for (f in files) {
00711 if (files.hasOwnProperty(f)) {
00712 console.log("Current file information: " + JSON.stringify(files[f], null, 4));
00713 var collectionName = files[f].collection;
00714 var entities = files[f].entities;
00715 var entity = files[f].entity ? files[f].entity : "notprovided";
00716 var version = files[f].version;
00717 var thisFileInfo = {};
00718 for (var fi in fileInfo) {
00719 if (fileInfo.hasOwnProperty(fi)) {
00720 if (collectionName === fileInfo[fi].query.collection && Utils.ContainsString(entities, fileInfo[fi].query.filter["entities.name"]) != -1) {
00721 console.log("Matched file information to Document: " + JSON.stringify(fileInfo[fi], null, 4));
00722 thisFileInfo = fileInfo[fi];
00723 entity = fileInfo[fi].query.filter["entities.name"];
00724 fileInfo.splice(fi, 1);
00725 }
00726 }
00727 }
00728
00729 console.log("Getting metadata from original and changed files");
00730 var modified = GetFilePath(oldConfig, collectionName, entity, dirs, false);
00731 var newMetadata = ReadFileMetadata(dirs, thisFileInfo, dbConfig);
00732
00733
00734
00735 newMetadata.version = version;
00736 console.log("newMetadata: " + JSON.stringify(newMetadata, null, 4));
00737
00738 console.log("Checking metadata version strings");
00739 while (VersionExists(entity, collectionName, newMetadata.version, dbConfig)) {
00740 console.log("Inferring new version string...");
00741 version = Utils.Uniquify(newMetadata.version);
00742 console.log("Changing version from " + newMetadata.version + " to " + version);
00743 newMetadata.version = version;
00744 console.log("OK");
00745 }
00746 console.log("Prepending changelog");
00747 newMetadata.changelog = files[f].changelog + newMetadata.changelog;
00748
00749 console.log("Writing new metadata to file");
00750 if (WriteFileMetadata(newMetadata, modified)) {
00751
00752 console.log("Running store query");
00753 var data = "" + fs.readFileSync(modified);
00754 console.log("Writing " + data + " to database");
00755 Connector.RunStoreQuery(dbConfig, data, collectionName, newMetadata.version, entity, "gui", newConfig);
00756 } else {
00757 console.log("ERROR: Could not find file " + modified);
00758 console.log("Please check if it exists.");
00759 }
00760 }
00761 }
00762
00763 console.log("Running addconfig for unmodified files: " + JSON.stringify(fileInfo, null, 4));
00764 for (f in fileInfo) {
00765 if (fileInfo.hasOwnProperty(f)) {
00766 var unmodifiedVersion = GetVersion(fileInfo[f], dirs, dbConfig);
00767 Connector.RunAddConfigQuery(dbConfig, newConfig, unmodifiedVersion, fileInfo[f].query.collection, { name: fileInfo[f].query.filter["entities.name"] });
00768 }
00769 }
00770
00771 DiscardWorkingDir(dirs);
00772 };
00773
00782 function CreateNewConfiguration(configName, configData, dbConfig) {
00783 console.log("CreateNewConfigration: configName: " + configName + ", configData: " + JSON.stringify(configData, null, 4));
00784 var query = {
00785 operations: []
00786 };
00787
00788 for (var d in configData.entities) {
00789 if (configData.entities.hasOwnProperty(d)) {
00790 var entityData = configData.entities[d];
00791 console.log("Entity: " + JSON.stringify(entityData, null, 4));
00792 query.operations.push({
00793 filter: { version: entityData.version, "entities.name": entityData.name },
00794 configuration: configName,
00795 collection: entityData.collection,
00796 dbprovider: dbConfig.dbprovider,
00797 operation: "addconfig",
00798 dataformat: "gui"
00799 });
00800 }
00801 }
00802
00803 Connector.RunNewConfigQuery(dbConfig, query);
00804 };
00805
00812 function ReadConfigurationMetadata(configName, dirs, dbConfig) {
00813 console.log("ReadConfigurationMetadata: configname: " + configName + ", dirs: " + JSON.stringify(dirs, null, 4));
00814
00815 var data = Connector.RunBuildFilterQuery(dbConfig, configName ).search;
00816
00817 var metadata = {
00818 entities: []
00819 };
00820 for (var i in data) {
00821 if (data.hasOwnProperty(i)) {
00822 console.log("Loading metadata: File " + i + " of " + data.length);
00823 var version = GetVersion(data[i], dirs, dbConfig);
00824 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 });
00825 }
00826 }
00827
00828 console.log("Returning entity list: " + JSON.stringify(metadata.entities, null, 4));
00829 return metadata;
00830 };
00831
00840 function GetVersion(query, dirs, dbConfig) {
00841 console.log("\"GetVersion\": {\"query\":" + JSON.stringify(query, null, 4) + ", \"dirs\":" + JSON.stringify(dirs, null, 4) + "},");
00842 var ver = LoadFile(query, dirs, dbConfig).data.version;
00843 console.log("GetVersion Returning " + ver);
00844 return ver;
00845 };
00846
00856 function ReadFileMetadata(dirs, query, dbConfig) {
00857 console.log("ReadFileMetadata: query=" + JSON.stringify(query, null, 4) + ", dirs=" + JSON.stringify(dirs, null, 4) + ", dbConfig: " + JSON.stringify(dbConfig, null, 4));
00858
00859 var jsonFile = LoadFile(query, dirs, dbConfig).data;
00860 if (jsonFile.changelog === undefined) {
00861 jsonFile.changelog = "";
00862 }
00863 var metadata = {
00864 entities: jsonFile.entities,
00865 bookkeeping: jsonFile.bookkeeping,
00866 aliases: jsonFile.aliases,
00867 configurations: jsonFile.configurations,
00868 version: jsonFile.version,
00869 changelog: jsonFile.changelog,
00870 collection: query.query.collection
00871 };
00872
00873 console.log("ReadFileMetadata returning: " + JSON.stringify(metadata, null, 4));
00874 return metadata;
00875 };
00876
00883 function WriteFileMetadata(newMetadata, fileName) {
00884 console.log("WriteFileMetadata: newMetadata=" + JSON.stringify(newMetadata, null, 4) + ", fileName=" + fileName);
00885
00886 console.log("Reading file: " + fileName);
00887 if (!fs.existsSync(fileName)) return false;
00888 var jsonFile = JSON.parse("" + fs.readFileSync(fileName));
00889
00890
00891 console.log("Setting fields: " + JSON.stringify(newMetadata, null, 4));
00892 jsonFile.configurable_entity = newMetadata.configurable_entity;
00893 jsonFile.bookkeeping = newMetadata.bookkeeping;
00894 jsonFile.aliases = newMetadata.aliases;
00895 jsonFile.configurations = newMetadata.configurations;
00896 jsonFile.version = newMetadata.version;
00897 jsonFile.document.converted.changelog = newMetadata.changelog;
00898
00899 console.log("Writing data to file");
00900
00901 fs.writeFileSync(fileName, JSON.stringify(jsonFile, null, 4));
00902
00903 return true;
00904 };
00905
00911 function GetDirectories(userId, dbConfig) {
00912 console.log("GetDirectories: userid=" + userId);
00913 if (dbConfig.baseDir === "" || !dbConfig.baseDir) {
00914 dbConfig.baseDir = process.env["HOME"] + "/databases";
00915 console.log("WARNING: ARTDAQ_DATABASE_DATADIR not set. Using $HOME/databases instead!!!");
00916 }
00917
00918 if (!fs.existsSync(dbConfig.baseDir)) {
00919 console.log("ERROR: Base Directory " +dbConfig.baseDir + " doesn't exist!!!");
00920 throw { name: "BaseDirectoryMissingException", message: "ERROR: Base Directory doesn't exist!!!" };
00921 }
00922 if (!fs.existsSync(path_module.join(dbConfig.baseDir, "db"))) {
00923 fs.mkdirSync(path_module.join(dbConfig.baseDir, "db"));
00924 }
00925 if (!fs.existsSync(path_module.join(dbConfig.baseDir, "tmp"))) {
00926 fs.mkdirSync(path_module.join(dbConfig.baseDir, "tmp"));
00927 }
00928 if (!fs.existsSync(path_module.join(dbConfig.baseDir, "TRASH"))) {
00929 fs.mkdirSync(path_module.join(dbConfig.baseDir, "TRASH"));
00930 }
00931
00932
00933 var db = path_module.join(dbConfig.baseDir, "db", userId);
00934 var tmp = path_module.join(dbConfig.baseDir, "tmp", userId);
00935 var trash = path_module.join(dbConfig.baseDir, "TRASH", userId);
00936
00937
00938 if (!fs.existsSync(db)) {
00939 fs.mkdirSync(db);
00940 }
00941 if (!fs.existsSync(tmp)) {
00942 fs.mkdirSync(tmp);
00943 }
00944 if (!fs.existsSync(trash)) {
00945 fs.mkdirSync(trash);
00946 }
00947
00948 return { db: db, tmp: tmp, trash: trash };
00949 };
00950
00959 function VersionExists(entity, collection, version, dbConfig) {
00960 console.log("\"VersionExists\": { version:\"" + version + "\", entity:" + JSON.stringify(entity, null, 4) + ", collection: \"" + collection + "\"}");
00961 var query = {
00962 filter: {
00963 "entities.name": entity
00964 },
00965 collection: collection,
00966 dbprovider: dbConfig.dbprovider,
00967 operation: "findversions",
00968 dataformat: "gui"
00969 };
00970 var vers = Connector.RunGetVersionsQuery(dbConfig, query).search;
00971 console.log("Search returned: " + JSON.stringify(vers, null, 4));
00972 return Utils.ContainsName(vers, version, "name") >= 0;
00973 };
00974
00979 function Lock() {
00980 console.log("Lock");
00981 if (fs.existsSync("/tmp/node_db_lockfile")) {
00982 if (Date.now() - fs.fstatSync("/tmp/node_db_lockfile").ctime.getTime() > 1000) {
00983 console.log("Stale Lockfile detected, deleting...");
00984 return Unlock();
00985 } else {
00986 console.log("Lockfile detected and is not stale, aborting...");
00987 }
00988 return false;
00989 }
00990
00991 fs.writeFileSync("/tmp/node_db_lockfile", "locked");
00992 return true;
00993 }
00994
00999 function Unlock() {
01000 console.log("Unlock");
01001 fs.unlinkSync("/tmp/node_db_lockfile");
01002 return true;
01003 }
01004
01005
01006 db.RO_GetData = function (post, dbConfig) {
01007 console.log("RO_GetData: " + JSON.stringify(post, null, 4));
01008 var ret = { Success: false, data: {} };
01009 try {
01010 ret.data = GetData(post.configName, post.collection, post.entity, GetDirectories(post.user, dbConfig));
01011 ret.Success = true;
01012 } catch (e) {
01013 console.log("Exception occurred: " + e.name + ": " + e.message);
01014 }
01015
01016 console.log("GetData complete");
01017 return ret;
01018 };
01019
01020 db.RW_MakeNewConfig = function (post, dbConfig) {
01021 if (Lock()) {
01022 console.log("RW_MakeNewConfig: Request to make new configuration received: " + JSON.stringify(post, null, 4));
01023 var res = { Success: false };
01024 var error = false;
01025 var e;
01026 try {
01027 var configs = Connector.RunGetConfigsQuery(dbConfig).search;
01028 if (!Utils.ValidatePath(post.name)) {
01029 console.log("Invalid name detected!");
01030 error = true;
01031 }
01032 while (Utils.ContainsName(configs, post.name, "name") >= 0) {
01033 console.log("Inferring new configuration name");
01034 post.name = Utils.Uniquify(post.name);
01035 }
01036 } catch (e) {
01037 error = true;
01038 console.log("Exception occurred: " + e.name + ": " + e.message);
01039 }
01040 if (!error) {
01041 console.log("Creating Configuration");
01042 try {
01043 CreateNewConfiguration(post.name, JSON.parse(post.config), dbConfig);
01044 res.Success = true;
01045 } catch (e) {
01046 console.log("Exception occurred: " + e.name + ": " + e.message);
01047 }
01048 }
01049 Unlock();
01050 console.log("MakeNewConfig completed");
01051 return res;
01052 }
01053 return null;
01054 };
01055
01056 db.RW_saveConfig = function (post, dbConfig) {
01057 if (Lock()) {
01058 console.log("RW_saveConfig: Request to save configuration recieved. Configuration data: " + JSON.stringify(post, null, 4));
01059 var res = { Success: false };
01060 var error = false;
01061 var e;
01062 try {
01063 console.log("Checking for unique Configuration name");
01064 var configs = Connector.RunGetConfigsQuery(dbConfig).search;
01065 if (!Utils.ValidatePath(post.newConfigName) || Utils.ContainsName(configs, post.oldConfigName, "name") < 0) {
01066 console.log("Invalid name detected!");
01067 error = true;
01068 }
01069 while (Utils.ContainsName(configs, post.newConfigName, "name") >= 0) {
01070 console.log("Inferring new configuration name");
01071 post.newConfigName = Utils.Uniquify(post.newConfigName);
01072 }
01073 } catch (e) {
01074 error = true;
01075 console.log("Exception occurred: " + e.name + ": " + e.message);
01076 }
01077 if (!error) {
01078 try {
01079 console.log("Updating Configuration Files");
01080 SaveConfigurationChanges(post.oldConfigName, post.newConfigName, post.files, GetDirectories(post.user, dbConfig), dbConfig);
01081 res.Success = true;
01082 } catch (e) {
01083 console.log("Exception occurred: " + e.name + ": " + e.message);
01084 }
01085 }
01086 Unlock();
01087 console.log("SaveConfig completed");
01088 return res;
01089 }
01090 return null;
01091 };
01092
01093 db.RO_LoadNamedConfig = function (post, dbConfig) {
01094 console.log("RO_LoadNamedConfig: Request for configuration with name \"" + post.configName + "\" and search query \"" + post.query + "\" received.");
01095 if (post.query.length === 0 || post.configName === "No Configurations Found") {
01096 return { collections: [] };
01097 }
01098 return LoadConfigFiles(post.configName, GetDirectories(post.user, dbConfig), JSON.parse(post.query), dbConfig);
01099 };
01100
01101 db.RW_discardConfig = function (post, dbConfig) {
01102 console.log("RW_discardConfig: Discarding configuration with parameters: " + JSON.stringify(post, null, 4));
01103 DiscardWorkingDir(GetDirectories(post.user, dbConfig));
01104 return { Success: true };
01105 };
01106
01107 db.RO_AddOrUpdate = function (post, dbConfig) {
01108 console.log("RO_AddOrUpdate: Request to update table row recieved: " + JSON.stringify(post, null, 4));
01109 UpdateTable(post.configName, post.table, post.row, GetDirectories(post.user, dbConfig));
01110 return { Success: true };
01111 }
01112
01113 db.RO_Update = function (post, dbConfig) {
01114 console.log("RO_Update: Request to update table received: " + JSON.stringify(post, null, 4));
01115 UpdateTable(post.configName, post.table, { id: post.id, name: post.name, column: post.column, value: post.value }, GetDirectories(post.user, dbConfig));
01116 console.log("Update Complete");
01117 return { Success: true };
01118 };
01119
01120 db.RO_LoadConfigMetadata = function (post, dbConfig) {
01121 console.log("RO_LoadConfigMetadata: Request to load configuration metadata received: " + JSON.stringify(post, null, 4) + ", dbConfig: " + JSON.stringify(dbConfig, null, 4));
01122 var ret = { Success: false, data: {} };
01123 try {
01124 ret.data = ReadConfigurationMetadata(post.configName, GetDirectories(post.user, dbConfig), dbConfig);
01125 ret.Success = true;
01126 } catch (e) {
01127 console.log("Exception caught: " + e.name + ": " + e.message);
01128 }
01129 console.log("LoadConfigMetadata complete");
01130 return ret;
01131 };
01132
01133 db.RO_LoadFileMetadata = function (post, dbConfig) {
01134 console.log("RO_LoadFileMetadata: Request to load file metadata received: " + JSON.stringify(post, null, 4));
01135 var ret = { Success: false, data: {} };
01136 var dirs = GetDirectories(post.user, dbConfig);
01137 var error = false;
01138 var query = {};
01139 var e;
01140 try {
01141 var search = Connector.RunBuildFilterQuery(dbConfig, post.configName).search;
01142 for (var s in search) {
01143 if (search.hasOwnProperty(s)) {
01144 if (search[s].query.collection === post.collection && search[s].query.filter["entities.name"] === post.entity) {
01145 query = search[s];
01146 }
01147 }
01148 }
01149 } catch (e) {
01150 error = true;
01151 console.log("Exception caught: " + e.name + ": " + e.message);
01152 }
01153 if (!error) {
01154 try {
01155 ret.data = ReadFileMetadata(dirs, query, dbConfig);
01156 ret.Success = true;
01157 } catch (e) {
01158 console.log("Exception caught: " + e.name + ": " + e.message);
01159 }
01160 }
01161 console.log("LoadFileMetadata complete");
01162 return ret;
01163 };
01164
01165 db.RW_UploadConfigurationFile = function (post, dbConfig) {
01166 if (Lock()) {
01167 console.log("RW_UploadConfigurationFile: Recieved request to upload file: " + JSON.stringify(post, null, 4));
01168 var e;
01169 var error = false;
01170 var ret = { Success: false };
01171 try {
01172 while (VersionExists(post.entity, post.collection, post.version, dbConfig)) {
01173 console.log("Version already exists. Running uniquifier...");
01174 post.version = Utils.Uniquify(post.version);
01175 }
01176 } catch (e) {
01177 error = true;
01178 console.log("Exception caught: " + e.name + ": " + e.message);
01179 }
01180
01181 if (!error) {
01182 console.log("Running store fhicl query");
01183 try {
01184 Connector.RunStoreQuery(dbConfig, post.file, post.collection, post.version, post.entity, post.type);
01185 ret.Success = true;
01186 } catch (e) {
01187 console.log("Exception caught: " + e.name + ": " + e.message);
01188 }
01189 }
01190 Unlock();
01191 console.log("UploadConfigurationFile complete");
01192 return ret;
01193 }
01194 return null;
01195 };
01196
01197 db.RO_DownloadConfigurationFile = function (post, dbConfig) {
01198 console.log("RO_DownloadConfigurationFile: Request to download file(s) received: " + JSON.stringify(post, null, 4));
01199 var dirs = GetDirectories(post.user, dbConfig);
01200 var configObj = JSON.parse(post.config);
01201 try {
01202 if (configObj.entities.length === 1) {
01203 console.log("Single file mode: Fetching file...");
01204 var fileInfo = FetchFile(configObj.entities[0], post.type, dirs.db, dbConfig);
01205
01206 var fclhdrs = {
01207 'Content-Type': 'text/plain',
01208 'Content-Length': fileInfo.size,
01209 'Content-Disposition': 'attachment filename=' + fileInfo.fileName
01210 }
01211 console.log("Headers: " + JSON.stringify(fclhdrs, null, 4) + ", fileInfo: " + JSON.stringify(fileInfo, null, 4));
01212
01213 var fclStream = fs.createReadStream(fileInfo.filePath);
01214 db.emit("stream", fclStream, fclhdrs, 200);
01215 } else if (configObj.entities.length > 1) {
01216 var args = ['cz'];
01217 for (var e in configObj.entities) {
01218 if (configObj.entities.hasOwnProperty(e)) {
01219 args.push(FetchFile(configObj.entities[e], post.type, dirs.db, dbConfig).fileName);
01220 }
01221 }
01222 var fileName = post.tarFileName + ".tar.gz";
01223 var tarhdrs = {
01224 'Content-Type': "application/x-gzip",
01225 'Content-Disposition': 'attachment filename=' + fileName
01226 }
01227
01228 console.log("Spawning: tar " + args.join(" "));
01229 var tar = child_process.spawn("tar", args, { cwd: dirs.db, stdio: [0, 'pipe', 0] });
01230 db.emit("stream", tar.stdout, tarhdrs, 200);
01231
01232 }
01233 } catch (err) {
01234 console.log("Exception caught: " + err.name + ": " + err.message);
01235
01236 var s = new stream.Readable();
01237 s._read = function noop() { };
01238 s.push("ERROR");
01239 s.push(null);
01240
01241 var errhdrs = {
01242 'Content-Type': 'text/plain'
01243 }
01244 db.emit("stream", s, errhdrs, 500);
01245 }
01246
01247 };
01248
01249 db.RO_NamedConfigs = function (post, dbConfig) {
01250 console.log("RO_NamedConfigs: Request for Named Configurations received");
01251 var filter = "" + post.configFilter;
01252 return FindConfigs(filter, dbConfig);
01253 };
01254
01255 db.RW_updateDbConfig = function (post, dbConfig) {
01256 console.log("RW_updateDbConfig: Request to update module configuration received: " + JSON.stringify(post, null, 4));
01257 var output = { Success: false };
01258 if (fs.existsSync(post.baseDir) && (post.dbprovider === "filesystem" || post.dbprovider === "mongo")) {
01259 if (dbConfig.baseDir !== post.baseDir) {
01260 dbConfig.baseDir = post.baseDir;
01261 db.emit("message", { name: "db", target: "baseDir", data: post.baseDir });
01262 }
01263 if (dbConfig.dbprovider !== post.dbprovider) {
01264 dbConfig.dbprovider = post.dbprovider;
01265 db.emit("message", { name: "db", target: "dbprovider", data: post.dbprovider });
01266 }
01267 if (dbConfig.instanceName !== post.instanceName) {
01268 dbConfig.instanceName = post.instanceName;
01269 db.emit("message", { name: "db", target: "instanceName", data: post.instanceName });
01270 }
01271 console.log("DB Config is now: " + JSON.stringify(dbConfig, null, 4));
01272 output.Success = true;
01273 }
01274 return output;
01275 }
01276
01277 db.RO_SearchLoadedConfig = function (post, dbConfig) {
01278 console.log("RO_SearchLoadedConfig: Searching for keys containing name \"" + post.searchKey + "\" from configuration name \"" + post.configName + "\" received.");
01279 if (post.configName === "No Configurations Found") {
01280 return { Success: false, collections: [] };
01281 }
01282 return SearchConfigFiles(post.searchKey, post.configName, GetDirectories(post.user, dbConfig), dbConfig);
01283 }
01284
01285 db.RW_makeNewDBInstance = function (post, dbConfig) {
01286 console.log("RW_makeNewDBInstance: Creating new database instance \"" + post.name + "\".");
01287 dbConfig.instanceName = post.name;
01288 return { Success: true };
01289 }
01290
01291 db.RW_AddEntityToFile = function (post, dbConfig) {
01292 console.log("RW_AddEntityToFile: request to add entity name \"" + post.name + "\" to configuration file " + post.configName + "/" + post.collection + "/" + post.entity);
01293 return { Success: true };
01294 }
01295
01296
01297 db.GET_EntitiesAndVersions = function (dbConfig) {
01298 console.log("GET_EntitiesAndVersions: Request for current Entities and Versions received");
01299 var output = {
01300 Success: false,
01301 collections: []
01302 };
01303 try {
01304 var entities = Connector.RunGetEntitiesQuery(dbConfig).search;
01305 console.log("Returned entities: " + JSON.stringify(entities, null, 4));
01306 for (var ent in entities) {
01307 if (entities.hasOwnProperty(ent)) {
01308 var entity = entities[ent];
01309 var versions = Connector.RunGetVersionsQuery(dbConfig, entity.query);
01310 if (Utils.ContainsName(output.collections, entity.query.collection, "name") < 0) {
01311 output.collections.push({ name: entity.query.collection, entities: [] });
01312 }
01313
01314 var index = Utils.ContainsName(output.collections, entity.query.collection, "name");
01315
01316 var entityObj = {
01317 collection: entity.query.collection,
01318 name: entity.name,
01319 versions: versions
01320 };
01321 output.collections[index].entities.push(entityObj);
01322 }
01323 }
01324 output.Success = true;
01325 } catch (e) {
01326 console.log("Exception caught: " + e.name + ": " + e.message);
01327 }
01328 console.log("EntitiesAndVersions complete");
01329 return output;
01330 };
01331
01332 db.GET_getDbConfig = function (dbConfig) {
01333 console.log("GET_getDbConfig Request for Database Module Configuration received");
01334
01335 var instances = FindInstances(dbConfig);
01336 var output = {
01337 Success: true,
01338 baseDir: dbConfig.baseDir,
01339 dbprovider: dbConfig.dbprovider,
01340 instanceName: dbConfig.instanceName,
01341 data: instances.data
01342 };
01343 return output;
01344 }
01345
01346
01347 db.MasterInitFunction = function (workerData, config) {
01348 var dbConfig = MakeDbConfig(config);
01349 workerData["db"] = dbConfig;
01350 GetDirectories("", dbConfig);
01351 };
01352
01353 module.exports = function (moduleHolder) {
01354 moduleHolder["db"] = db;
01355 };