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 if (index === -1 && thisName == data.name) {
00634 console.log("New Entry! Appending...");
00635 var dataObj = {};
00636 for (var i in data) {
00637 if (data.hasOwnProperty(i) && data[i] !== "") {
00638 dataObj[i] = data[i];
00639 }
00640 }
00641 obj.children.push(dataObj);
00642 }
00643 else {
00644 obj.children[index] = ReplaceByPath(obj.children[index], pathArr, data);
00645 }
00646 return obj;
00647 }
00648
00658 function UpdateTable(configName, tablePath, data, dirs) {
00659 console.log("UpdateTable: tablePath:" + tablePath + ", configName: " + configName + ", data: " + JSON.stringify(data, null, 4) + ", dirs: " + JSON.stringify(dirs, null, 4));
00660 var tableArray = tablePath.split('/');
00661 var collection = tableArray.shift();
00662 var entity = tableArray.shift();
00663 var fileName = GetFilePath(configName, collection, entity, dirs, false);
00664 if (!fs.existsSync(fileName)) { throw { name: "FileNotFoundException", message: "The requested file: \"" + fileName + "\" was not found" }; }
00665 console.log("Reading from file " + fileName);
00666 var jsonFile = JSON.parse("" + fs.readFileSync(fileName));
00667 var oldFile = jsonFile.document.converted.guidata;
00668
00669 var curName = tableArray.shift();
00670 var dataIdx = Utils.ContainsName(oldFile, curName, "name");
00671 if (dataIdx < 0) {
00672 console.log("Cannot find data in file!");
00673 return;
00674 }
00675 var oldData = oldFile[dataIdx];
00676 console.log("oldData: " + JSON.stringify(oldData, null, 4));
00677 ReplaceByPath(oldData, tableArray, data);
00678
00679 jsonFile.document.converted.guidata[dataIdx] = oldData;
00680 console.log("After replacement, table data is " + JSON.stringify(oldData, null, 4));
00681
00682 var filePath = GetTempFilePath(configName, collection, entity, dirs);
00683 console.log("Writing to file " + filePath);
00684 fs.writeFileSync(filePath, JSON.stringify(jsonFile, null, 4));
00685 };
00686
00694 function DiscardWorkingDir(dirs) {
00695 console.log("Deleting existing trash dir (if any)");
00696 Utils.ExecSync("rm -rf " + dirs.trash);
00697 console.log("DiscardWorkingDir: Moving db temp to TRASH: mv " + dirs.db + " " + dirs.trash);
00698 Utils.ExecSync("mv " + dirs.db + " " + dirs.trash);
00699 console.log("DiscardWorkingDir: Moving temp files to TRASH: mv " + dirs.tmp + "/* " + dirs.trash);
00700 Utils.ExecSync("mv " + dirs.tmp + "/* " + dirs.trash);
00701 console.log("DiscardWorkingDir: Deleting temp directory: rmdir " + dirs.tmp);
00702 Utils.ExecSync("rmdir " + dirs.tmp);
00703 };
00704
00717 function SaveConfigurationChanges(oldConfig, newConfig, files, dirs, dbConfig) {
00718 console.log("Saving Configuration Changes, oldConfig: " + oldConfig + ", newConfig: " + newConfig + ", files: " + JSON.stringify(files, null, 4) + ", dirs: " + JSON.stringify(dirs, null, 4));
00719 var fileInfo = Connector.RunBuildFilterQuery(dbConfig, oldConfig).search;
00720
00721 var f;
00722 for (f in files) {
00723 if (files.hasOwnProperty(f)) {
00724 console.log("Current file information: " + JSON.stringify(files[f], null, 4));
00725 var collectionName = files[f].collection;
00726 var entities = files[f].entities;
00727 var entity = files[f].entity ? files[f].entity : "notprovided";
00728 var version = files[f].version;
00729 var thisFileInfo = {};
00730 for (var fi in fileInfo) {
00731 if (fileInfo.hasOwnProperty(fi)) {
00732 if (collectionName === fileInfo[fi].query.collection && Utils.ContainsString(entities, fileInfo[fi].query.filter["entities.name"]) != -1) {
00733 console.log("Matched file information to Document: " + JSON.stringify(fileInfo[fi], null, 4));
00734 thisFileInfo = fileInfo[fi];
00735 entity = fileInfo[fi].query.filter["entities.name"];
00736 fileInfo.splice(fi, 1);
00737 }
00738 }
00739 }
00740
00741 console.log("Getting metadata from original and changed files");
00742 var modified = GetFilePath(oldConfig, collectionName, entity, dirs, false);
00743 var newMetadata = ReadFileMetadata(dirs, thisFileInfo, dbConfig);
00744
00745
00746
00747 newMetadata.version = version;
00748 console.log("newMetadata: " + JSON.stringify(newMetadata, null, 4));
00749
00750 console.log("Checking metadata version strings");
00751 while (VersionExists(entity, collectionName, newMetadata.version, dbConfig)) {
00752 console.log("Inferring new version string...");
00753 version = Utils.Uniquify(newMetadata.version);
00754 console.log("Changing version from " + newMetadata.version + " to " + version);
00755 newMetadata.version = version;
00756 console.log("OK");
00757 }
00758 console.log("Prepending changelog");
00759 newMetadata.changelog = files[f].changelog + newMetadata.changelog;
00760
00761 console.log("Writing new metadata to file");
00762 if (WriteFileMetadata(newMetadata, modified)) {
00763
00764 console.log("Running store query");
00765 var data = "" + fs.readFileSync(modified);
00766 console.log("Writing " + data + " to database");
00767 Connector.RunStoreQuery(dbConfig, data, collectionName, newMetadata.version, entity, "gui", newConfig);
00768 } else {
00769 console.log("ERROR: Could not find file " + modified);
00770 console.log("Please check if it exists.");
00771 }
00772 }
00773 }
00774
00775 console.log("Running addconfig for unmodified files: " + JSON.stringify(fileInfo, null, 4));
00776 for (f in fileInfo) {
00777 if (fileInfo.hasOwnProperty(f)) {
00778 var unmodifiedVersion = GetVersion(fileInfo[f], dirs, dbConfig);
00779 Connector.RunAddConfigQuery(dbConfig, newConfig, unmodifiedVersion, fileInfo[f].query.collection, { name: fileInfo[f].query.filter["entities.name"] });
00780 }
00781 }
00782
00783 DiscardWorkingDir(dirs);
00784 };
00785
00794 function CreateNewConfiguration(configName, configData, dbConfig) {
00795 console.log("CreateNewConfigration: configName: " + configName + ", configData: " + JSON.stringify(configData, null, 4));
00796 var query = {
00797 operations: []
00798 };
00799
00800 for (var d in configData.entities) {
00801 if (configData.entities.hasOwnProperty(d)) {
00802 var entityData = configData.entities[d];
00803 console.log("Entity: " + JSON.stringify(entityData, null, 4));
00804 query.operations.push({
00805 filter: { version: entityData.version, "entities.name": entityData.name },
00806 configuration: configName,
00807 collection: entityData.collection,
00808 dbprovider: dbConfig.dbprovider,
00809 operation: "addconfig",
00810 dataformat: "gui"
00811 });
00812 }
00813 }
00814
00815 Connector.RunNewConfigQuery(dbConfig, query);
00816 };
00817
00824 function ReadConfigurationMetadata(configName, dirs, dbConfig) {
00825 console.log("ReadConfigurationMetadata: configname: " + configName + ", dirs: " + JSON.stringify(dirs, null, 4));
00826
00827 var data = Connector.RunBuildFilterQuery(dbConfig, configName ).search;
00828
00829 var metadata = {
00830 entities: []
00831 };
00832 for (var i in data) {
00833 if (data.hasOwnProperty(i)) {
00834 console.log("Loading metadata: File " + i + " of " + data.length);
00835 var version = GetVersion(data[i], dirs, dbConfig);
00836 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 });
00837 }
00838 }
00839
00840 console.log("Returning entity list: " + JSON.stringify(metadata.entities, null, 4));
00841 return metadata;
00842 };
00843
00852 function GetVersion(query, dirs, dbConfig) {
00853 console.log("\"GetVersion\": {\"query\":" + JSON.stringify(query, null, 4) + ", \"dirs\":" + JSON.stringify(dirs, null, 4) + "},");
00854 var ver = LoadFile(query, dirs, dbConfig).data.version;
00855 console.log("GetVersion Returning " + ver);
00856 return ver;
00857 };
00858
00868 function ReadFileMetadata(dirs, query, dbConfig) {
00869 console.log("ReadFileMetadata: query=" + JSON.stringify(query, null, 4) + ", dirs=" + JSON.stringify(dirs, null, 4) + ", dbConfig: " + JSON.stringify(dbConfig, null, 4));
00870
00871 var jsonFile = LoadFile(query, dirs, dbConfig).data;
00872 if (jsonFile.changelog === undefined) {
00873 jsonFile.changelog = "";
00874 }
00875 var metadata = {
00876 entities: jsonFile.entities,
00877 bookkeeping: jsonFile.bookkeeping,
00878 aliases: jsonFile.aliases,
00879 configurations: jsonFile.configurations,
00880 version: jsonFile.version,
00881 changelog: jsonFile.changelog,
00882 collection: query.query.collection
00883 };
00884
00885 console.log("ReadFileMetadata returning: " + JSON.stringify(metadata, null, 4));
00886 return metadata;
00887 };
00888
00895 function WriteFileMetadata(newMetadata, fileName) {
00896 console.log("WriteFileMetadata: newMetadata=" + JSON.stringify(newMetadata, null, 4) + ", fileName=" + fileName);
00897
00898 console.log("Reading file: " + fileName);
00899 if (!fs.existsSync(fileName)) return false;
00900 var jsonFile = JSON.parse("" + fs.readFileSync(fileName));
00901
00902
00903 console.log("Setting fields: " + JSON.stringify(newMetadata, null, 4));
00904 jsonFile.configurable_entity = newMetadata.configurable_entity;
00905 jsonFile.bookkeeping = newMetadata.bookkeeping;
00906 jsonFile.aliases = newMetadata.aliases;
00907 jsonFile.configurations = newMetadata.configurations;
00908 jsonFile.version = newMetadata.version;
00909 jsonFile.document.converted.changelog = newMetadata.changelog;
00910
00911 console.log("Writing data to file");
00912
00913 fs.writeFileSync(fileName, JSON.stringify(jsonFile, null, 4));
00914
00915 return true;
00916 };
00917
00923 function GetDirectories(userId, dbConfig) {
00924 console.log("GetDirectories: userid=" + userId);
00925 if (dbConfig.baseDir === "" || !dbConfig.baseDir) {
00926 dbConfig.baseDir = process.env["HOME"] + "/databases";
00927 console.log("WARNING: ARTDAQ_DATABASE_DATADIR not set. Using $HOME/databases instead!!!");
00928 }
00929
00930 if (!fs.existsSync(dbConfig.baseDir)) {
00931 console.log("ERROR: Base Directory " +dbConfig.baseDir + " doesn't exist!!!");
00932 throw { name: "BaseDirectoryMissingException", message: "ERROR: Base Directory doesn't exist!!!" };
00933 }
00934 if (!fs.existsSync(path_module.join(dbConfig.baseDir, "db"))) {
00935 fs.mkdirSync(path_module.join(dbConfig.baseDir, "db"));
00936 }
00937 if (!fs.existsSync(path_module.join(dbConfig.baseDir, "tmp"))) {
00938 fs.mkdirSync(path_module.join(dbConfig.baseDir, "tmp"));
00939 }
00940 if (!fs.existsSync(path_module.join(dbConfig.baseDir, "TRASH"))) {
00941 fs.mkdirSync(path_module.join(dbConfig.baseDir, "TRASH"));
00942 }
00943
00944
00945 var db = path_module.join(dbConfig.baseDir, "db", userId);
00946 var tmp = path_module.join(dbConfig.baseDir, "tmp", userId);
00947 var trash = path_module.join(dbConfig.baseDir, "TRASH", userId);
00948
00949
00950 if (!fs.existsSync(db)) {
00951 fs.mkdirSync(db);
00952 }
00953 if (!fs.existsSync(tmp)) {
00954 fs.mkdirSync(tmp);
00955 }
00956 if (!fs.existsSync(trash)) {
00957 fs.mkdirSync(trash);
00958 }
00959
00960 return { db: db, tmp: tmp, trash: trash };
00961 };
00962
00971 function VersionExists(entity, collection, version, dbConfig) {
00972 console.log("\"VersionExists\": { version:\"" + version + "\", entity:" + JSON.stringify(entity, null, 4) + ", collection: \"" + collection + "\"}");
00973 var query = {
00974 filter: {
00975 "entities.name": entity
00976 },
00977 collection: collection,
00978 dbprovider: dbConfig.dbprovider,
00979 operation: "findversions",
00980 dataformat: "gui"
00981 };
00982 var vers = Connector.RunGetVersionsQuery(dbConfig, query).search;
00983 console.log("Search returned: " + JSON.stringify(vers, null, 4));
00984 return Utils.ContainsName(vers, version, "name") >= 0;
00985 };
00986
00991 function Lock() {
00992 console.log("Lock");
00993 if (fs.existsSync("/tmp/node_db_lockfile")) {
00994 if (Date.now() - fs.fstatSync("/tmp/node_db_lockfile").ctime.getTime() > 1000) {
00995 console.log("Stale Lockfile detected, deleting...");
00996 return Unlock();
00997 } else {
00998 console.log("Lockfile detected and is not stale, aborting...");
00999 }
01000 return false;
01001 }
01002
01003 fs.writeFileSync("/tmp/node_db_lockfile", "locked");
01004 return true;
01005 }
01006
01011 function Unlock() {
01012 console.log("Unlock");
01013 fs.unlinkSync("/tmp/node_db_lockfile");
01014 return true;
01015 }
01016
01017
01018 db.RO_GetData = function (post, dbConfig) {
01019 console.log("RO_GetData: " + JSON.stringify(post, null, 4));
01020 var ret = { Success: false, data: {} };
01021 try {
01022 ret.data = GetData(post.configName, post.collection, post.entity, GetDirectories(post.user, dbConfig));
01023 ret.Success = true;
01024 } catch (e) {
01025 console.log("Exception occurred: " + e.name + ": " + e.message);
01026 }
01027
01028 console.log("GetData complete");
01029 return ret;
01030 };
01031
01032 db.RW_MakeNewConfig = function (post, dbConfig) {
01033 if (Lock()) {
01034 console.log("RW_MakeNewConfig: Request to make new configuration received: " + JSON.stringify(post, null, 4));
01035 var res = { Success: false };
01036 var error = false;
01037 var e;
01038 try {
01039 var configs = Connector.RunGetConfigsQuery(dbConfig).search;
01040 if (!Utils.ValidatePath(post.name)) {
01041 console.log("Invalid name detected!");
01042 error = true;
01043 }
01044 while (Utils.ContainsName(configs, post.name, "name") >= 0) {
01045 console.log("Inferring new configuration name");
01046 post.name = Utils.Uniquify(post.name);
01047 }
01048 } catch (e) {
01049 error = true;
01050 console.log("Exception occurred: " + e.name + ": " + e.message);
01051 }
01052 if (!error) {
01053 console.log("Creating Configuration");
01054 try {
01055 CreateNewConfiguration(post.name, JSON.parse(post.config), dbConfig);
01056 res.Success = true;
01057 } catch (e) {
01058 console.log("Exception occurred: " + e.name + ": " + e.message);
01059 }
01060 }
01061 Unlock();
01062 console.log("MakeNewConfig completed");
01063 return res;
01064 }
01065 return null;
01066 };
01067
01068 db.RW_saveConfig = function (post, dbConfig) {
01069 if (Lock()) {
01070 console.log("RW_saveConfig: Request to save configuration recieved. Configuration data: " + JSON.stringify(post, null, 4));
01071 var res = { Success: false };
01072 var error = false;
01073 var e;
01074 try {
01075 console.log("Checking for unique Configuration name");
01076 var configs = Connector.RunGetConfigsQuery(dbConfig).search;
01077 if (!Utils.ValidatePath(post.newConfigName) || Utils.ContainsName(configs, post.oldConfigName, "name") < 0) {
01078 console.log("Invalid name detected!");
01079 error = true;
01080 }
01081 while (Utils.ContainsName(configs, post.newConfigName, "name") >= 0) {
01082 console.log("Inferring new configuration name");
01083 post.newConfigName = Utils.Uniquify(post.newConfigName);
01084 }
01085 } catch (e) {
01086 error = true;
01087 console.log("Exception occurred: " + e.name + ": " + e.message);
01088 }
01089 if (!error) {
01090 try {
01091 console.log("Updating Configuration Files");
01092 SaveConfigurationChanges(post.oldConfigName, post.newConfigName, post.files, GetDirectories(post.user, dbConfig), dbConfig);
01093 res.Success = true;
01094 } catch (e) {
01095 console.log("Exception occurred: " + e.name + ": " + e.message);
01096 }
01097 }
01098 Unlock();
01099 console.log("SaveConfig completed");
01100 return res;
01101 }
01102 return null;
01103 };
01104
01105 db.RO_LoadNamedConfig = function (post, dbConfig) {
01106 console.log("RO_LoadNamedConfig: Request for configuration with name \"" + post.configName + "\" and search query \"" + post.query + "\" received.");
01107 if (post.query.length === 0 || post.configName === "No Configurations Found") {
01108 return { collections: [] };
01109 }
01110 return LoadConfigFiles(post.configName, GetDirectories(post.user, dbConfig), JSON.parse(post.query), dbConfig);
01111 };
01112
01113 db.RW_discardConfig = function (post, dbConfig) {
01114 console.log("RW_discardConfig: Discarding configuration with parameters: " + JSON.stringify(post, null, 4));
01115 DiscardWorkingDir(GetDirectories(post.user, dbConfig));
01116 return { Success: true };
01117 };
01118
01119 db.RO_AddOrUpdate = function (post, dbConfig) {
01120 console.log("RO_AddOrUpdate: Request to update table row recieved: " + JSON.stringify(post, null, 4));
01121 UpdateTable(post.configName, post.table, post.row, GetDirectories(post.user, dbConfig));
01122 return { Success: true };
01123 }
01124
01125 db.RO_Update = function (post, dbConfig) {
01126 console.log("RO_Update: Request to update table received: " + JSON.stringify(post, null, 4));
01127 UpdateTable(post.configName, post.table, { id: post.id, name: post.name, column: post.column, value: post.value }, GetDirectories(post.user, dbConfig));
01128 console.log("Update Complete");
01129 return { Success: true };
01130 };
01131
01132 db.RO_LoadConfigMetadata = function (post, dbConfig) {
01133 console.log("RO_LoadConfigMetadata: Request to load configuration metadata received: " + JSON.stringify(post, null, 4) + ", dbConfig: " + JSON.stringify(dbConfig, null, 4));
01134 var ret = { Success: false, data: {} };
01135 try {
01136 ret.data = ReadConfigurationMetadata(post.configName, GetDirectories(post.user, dbConfig), dbConfig);
01137 ret.Success = true;
01138 } catch (e) {
01139 console.log("Exception caught: " + e.name + ": " + e.message);
01140 }
01141 console.log("LoadConfigMetadata complete");
01142 return ret;
01143 };
01144
01145 db.RO_LoadFileMetadata = function (post, dbConfig) {
01146 console.log("RO_LoadFileMetadata: Request to load file metadata received: " + JSON.stringify(post, null, 4));
01147 var ret = { Success: false, data: {} };
01148 var dirs = GetDirectories(post.user, dbConfig);
01149 var error = false;
01150 var query = {};
01151 var e;
01152 try {
01153 var search = Connector.RunBuildFilterQuery(dbConfig, post.configName).search;
01154 for (var s in search) {
01155 if (search.hasOwnProperty(s)) {
01156 if (search[s].query.collection === post.collection && search[s].query.filter["entities.name"] === post.entity) {
01157 query = search[s];
01158 }
01159 }
01160 }
01161 } catch (e) {
01162 error = true;
01163 console.log("Exception caught: " + e.name + ": " + e.message);
01164 }
01165 if (!error) {
01166 try {
01167 ret.data = ReadFileMetadata(dirs, query, dbConfig);
01168 ret.Success = true;
01169 } catch (e) {
01170 console.log("Exception caught: " + e.name + ": " + e.message);
01171 }
01172 }
01173 console.log("LoadFileMetadata complete");
01174 return ret;
01175 };
01176
01177 db.RW_UploadConfigurationFile = function (post, dbConfig) {
01178 if (Lock()) {
01179 console.log("RW_UploadConfigurationFile: Recieved request to upload file: " + JSON.stringify(post, null, 4));
01180 var e;
01181 var error = false;
01182 var ret = { Success: false };
01183 try {
01184 while (VersionExists(post.entity, post.collection, post.version, dbConfig)) {
01185 console.log("Version already exists. Running uniquifier...");
01186 post.version = Utils.Uniquify(post.version);
01187 }
01188 } catch (e) {
01189 error = true;
01190 console.log("Exception caught: " + e.name + ": " + e.message);
01191 }
01192
01193 if (!error) {
01194 console.log("Running store fhicl query");
01195 try {
01196 Connector.RunStoreQuery(dbConfig, post.file, post.collection, post.version, post.entity, post.type);
01197 ret.Success = true;
01198 } catch (e) {
01199 console.log("Exception caught: " + e.name + ": " + e.message);
01200 }
01201 }
01202 Unlock();
01203 console.log("UploadConfigurationFile complete");
01204 return ret;
01205 }
01206 return null;
01207 };
01208
01209 db.RO_DownloadConfigurationFile = function (post, dbConfig) {
01210 console.log("RO_DownloadConfigurationFile: Request to download file(s) received: " + JSON.stringify(post, null, 4));
01211 var dirs = GetDirectories(post.user, dbConfig);
01212 var configObj = JSON.parse(post.config);
01213 try {
01214 if (configObj.entities.length === 1) {
01215 console.log("Single file mode: Fetching file...");
01216 var fileInfo = FetchFile(configObj.entities[0], post.type, dirs.db, dbConfig);
01217
01218 var fclhdrs = {
01219 'Content-Type': 'text/plain',
01220 'Content-Length': fileInfo.size,
01221 'Content-Disposition': 'attachment filename=' + fileInfo.fileName
01222 }
01223 console.log("Headers: " + JSON.stringify(fclhdrs, null, 4) + ", fileInfo: " + JSON.stringify(fileInfo, null, 4));
01224
01225 var fclStream = fs.createReadStream(fileInfo.filePath);
01226 db.emit("stream", fclStream, fclhdrs, 200);
01227 } else if (configObj.entities.length > 1) {
01228 var args = ['cz'];
01229 for (var e in configObj.entities) {
01230 if (configObj.entities.hasOwnProperty(e)) {
01231 args.push(FetchFile(configObj.entities[e], post.type, dirs.db, dbConfig).fileName);
01232 }
01233 }
01234 var fileName = post.tarFileName + ".tar.gz";
01235 var tarhdrs = {
01236 'Content-Type': "application/x-gzip",
01237 'Content-Disposition': 'attachment filename=' + fileName
01238 }
01239
01240 console.log("Spawning: tar " + args.join(" "));
01241 var tar = child_process.spawn("tar", args, { cwd: dirs.db, stdio: [0, 'pipe', 0] });
01242 db.emit("stream", tar.stdout, tarhdrs, 200);
01243
01244 }
01245 } catch (err) {
01246 console.log("Exception caught: " + err.name + ": " + err.message);
01247
01248 var s = new stream.Readable();
01249 s._read = function noop() { };
01250 s.push("ERROR");
01251 s.push(null);
01252
01253 var errhdrs = {
01254 'Content-Type': 'text/plain'
01255 }
01256 db.emit("stream", s, errhdrs, 500);
01257 }
01258
01259 };
01260
01261 db.RO_NamedConfigs = function (post, dbConfig) {
01262 console.log("RO_NamedConfigs: Request for Named Configurations received");
01263 var filter = "" + post.configFilter;
01264 return FindConfigs(filter, dbConfig);
01265 };
01266
01267 db.RW_updateDbConfig = function (post, dbConfig) {
01268 console.log("RW_updateDbConfig: Request to update module configuration received: " + JSON.stringify(post, null, 4));
01269 var output = { Success: false };
01270 if (fs.existsSync(post.baseDir) && (post.dbprovider === "filesystem" || post.dbprovider === "mongo")) {
01271 if (dbConfig.baseDir !== post.baseDir) {
01272 dbConfig.baseDir = post.baseDir;
01273 db.emit("message", { name: "db", target: "baseDir", data: post.baseDir });
01274 }
01275 if (dbConfig.dbprovider !== post.dbprovider) {
01276 dbConfig.dbprovider = post.dbprovider;
01277 db.emit("message", { name: "db", target: "dbprovider", data: post.dbprovider });
01278 }
01279 if (dbConfig.instanceName !== post.instanceName) {
01280 dbConfig.instanceName = post.instanceName;
01281 db.emit("message", { name: "db", target: "instanceName", data: post.instanceName });
01282 }
01283 console.log("DB Config is now: " + JSON.stringify(dbConfig, null, 4));
01284 output.Success = true;
01285 }
01286 return output;
01287 }
01288
01289 db.RO_SearchLoadedConfig = function (post, dbConfig) {
01290 console.log("RO_SearchLoadedConfig: Searching for keys containing name \"" + post.searchKey + "\" from configuration name \"" + post.configName + "\" received.");
01291 if (post.configName === "No Configurations Found") {
01292 return { Success: false, collections: [] };
01293 }
01294 return SearchConfigFiles(post.searchKey, post.configName, GetDirectories(post.user, dbConfig), dbConfig);
01295 }
01296
01297 db.RW_makeNewDBInstance = function (post, dbConfig) {
01298 console.log("RW_makeNewDBInstance: Creating new database instance \"" + post.name + "\".");
01299 dbConfig.instanceName = post.name;
01300 return { Success: true };
01301 }
01302
01303 db.RW_AddEntityToFile = function (post, dbConfig) {
01304 console.log("RW_AddEntityToFile: request to add entity name \"" + post.name + "\" to configuration file " + post.configName + "/" + post.collection + "/" + post.entity);
01305 return { Success: true };
01306 }
01307
01308
01309 db.GET_EntitiesAndVersions = function (dbConfig) {
01310 console.log("GET_EntitiesAndVersions: Request for current Entities and Versions received");
01311 var output = {
01312 Success: false,
01313 collections: []
01314 };
01315 try {
01316 var entities = Connector.RunGetEntitiesQuery(dbConfig).search;
01317 console.log("Returned entities: " + JSON.stringify(entities, null, 4));
01318 for (var ent in entities) {
01319 if (entities.hasOwnProperty(ent)) {
01320 var entity = entities[ent];
01321 var versions = Connector.RunGetVersionsQuery(dbConfig, entity.query);
01322 if (Utils.ContainsName(output.collections, entity.query.collection, "name") < 0) {
01323 output.collections.push({ name: entity.query.collection, entities: [] });
01324 }
01325
01326 var index = Utils.ContainsName(output.collections, entity.query.collection, "name");
01327
01328 var entityObj = {
01329 collection: entity.query.collection,
01330 name: entity.name,
01331 versions: versions
01332 };
01333 output.collections[index].entities.push(entityObj);
01334 }
01335 }
01336 output.Success = true;
01337 } catch (e) {
01338 console.log("Exception caught: " + e.name + ": " + e.message);
01339 }
01340 console.log("EntitiesAndVersions complete");
01341 return output;
01342 };
01343
01344 db.GET_getDbConfig = function (dbConfig) {
01345 console.log("GET_getDbConfig Request for Database Module Configuration received");
01346
01347 var instances = FindInstances(dbConfig);
01348 var output = {
01349 Success: true,
01350 baseDir: dbConfig.baseDir,
01351 dbprovider: dbConfig.dbprovider,
01352 instanceName: dbConfig.instanceName,
01353 data: instances.data
01354 };
01355 return output;
01356 }
01357
01358
01359 db.MasterInitFunction = function (workerData, config) {
01360 var dbConfig = MakeDbConfig(config);
01361 workerData["db"] = dbConfig;
01362 GetDirectories("", dbConfig);
01363 };
01364
01365 module.exports = function (moduleHolder) {
01366 moduleHolder["db"] = db;
01367 };