feat: separate Server and Client

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
MiaoWoo 2019-07-22 16:43:50 +08:00
parent 9c300cd191
commit da3afe1110
8 changed files with 186 additions and 177 deletions

View File

@ -1353,14 +1353,14 @@ export default class CConsensus extends CBlock {
var BlockMining = this.GetBlock(msg.BlockNum); var BlockMining = this.GetBlock(msg.BlockNum);
if (!BlockMining) { if (!BlockMining) {
teraManager.SendToWebClient({ teraManager.SendToWebClient({
msg: msg, BlockNum: msg.BlockNum,
error: '!BlockMining' error: '!BlockMining'
}) })
return; return;
} }
if (!BlockMining.StartMining || BlockMining.bSave) { if (!BlockMining.StartMining || BlockMining.bSave) {
teraManager.SendToWebClient({ teraManager.SendToWebClient({
msg: msg, BlockNum: msg.BlockNum,
error: `!BlockMining.StartMining ${BlockMining.StartMining} || BlockMining.bSave ${BlockMining.bSave}` error: `!BlockMining.StartMining ${BlockMining.StartMining} || BlockMining.bSave ${BlockMining.bSave}`
}) })
return; return;
@ -1414,7 +1414,7 @@ export default class CConsensus extends CBlock {
Object.assign(webmsg, { Object.assign(webmsg, {
HashCount, HashCount,
Power, Power,
Num: msg.NodeNum NodeNum: msg.NodeNum
}) })
teraManager.SendToWebClient(webmsg) teraManager.SendToWebClient(webmsg)
}, 1) }, 1)

View File

@ -35,9 +35,9 @@ const WorkStructHeader2 = {};
const DEFAULT_DB_VERSION = 2; const DEFAULT_DB_VERSION = 2;
import CCode from '../code' import CCode from '../code'
export default class CDB extends CCode { export default class CDB extends CCode {
DBHeader100 DBHeader100: DBRow
BlockNumDB BlockNumDB: number
BlockNumDBMin BlockNumDBMin: number
CurrentBlockNum CurrentBlockNum
CheckOnStartComplete CheckOnStartComplete
UseTruncateBlockDB UseTruncateBlockDB
@ -501,8 +501,7 @@ export default class CDB extends CCode {
bytesRead = fs.readSync(FileItem.fd, BufRead, 0, BufRead.length, Position) bytesRead = fs.readSync(FileItem.fd, BufRead, 0, BufRead.length, Position)
Block = global.BufLib.GetObjectFromBuffer(BufRead, FORMAT_STREAM_HEADER, WorkStructStreamHeader) Block = global.BufLib.GetObjectFromBuffer(BufRead, FORMAT_STREAM_HEADER, WorkStructStreamHeader)
if (Block.VersionDB !== global.DB_VERSION) { if (Block.VersionDB !== global.DB_VERSION) {
throw ("ERROR Block.VersionDB"); throw (`ERROR Position: ${Position} Block.VersionDB: ${Block.VersionDB}`);
return undefined;
} }
Block.FilePos = Position Block.FilePos = Position
Block.VersionDB = global.DB_VERSION Block.VersionDB = global.DB_VERSION

View File

@ -381,11 +381,12 @@ global.CreateEval = CreateEval;
var CPU_Count = os.cpus().length; var CPU_Count = os.cpus().length;
function GetCountMiningCPU() { function GetCountMiningCPU() {
if (global.COUNT_MINING_CPU) return global.COUNT_MINING_CPU
return global.COUNT_MINING_CPU; // if (global.COUNT_MINING_CPU)
else { // return global.COUNT_MINING_CPU;
return CPU_Count - 1; // else {
} // return CPU_Count - 1;
// }
}; };
global.GetCountMiningCPU = GetCountMiningCPU; global.GetCountMiningCPU = GetCountMiningCPU;
var AddTrMap: any = {}; var AddTrMap: any = {};

2
src/global.d.ts vendored
View File

@ -238,7 +238,7 @@ declare global {
//#region main-process.ts:375 //#region main-process.ts:375
MiningPaused: number; MiningPaused: number;
ArrMiningWrk: TeraChildProcess[]; ArrMiningWrk: any[];
//#endregion //#endregion
//#region library.ts:118 //#region library.ts:118

View File

@ -396,129 +396,141 @@ if (global.ADDRLIST_MODE) {
return; return;
} }
function AllAlive() { function AllAlive() {
for (var i = 0; i < global.ArrMiningWrk.length; i++) {
global.ArrMiningWrk[i].send({ cmd: "Alive", DELTA_CURRENT_TIME: global.DELTA_CURRENT_TIME });
}
teraManager.SendToClient({ cmd: "Alive", DELTA_CURRENT_TIME: global.DELTA_CURRENT_TIME }) teraManager.SendToClient({ cmd: "Alive", DELTA_CURRENT_TIME: global.DELTA_CURRENT_TIME })
// for (var i = 0; i < global.ArrMiningWrk.length; i++) {
// global.ArrMiningWrk[i].send({ cmd: "Alive", DELTA_CURRENT_TIME: global.DELTA_CURRENT_TIME });
// }
}; };
function ClearArrMining() { // function ClearArrMining() {
for (var i = 0; i < global.ArrMiningWrk.length; i++) { // for (var i = 0; i < global.ArrMiningWrk.length; i++) {
global.ArrMiningWrk[i].send({ cmd: "Exit" }); // global.ArrMiningWrk[i].send({ cmd: "Exit" });
} // }
global.ArrMiningWrk = []; // global.ArrMiningWrk = [];
}; // };
function RunStopPOWProcess(Mode) { function RunStopPOWProcess(Mode) {
if (!global.GetCountMiningCPU() || global.GetCountMiningCPU() <= 0)
return;
if (!StartCheckMining) { if (!StartCheckMining) {
StartCheckMining = 1; StartCheckMining = 1;
global.COUNT_MINING_CPU = 0
setInterval(RunStopPOWProcess, global.CHECK_RUN_MINING); setInterval(RunStopPOWProcess, global.CHECK_RUN_MINING);
setInterval(AllAlive, 1000); setInterval(AllAlive, 1000);
} }
if (global.NeedRestart) if (global.ArrMiningWrk.length != Object.keys(teraManager.pows).length) {
return; global.ArrMiningWrk = Object.keys(teraManager.pows)
if (global.USE_MINING && global.MINING_START_TIME && global.MINING_PERIOD_TIME) { global.COUNT_MINING_CPU = global.ArrMiningWrk.length
var Time = global.GetCurrentTime();
var TimeCur = Time.getUTCHours() * 3600 + Time.getUTCMinutes() * 60 + Time.getUTCSeconds();
var StartTime = global.GetSecFromStrTime(global.MINING_START_TIME);
var RunPeriod = global.GetSecFromStrTime(global.MINING_PERIOD_TIME);
var TimeEnd = StartTime + RunPeriod;
global.MiningPaused = 1;
if (TimeCur >= StartTime && TimeCur <= TimeEnd) {
global.MiningPaused = 0;
} else {
StartTime -= 24 * 3600;
TimeEnd -= 24 * 3600;
if (TimeCur >= StartTime && TimeCur <= TimeEnd) {
global.MiningPaused = 0;
}
}
if (global.ArrMiningWrk.length && global.MiningPaused) {
global.ToLog("------------ MINING MUST STOP ON TIME");
ClearArrMining();
return;
} else
if (!global.ArrMiningWrk.length && !global.MiningPaused) {
global.ToLog("*********** MINING MUST START ON TIME");
} else {
return;
}
} else {
global.MiningPaused = 0;
}
if (!global.USE_MINING || Mode === "STOP") {
ClearArrMining();
return;
}
if (global.USE_MINING && global.ArrMiningWrk.length)
return;
if (global.SERVER.LoadHistoryMode)
return;
if (global.GENERATE_BLOCK_ACCOUNT < 8)
return;
var PathMiner = global.GetCodePath("../miner.js");
if (!fs.existsSync(PathMiner))
PathMiner = "./process/pow-process.js";
if (global.ArrMiningWrk.length >= global.GetCountMiningCPU())
return;
if (global.GrayConnect()) {
global.ToLog("CANNOT START MINER IN NOT DIRECT IP MODE");
return;
}
var Memory;
if (global.SIZE_MINING_MEMORY)
Memory = global.SIZE_MINING_MEMORY;
else {
Memory = os.freemem() - (512 + global.GetCountMiningCPU() * 100) * 1024 * 1014;
if (Memory < 0) {
global.ToLog("Not enough memory to start processes.");
return;
}
}
ProcessMemorySize = Math.trunc(Memory / global.GetCountMiningCPU());
global.ToLog("START MINER PROCESS COUNT: " + global.GetCountMiningCPU() + " Memory: " + ProcessMemorySize / 1024 / 1024 + " Mb for each process");
for (var R = 0; R < global.GetCountMiningCPU(); R++) {
let Worker = Fork(PathMiner);
global.ArrMiningWrk.push(Worker);
Worker.Num = global.ArrMiningWrk.length;
Worker.on('message', function(msg) {
if (msg.cmd === "log") {
global.ToLog(msg.message);
} else {
if (msg.cmd === "online") {
Worker.bOnline = true;
global.ToLog("RUNNING PROCESS:" + Worker.Num + ":" + msg.message);
} else {
if (msg.cmd === "POW") {
global.SERVER.MiningProcess(msg);
} else {
if (msg.cmd === "HASHRATE") {
global.ADD_HASH_RATE(msg.CountNonce);
}
}
}
}
});
Worker.on('error', function(err) {
if (!global.ArrMiningWrk.length)
return;
global.ToError('ERROR IN PROCESS: ' + err);
});
Worker.on('close', function(code) {
global.ToLog("STOP PROCESS: " + Worker.Num + " pid:" + Worker.pid);
for (var i = 0; i < global.ArrMiningWrk.length; i++) {
if (global.ArrMiningWrk[i].pid === Worker.pid) {
global.ToLog("Delete wrk from arr - pid:" + Worker.pid);
global.ArrMiningWrk.splice(i, 1);
}
}
});
} }
// if (!global.GetCountMiningCPU() || global.GetCountMiningCPU() <= 0)
// return;
// if (!StartCheckMining) {
// StartCheckMining = 1;
// setInterval(RunStopPOWProcess, global.CHECK_RUN_MINING);
// setInterval(AllAlive, 1000);
// }
// if (global.NeedRestart)
// return;
// if (global.USE_MINING && global.MINING_START_TIME && global.MINING_PERIOD_TIME) {
// var Time = global.GetCurrentTime();
// var TimeCur = Time.getUTCHours() * 3600 + Time.getUTCMinutes() * 60 + Time.getUTCSeconds();
// var StartTime = global.GetSecFromStrTime(global.MINING_START_TIME);
// var RunPeriod = global.GetSecFromStrTime(global.MINING_PERIOD_TIME);
// var TimeEnd = StartTime + RunPeriod;
// global.MiningPaused = 1;
// if (TimeCur >= StartTime && TimeCur <= TimeEnd) {
// global.MiningPaused = 0;
// } else {
// StartTime -= 24 * 3600;
// TimeEnd -= 24 * 3600;
// if (TimeCur >= StartTime && TimeCur <= TimeEnd) {
// global.MiningPaused = 0;
// }
// }
// if (global.ArrMiningWrk.length && global.MiningPaused) {
// global.ToLog("------------ MINING MUST STOP ON TIME");
// ClearArrMining();
// return;
// } else
// if (!global.ArrMiningWrk.length && !global.MiningPaused) {
// global.ToLog("*********** MINING MUST START ON TIME");
// } else {
// return;
// }
// } else {
// global.MiningPaused = 0;
// }
// if (!global.USE_MINING || Mode === "STOP") {
// ClearArrMining();
// return;
// }
// if (global.USE_MINING && global.ArrMiningWrk.length)
// return;
// if (global.SERVER.LoadHistoryMode)
// return;
// if (global.GENERATE_BLOCK_ACCOUNT < 8)
// return;
// var PathMiner = global.GetCodePath("../miner.js");
// if (!fs.existsSync(PathMiner))
// PathMiner = "./process/pow-process.js";
// if (global.ArrMiningWrk.length >= global.GetCountMiningCPU())
// return;
// if (global.GrayConnect()) {
// global.ToLog("CANNOT START MINER IN NOT DIRECT IP MODE");
// return;
// }
// var Memory;
// if (global.SIZE_MINING_MEMORY)
// Memory = global.SIZE_MINING_MEMORY;
// else {
// Memory = os.freemem() - (512 + global.GetCountMiningCPU() * 100) * 1024 * 1014;
// if (Memory < 0) {
// global.ToLog("Not enough memory to start processes.");
// return;
// }
// }
// ProcessMemorySize = Math.trunc(Memory / global.GetCountMiningCPU());
// global.ToLog("START MINER PROCESS COUNT: " + global.GetCountMiningCPU() + " Memory: " + ProcessMemorySize / 1024 / 1024 + " Mb for each process");
// for (var R = 0; R < global.GetCountMiningCPU(); R++) {
// let Worker = Fork(PathMiner);
// global.ArrMiningWrk.push(Worker);
// Worker.Num = global.ArrMiningWrk.length;
// Worker.on('message', function(msg) {
// if (msg.cmd === "log") {
// global.ToLog(msg.message);
// } else {
// if (msg.cmd === "online") {
// Worker.bOnline = true;
// global.ToLog("RUNNING PROCESS:" + Worker.Num + ":" + msg.message);
// } else {
// if (msg.cmd === "POW") {
// global.SERVER.MiningProcess(msg);
// } else {
// if (msg.cmd === "HASHRATE") {
// global.ADD_HASH_RATE(msg.CountNonce);
// }
// }
// }
// }
// });
// Worker.on('error', function(err) {
// if (!global.ArrMiningWrk.length)
// return;
// global.ToError('ERROR IN PROCESS: ' + err);
// });
// Worker.on('close', function(code) {
// global.ToLog("STOP PROCESS: " + Worker.Num + " pid:" + Worker.pid);
// for (var i = 0; i < global.ArrMiningWrk.length; i++) {
// if (global.ArrMiningWrk[i].pid === Worker.pid) {
// global.ToLog("Delete wrk from arr - pid:" + Worker.pid);
// global.ArrMiningWrk.splice(i, 1);
// }
// }
// });
// }
}; };
function SetCalcPOW(Block, cmd) { function SetCalcPOW(Block, cmd) {
if (!global.USE_MINING)
return;
teraManager.SendToClient({ teraManager.SendToClient({
cmd: cmd, cmd: cmd,
BlockNum: Block.BlockNum, BlockNum: Block.BlockNum,
@ -530,36 +542,32 @@ function SetCalcPOW(Block, cmd) {
Time: Date.now(), Time: Date.now(),
RunPeriod: global.POWRunPeriod, RunPeriod: global.POWRunPeriod,
RunCount: global.POW_RUN_COUNT, RunCount: global.POW_RUN_COUNT,
Percent: global.POW_MAX_PERCENT, Percent: global.POW_MAX_PERCENT
CountMiningCPU: global.GetCountMiningCPU(),
ProcessMemorySize: ProcessMemorySize,
}) })
if (!global.USE_MINING) // if (global.ArrMiningWrk.length !== global.GetCountMiningCPU())
return; // return;
if (global.ArrMiningWrk.length !== global.GetCountMiningCPU()) // BlockMining = Block;
return; // for (var i = 0; i < global.ArrMiningWrk.length; i++) {
BlockMining = Block; // var CurWorker = global.ArrMiningWrk[i];
for (var i = 0; i < global.ArrMiningWrk.length; i++) { // if (!CurWorker.bOnline)
var CurWorker = global.ArrMiningWrk[i]; // continue;
if (!CurWorker.bOnline) // CurWorker.send({
continue; // cmd: cmd,
CurWorker.send({ // BlockNum: Block.BlockNum,
cmd: cmd, // Account: global.GENERATE_BLOCK_ACCOUNT,
BlockNum: Block.BlockNum, // MinerID: global.GENERATE_BLOCK_ACCOUNT,
Account: global.GENERATE_BLOCK_ACCOUNT, // SeqHash: Block.SeqHash,
MinerID: global.GENERATE_BLOCK_ACCOUNT, // Hash: Block.Hash,
SeqHash: Block.SeqHash, // PrevHash: Block.PrevHash,
Hash: Block.Hash, // Time: Date.now(),
PrevHash: Block.PrevHash, // Num: CurWorker.Num,
Time: Date.now(), // RunPeriod: global.POWRunPeriod,
Num: CurWorker.Num, // RunCount: global.POW_RUN_COUNT,
RunPeriod: global.POWRunPeriod, // Percent: global.POW_MAX_PERCENT,
RunCount: global.POW_RUN_COUNT, // CountMiningCPU: global.GetCountMiningCPU(),
Percent: global.POW_MAX_PERCENT, // ProcessMemorySize: ProcessMemorySize,
CountMiningCPU: global.GetCountMiningCPU(), // });
ProcessMemorySize: ProcessMemorySize, // }
});
}
}; };
global.SetCalcPOW = SetCalcPOW; global.SetCalcPOW = SetCalcPOW;
global.RunStopPOWProcess = RunStopPOWProcess; global.RunStopPOWProcess = RunStopPOWProcess;

View File

@ -42,23 +42,6 @@ PROCESS.on('message', function(msg) {
} }
}) })
import { powClient } from '../rpc/client'
powClient.on('message', (msg) => {
LastAlive = Date.now();
switch (msg.cmd) {
case "FastCalcBlock":
FastCalcBlock(msg);
break;
case "Alive":
global.DELTA_CURRENT_TIME = msg.DELTA_CURRENT_TIME;
break;
case "Exit":
PROCESS.exit(0);
}
})
powClient.connect()
function FastCalcBlock(msg) { function FastCalcBlock(msg) {
var FastBlock = msg; var FastBlock = msg;
StartHashPump(FastBlock); StartHashPump(FastBlock);
@ -75,7 +58,7 @@ function FastCalcBlock(msg) {
Hash: FastBlock.Hash, Hash: FastBlock.Hash,
PowHash: FastBlock.PowHash, PowHash: FastBlock.PowHash,
AddrHash: FastBlock.AddrHash, AddrHash: FastBlock.AddrHash,
Num: FastBlock.NodeNum NodeNum: FastBlock.NodeNum
}); });
} }
} catch (e) { } catch (e) {
@ -129,8 +112,8 @@ function PumpHash() {
EndTime = CurTime; EndTime = CurTime;
return; return;
} }
global.BlockPump.LastNonce = global.BlockPump.LastNonce + global.BlockPump.Num * 200000 global.BlockPump.LastNonce = global.BlockPump.LastNonce + global.BlockPump.NodeNum * 200000
global.BlockPump.LastNonce0 = global.BlockPump.LastNonce0 + global.BlockPump.Num * 200000 global.BlockPump.LastNonce0 = global.BlockPump.LastNonce0 + global.BlockPump.NodeNum * 200000
CreatePOWVersionX(global.BlockPump, 1); CreatePOWVersionX(global.BlockPump, 1);
} else { } else {
var Delta = CurTime - EndTime; var Delta = CurTime - EndTime;
@ -140,3 +123,24 @@ function PumpHash() {
} }
} }
}; };
import { powClient } from '../rpc/client'
powClient.on('disconnect', (error) => {
console.log(`Client disconnect Error: ${error}...`)
clearInterval(idIntervalPump)
idIntervalPump = undefined
});
powClient.on('message', (msg) => {
LastAlive = Date.now();
switch (msg.cmd) {
case "FastCalcBlock":
FastCalcBlock(msg);
break;
case "Alive":
global.DELTA_CURRENT_TIME = msg.DELTA_CURRENT_TIME;
break;
case "Exit":
PROCESS.exit(0);
}
})
powClient.connect()

View File

@ -14,10 +14,6 @@ powClient.on('connect', () => {
powClient.send({ cmd: "online", message: "OK" }) powClient.send({ cmd: "online", message: "OK" })
}); });
powClient.on('disconnect', (error) => {
console.log(`Client disconnect Error: ${error}...`)
});
function SendToWebClient(msg: any) { function SendToWebClient(msg: any) {
powClient.emit('web', msg) powClient.emit('web', msg)
} }

View File

@ -1,5 +1,6 @@
let thread = parseInt(process.env.TERA_THREAD) || 1; let thread = parseInt(process.env.TERA_THREAD) || 1;
let Memory = thread * 4 * 1024 * 1024 * 1024 let threadMemory = parseInt(process.env.TERA_THREAD_MEMORY) || 4;
let Memory = thread * threadMemory * 1024 * 1024 * 1024
let ProcessMemorySize = Math.trunc(Memory / thread); let ProcessMemorySize = Math.trunc(Memory / thread);
import { fork } from 'child_process' import { fork } from 'child_process'
import './core/constant' import './core/constant'