提交 1e162fa4 authored 作者: blu's avatar blu

event notifier rev1: new issues interface and a set of utilities, preparing for rev2

上级 ab66cd7b
......@@ -209,10 +209,11 @@ int saveLocalConfigration(json &config, string fileName)
// }
// write prettified JSON file
try{
try {
std::ofstream o(fileName);
o << std::setw(4) << config << std::endl;
}catch(exception &e) {
}
catch(exception &e) {
spdlog::error("saveLocalConfigration failed to write configuration to file {}: {}\n{}", fileName, e.what(), config.dump());
return -2;
}
......
......@@ -3,10 +3,12 @@
#include <string>
using namespace std;
double getDiskAvailPercent(string path) {
double getDiskAvailPercent(string path)
{
struct statvfs fiData;
if((statvfs(path.c_str(),&fiData)) < 0 ) {
} else {
}
else {
double fper = fiData.f_bavail/double(fiData.f_blocks);
cout << fper << endl;
return fper;
......
......@@ -49,7 +49,7 @@ int downloadFile(string fileUrl, string outUrl)
/* write the page body to this file handle */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
auto res = curl_easy_perform(curl);
if(res != CURLE_OK){
if(res != CURLE_OK) {
spdlog::error("failed to upload files: {}", curl_easy_strerror(res));
return -1;
}
......
......@@ -55,7 +55,8 @@ private:
json allIssues;
json buildIssuesForIpc(string ipcSn, json &v){
json buildIssuesForIpc(string ipcSn, json &v)
{
json ret;
auto now = chrono::duration_cast<chrono::seconds>(chrono::system_clock::now().time_since_epoch()).count();
// check mgr status first
......@@ -72,31 +73,33 @@ private:
)"_json;
data["time"] = now;
bool hasIssue = false;
if(v.count("mgrTerminal") == 0|| v["mgrTerminal"].size() == 0||v["mgrTerminal"].count("online") == 0){
if(v.count("mgrTerminal") == 0|| v["mgrTerminal"].size() == 0||v["mgrTerminal"].count("online") == 0) {
data["catId"] = "AV_NO_CONFIG";
data["msg"] = "no configuratoin";
hasIssue = true;
}else{
if(!v["mgrTerminal"]["online"].get<bool>()){
}
else {
if(!v["mgrTerminal"]["online"].get<bool>()) {
data["msg"] = fmt::format(data["msg"].get<string>(), v["mgrTerminal"]["sn"].get<string>(), ipcSn);
hasIssue = true;
}
}
if(hasIssue){
if(ret.count(data["catId"].get<string>()) == 0){
if(hasIssue) {
if(ret.count(data["catId"].get<string>()) == 0) {
ret[data["catId"].get<string>()] = data;
}
}else{
}
else {
// check runtime issues
if(v.count("issues") != 0 && v["issues"].size() != 0){
for(auto &[m,n]: v["issues"].items()){
if(v.count("issues") != 0 && v["issues"].size() != 0) {
for(auto &[m,n]: v["issues"].items()) {
auto modId = m;
for(auto &[i,j]: n.items()){
for(auto &[i,j]: n.items()) {
auto catId = i;
auto data = j;
if(catId != EV_MSG_REPORT_CATID_AVMODOFFLINE) {
if(ret.count(catId) == 0){
if(ret.count(catId) == 0) {
ret[catId] = data;
}
}
......@@ -109,7 +112,8 @@ private:
}
void storeReportMsg(string selfId, string ipcSn, json &ipcStatus, string catId, string msg, bool active){
void storeReportMsg(string selfId, string ipcSn, json &ipcStatus, string catId, string msg, bool active)
{
json data;
data["msg"] = msg;
data["modId"] = "ALL";
......@@ -122,10 +126,11 @@ private:
if(ipcStatus["issues"].count(selfId) == 0) {
ipcStatus["issues"][selfId] = json();
}
if(active){
if(active) {
ipcStatus["issues"][selfId][catId] = data;
}else{
if(ipcStatus["issues"][selfId].count(catId) != 0){
}
else {
if(ipcStatus["issues"][selfId].count(catId) != 0) {
ipcStatus["issues"][selfId].erase(catId);
}
}
......@@ -762,7 +767,7 @@ private:
if(peerData["ipcStatus"].count(ipcSn) != 0) {
auto &ipcStatus = peerData["ipcStatus"][ipcSn];
if(ipcStatus.count("mgrTerminal") == 0){
if(ipcStatus.count("mgrTerminal") == 0) {
ipcStatus["mgrTerminal"] = json();
ipcStatus["mgrTerminal"]["sn"] = peerId;
ipcStatus["mgrTerminal"]["online"] = true;
......@@ -811,19 +816,19 @@ private:
}
auto issues = buildIssuesForIpc(ipcSn, ipcStatus);
if(allIssues.count(ipcSn) == 0){
if(allIssues.count(ipcSn) == 0) {
allIssues[ipcSn] = json();
}
bool report = false;
if(issues.size() > 0){
for(auto &[kk,vv]: issues.items()){
if(issues.size() > 0) {
for(auto &[kk,vv]: issues.items()) {
if(allIssues[ipcSn].count(kk) == 0) {
report = true;
break;
}
}
}
if(report){
if(report) {
/// TODO:
}
......@@ -1580,11 +1585,11 @@ public:
lock_guard<recursive_mutex> lg(mutIpcStatus);
if(this->peerData["ipcStatus"].count(sn) != 0) {
auto dsn = this->peerData["ipcStatus"][sn]["mgrTerminal"]["sn"].get<string>();
if(this->peerData["ipcStatus"][sn]["mgrTerminal"]["online"].get<bool>()){
if(this->peerData["ipcStatus"][sn]["mgrTerminal"]["online"].get<bool>()) {
// online
json j = getConfigForDevice(dsn);
if(j["code"] == 0) {
for(auto &[k,v]:j["data"].items()){
for(auto &[k,v]:j["data"].items()) {
auto &ipcs = v["ipcs"];
for(auto &ipc: ipcs) {
if(ipc["sn"] == sn) {
......@@ -1605,11 +1610,13 @@ public:
payload["data"]["start"] = start;
payload["data"]["end"] = end;
ret = this->handleCmd(payload);
}else{
}
else {
ret["code"] = 3;
ret["msg"] = dsn + " invalid config for slicer";
}
}else{
}
else {
// offline
ret["code"] = 2;
ret["msg"] = dsn + " terminal off line";
......@@ -1766,11 +1773,11 @@ public:
lock_guard<recursive_mutex> lg(mutIpcStatus);
json &ipcStatus = peerData["ipcStatus"];
json ret;
for(auto &[k,v]: ipcStatus.items()){
for(auto &[k,v]: ipcStatus.items()) {
auto ipcSn = k;
//
auto r = buildIssuesForIpc(k, v);
if(r.size() > 0){
if(r.size() > 0) {
ret[ipcSn] = r;
}
}
......
......@@ -457,12 +457,13 @@ private:
int ret = 0;
meta["type"] = EV_MSG_META_TYPE_CMD;
meta["value"] = cmdVal;
if(msg == "0"){
if(msg == "0") {
auto sp = strutils::split(peerId, ':');
if(sp.size() == 3){
if(sp.size() == 3) {
system((string("pkill -9 ") + sp[1]).c_str());
}
}else{
}
else {
ret = z_send(pRouter, peerId, this->daemonId, meta, msg);
if(ret < 0) {
spdlog::error("evdaemon {} failed to send msg to peer {}: {} - {}", devSn, peerId, meta.dump(), msg);
......@@ -786,7 +787,8 @@ private:
if(v.size() == 1) {
if(data["metaValue"] == EV_MSG_META_VALUE_CMD_REVESETUN) {
manageReverseTun(true, data["data"]);
}else if(data["metaValue"] == EV_MSG_META_VALUE_CMD_UPDATE){
}
else if(data["metaValue"] == EV_MSG_META_VALUE_CMD_UPDATE) {
//
}
else {
......@@ -1085,8 +1087,8 @@ public:
});
thHeartBeat.detach();
thSubMonitor = thread([this](){
while(true){
thSubMonitor = thread([this]() {
while(true) {
{
unique_lock<mutex> lk(this->mutSubMonitor);
this->cvSubMonitor.wait(lk, [this] {return !this->bColdStart;});
......@@ -1170,7 +1172,7 @@ public:
#define EV_WATCHDOG_STOP uint8_t(0xFD)
class EvWatchDog {
private:
private:
int fd_dog = 0;
string tty;
bool disabled = false;
......@@ -1197,7 +1199,7 @@ class EvWatchDog {
cfsetospeed(&tio,B115200); // 115200 baud
//cfsetispeed(&tio,B115200);
if(-1 == tcsetattr(tty_fd,TCSANOW,&tio)){
if(-1 == tcsetattr(tty_fd,TCSANOW,&tio)) {
spdlog::error("evdaemon failed to set tty {}", tty);
return -1;
}
......@@ -1205,7 +1207,8 @@ class EvWatchDog {
return tty_fd;
}
int watchdog_feed(int fd, uint8_t intervalMs){
int watchdog_feed(int fd, uint8_t intervalMs)
{
if(fd <=0) {
spdlog::error("evdaemon invalid watchdog fd");
return -1;
......@@ -1213,19 +1216,22 @@ class EvWatchDog {
uint8_t check = ~intervalMs;
uint8_t data[] = {0xFE, 0xFE, intervalMs, check, 0xEF};
spdlog::debug("evdaemon feed watch dog: {}, {}", intervalMs, check);
if( -1 == write(fd,data,5)){
if( -1 == write(fd,data,5)) {
spdlog::error("evdaemon failed to write watchdog fd");
return -1;
}else{
}
else {
return 0;
}
}
int _EV_WATCHDOG_STOP(int fd){
int _EV_WATCHDOG_STOP(int fd)
{
return watchdog_feed(fd, EV_WATCHDOG_STOP);
}
int watchdog_close(int fd) {
int watchdog_close(int fd)
{
spdlog::info("evdaemon disabling watch dog..");
if(fd > 0) {
_EV_WATCHDOG_STOP(fd);
......@@ -1233,17 +1239,19 @@ class EvWatchDog {
}
return 0;
}
public:
public:
EvWatchDog() = delete;
EvWatchDog(string tty):tty(tty){
EvWatchDog(string tty):tty(tty)
{
if((fd_dog = watchdog_init(tty)) < 0) {
spdlog::error("evdaemon can't open watchdog tty, ignore watchdog");
fd_dog = 0;
}
}
thread run(){
thread th = thread([this](){
thread run()
{
thread th = thread([this]() {
uint8_t intval = 10;
if(this->fd_dog > 0) {
while(!this->disabled) {
......@@ -1252,14 +1260,16 @@ class EvWatchDog {
}
watchdog_close(this->fd_dog);
this->fd_dog = 0;
}else{
}
else {
this->fd_dog = 0;
}
});
return th;
}
void stop(){
void stop()
{
if(fd_dog > 0 && !disabled) {
disabled = true;
while(fd_dog != 0) {
......@@ -1296,7 +1306,7 @@ int main()
signal(SIGKILL, cleanup);
thread t = gWatchDog.run();
if(t.joinable()){
if(t.joinable()) {
t.detach();
}
//sigignore(SIGCHLD);
......
......@@ -396,7 +396,7 @@ public:
spdlog::info("{} boot", devSn);
SingletonProcess self(selfName, 0);
if(!self()){
if(!self()) {
spdlog::error("{} already running. ignore this instance", selfName);
exit(0);
}
......
......@@ -325,7 +325,8 @@ private:
detPara.resize = evmlmotion["resize"];
if(detPara.resize < 0.001) {
detPara.resize = 0;
}else if (detPara.resize > 0.99) {
}
else if (detPara.resize > 0.99) {
detPara.resize = 1;
}
}
......@@ -342,12 +343,13 @@ private:
if(region.count("minX") == 0|| !region["minX"].is_number() ||
region.count("minY") == 0||!region["minY"].is_number() ||
region.count("maxX") == 0||!region["maxX"].is_number() ||
region.count("maxY") == 0||!region["maxY"].is_number()){
region.count("maxY") == 0||!region["maxY"].is_number()) {
spdlog::error("{} invalid region config: format. ignored", selfId);
}else{
}
else {
cv::Point2f p1, p2;
const float EVML_MARGIN_F = 0.0001;
try{
try {
p1.x = region["minX"].get<float>();
p1.y = region["minY"].get<float>();
p2.x = region["maxX"].get<float>();
......@@ -356,16 +358,19 @@ private:
if(p1.x < 0 || p1.x>=1 || p1.y <=0 || p1.y > 1||
p2.x <=0 || p2.x > 1 || p2.y <=0 || p2.y >1 || p1.x >= p2.x || p1.y >= p2.y) {
spdlog::error("{} invalid region config: invalid value range. ignored", selfId);
}else{
}
else {
detPara.region[0] = p1;
detPara.region[1] = p2;
spdlog::info("{} region: {} {}, {} {}", selfId, p1.x, p1.y, p2.x, p2.y);
}
}catch(exception &e) {
}
catch(exception &e) {
spdlog::error("{} failed to parse regoin config: {}. ignored", selfId, e.what());
}
}
}else{
}
else {
spdlog::error("{} no/invalid region config. ignored", selfId);
}
......@@ -620,22 +625,25 @@ private:
// auto config
if(detPara.resize == 0) {
detPara.resize = detPara.size*1.0/h;
}else{
}
else {
detPara.size = int(h * detPara.resize);
}
if(detPara.resize > 0 && detPara.resize < 1){
if(detPara.resize > 0 && detPara.resize < 1) {
// resize. new w, h caculated
w = int(w * detPara.resize);
h = int(h * detPara.resize);
cv::resize(origin, origin, cv::Size(w,h));
}else{
}
else {
detPara.resize = 1;
}
if(detPara.region[0].y == 0 || (detPara.region[0].x == 0 && detPara.region[0].y == 0 && detPara.region[1].x == 1 && detPara.region[1].y == 1)) {
// do nothing
}else {
}
else {
// crop
auto x = (int)(w * detPara.region[0].x);
auto y = (int)(h * detPara.region[0].y);
......@@ -716,13 +724,14 @@ private:
long long dura = 0;
if(evtStartTmLast != 0) {
dura = packetTm - evtStartTmLast;
}else{
}
else {
evtStartTmLast = packetTm;
return;
}
static long long pktDelt = 0;
if(pktCnt %18 == 0){
if(pktCnt %18 == 0) {
auto tmp = chrono::duration_cast<chrono::seconds>(chrono::system_clock::now().time_since_epoch()).count();
pktDelt = tmp - packetTm;
}
......@@ -741,7 +750,8 @@ private:
// spdlog::info("state: NONE->NONE ({}, {}, {}, {}, {}, {})", this->fps, dura, frameProcessed, evtCnt, thr, _area);
// }
spdlog::info("state: NONE->NONE ({}, {}, {}, {}, {}, {}, {})", pktDelt, this->fps, dura, frameProcessed, evtCnt, thr, _area);
}else{
}
else {
// if(evtState == PRE) {
// json p;
// evtState = IN;
......@@ -776,12 +786,14 @@ private:
evtCnt = 0;
frameProcessed = 0;
evtStartTmLast = packetTm;
}else if(dura >= detPara.post/2){
}
else if(dura >= detPara.post/2) {
auto thr = frameProcessed/5;
if(evtCnt <= thr){
if(evtCnt <= thr) {
evtState = POST;
spdlog::info("{} state: IN->POST ({}, {}, {}, {}, {}, {}, {})", selfId, pktDelt, this->fps, dura, frameProcessed, evtCnt, thr, _area);
}else{
}
else {
spdlog::info("{} state: IN->IN ({}, {}, {}, {}, {}, {}, {})", selfId, pktDelt, this->fps, dura, frameProcessed, evtCnt, thr, _area);
}
evtCnt = 0;
......@@ -791,13 +803,14 @@ private:
break;
}
case POST: {
if(dura >= detPara.post/2){
if(dura >= detPara.post/2) {
auto thr = frameProcessed/5;
if(evtCnt <= thr){
if(evtCnt <= thr) {
spdlog::info("{} state: POST->NONE ({}, {}, {}, {}, {}, {}, {})",selfId, pktDelt, this->fps, dura, frameProcessed, evtCnt, thr, _area);
evtState = NONE;
makeEvent(EV_MSG_EVENT_MOTION_END, packetTs - detPara.post/2);
}else{
}
else {
spdlog::info("{} state: POST->IN ({}, {}, {}, {}, {}, {}, {})",selfId, pktDelt, this->fps, dura, frameProcessed, evtCnt, thr, _area);
evtState = IN;
}
......@@ -916,7 +929,7 @@ protected:
static int _fpsDetectCnt = 0;
static auto _pts = packet.pts;
if(pAVFormatInput->streams[packet.stream_index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && (this->fps == 0|| pktCnt % 250 == 0)){
if(pAVFormatInput->streams[packet.stream_index]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && (this->fps == 0|| pktCnt % 250 == 0)) {
// static auto num = pAVFormatInput->streams[packet.stream_index]->time_base.num;s
// static auto den = pAVFormatInput->streams[packet.stream_index]->time_base.den;
// _fpsDetectCnt++;
......@@ -1040,7 +1053,7 @@ public:
spdlog::info("evmlmotion {} boot", selfId);
SingletonProcess self(selfName, iid);
if(!self()){
if(!self()) {
spdlog::error("{} already running. ignore this instance", selfId);
exit(0);
}
......@@ -1054,24 +1067,26 @@ public:
}
// setup heath checker
thHealdChecker = thread([this]{
thHealdChecker = thread([this] {
int cnt = 0;
uint64_t pktCntLast = pktCnt;
while(true){
while(true)
{
if(cnt >=3) {
kill(getpid(), SIGTERM);
exit(1);
}
this_thread::sleep_for(chrono::seconds(30));
if(pktCntLast == pktCnt){
if(pktCntLast == pktCnt) {
cnt++;
}else{
}
else {
pktCntLast = pktCnt;
cnt = 0;
}
}
});
if(thHealdChecker.joinable()){
if(thHealdChecker.joinable()) {
thHealdChecker.detach();
}
......
......@@ -302,9 +302,10 @@ private:
}
unique_lock<mutex> lk(this->mutMsg);
bool got = this->cvMsg.wait_for(lk, 30s, [this] {return this->gotFormat;});
if(got){
if(got) {
}else{
}
else {
// restart
spdlog::error("{} failed wait for avformatctx for {}s, restart", devSn, 30);
exit(1);
......@@ -623,7 +624,7 @@ public:
spdlog::info("{} boot", selfId);
SingletonProcess self(selfName, iid);
if(!self()){
if(!self()) {
spdlog::error("{} already running. ignore this instance", selfId);
exit(0);
}
......@@ -637,24 +638,26 @@ public:
}
// setup heath checker
thHealdChecker = thread([this]{
thHealdChecker = thread([this] {
int cnt = 0;
uint64_t pktCntLast = pktCnt;
while(true){
while(true)
{
if(cnt >=3) {
kill(getpid(), SIGTERM);
exit(1);
}
this_thread::sleep_for(chrono::seconds(30));
if(pktCntLast == pktCnt){
if(pktCntLast == pktCnt) {
cnt++;
}else{
}
else {
pktCntLast = pktCnt;
cnt = 0;
}
}
});
if(thHealdChecker.joinable()){
if(thHealdChecker.joinable()) {
thHealdChecker.detach();
}
......
......@@ -196,7 +196,8 @@ private:
}
bProcessed = true;
spdlog::info("{} debug:record event enqueued: {}", selfId, evt.dump());
}else{
}
else {
spdlog::error("{} debug:record format error: {}", selfId, body.dump());
}
}
......@@ -451,9 +452,10 @@ private:
}
unique_lock<mutex> lk(this->mutMsg);
bool got = this->cvMsg.wait_for(lk, 30s, [this] {return this->gotFormat;});
if(got){
if(got) {
}else{
}
else {
// restart
spdlog::error("{} failed wait for avformatctx for {}s, restart", devSn, 30);
exit(1);
......@@ -945,7 +947,7 @@ public:
spdlog::info("{} boot", selfId);
//TODO: single process
SingletonProcess self(selfName, iid);
if(!self()){
if(!self()) {
spdlog::error("{} already running. ignore this instance", selfId);
exit(0);
}
......@@ -961,24 +963,26 @@ public:
// health checker
// setup heath checker
thHealdChecker = thread([this]{
thHealdChecker = thread([this] {
int cnt = 0;
uint64_t pktCntLast = pktCnt;
while(true){
while(true)
{
if(cnt >=3) {
kill(getpid(), SIGTERM);
exit(1);
}
this_thread::sleep_for(chrono::seconds(30));
if(pktCntLast == pktCnt){
if(pktCntLast == pktCnt) {
cnt++;
}else{
}
else {
pktCntLast = pktCnt;
cnt = 0;
}
}
});
if(thHealdChecker.joinable()){
if(thHealdChecker.joinable()) {
thHealdChecker.detach();
}
......@@ -1092,7 +1096,8 @@ public:
// th.detach();
// continue;
}else if(tse > end*10){
}
else if(tse > end*10) {
spdlog::error("{} thEventHandler invalid event range ({}, {})", selfId, tss, tse);
continue;
}
......@@ -1149,7 +1154,8 @@ public:
system((string("mkdir -p ") + dirDest).c_str());
auto bfPer = sysutils::getDiskAvailPercent(dirDest);
if(bfPer >= 0.1) {
}else{
}
else {
system((string("rm -fr ") + dirDest).c_str());
}
......
......@@ -64,32 +64,39 @@ static char lightLed(bool on)
list<string> ledPattList;
void ledPattDefault(){
void ledPattDefault()
{
ledPattList.push_back("1");
}
void ledPattAPMode(){
void ledPattAPMode()
{
ledPattList.push_back("10");
}
void ledTryWifi(){
void ledTryWifi()
{
ledPattList.push_back("1110");
}
void ledNoNetwork(){
void ledNoNetwork()
{
ledPattList.push_back("1000");
}
#else
void ledPattDefault(){
void ledPattDefault()
{
}
void ledPattAPMode(){
void ledPattAPMode()
{
}
void ledNoNetwork(){
void ledNoNetwork()
{
}
#endif
......@@ -196,7 +203,7 @@ public:
});
}
public:
public:
json enableMode(int mode)
{
lock_guard<mutex> lk(mutMode);
......@@ -433,20 +440,24 @@ WifiMgr mgr;
#ifdef EMBED_HW_ILS
static int key_event_fd;
key_msg key_event_msg;
void hand_sig(int sig) {
void hand_sig(int sig)
{
read(key_event_fd, &key_event_msg, sizeof(key_event_msg));
spdlog::info("key event id {}, time {}, count {}", key_event_msg.key_id, key_event_msg.time, key_event_msg.count);
if(key_event_msg.count == 5) {
// switch AP mode
mgr.enableMode(1);
}else if(key_event_msg.count == 3){
}
else if(key_event_msg.count == 3) {
// station mode
mgr.scanWifi();
mgr.enableMode(2);
}else if(key_event_msg.count == 5 && key_event_msg.time * 10 >= 10 * 1000){
}
else if(key_event_msg.count == 5 && key_event_msg.time * 10 >= 10 * 1000) {
// clear SN && reboot
system("rm -fr /opt/lvldb && reboot");
}else if((key_event_msg.count == 1 && key_event_msg.time * 10 >= 10 * 1000)){
}
else if((key_event_msg.count == 1 && key_event_msg.time * 10 >= 10 * 1000)) {
// restart network and evdaemon
system("/sbin/ifdown -a; /sbin/ifup -a; systemctl restart evdaemon");
}
......@@ -482,13 +493,15 @@ int main()
}
for(auto &c: lastPatt) {
if(c == lastMode){
if(c == lastMode) {
//skip
}else{
if(c == '1'){
}
else {
if(c == '1') {
// on
lightLed(true);
}else{
}
else {
lightLed(false);
}
lastMode = c;
......
......@@ -72,13 +72,15 @@ vector<long> LoadVideoFiles(string path, int days, int maxSlices, map<long, stri
auto posS = fname.find_last_of('/');
if(posS == string::npos) {
posS = 0;
}else{
}
else {
posS = posS +1;
}
auto posE = fname.find_last_of('.');
if(posE == string::npos) {
posE = fname.size()-1;
}else{
}
else {
posE = posE -1;
}
if(posE < posS) {
......
......@@ -42,8 +42,7 @@ void avlogThrow(void *avcl, int lvl, const char *fmt, ...)
}
// AVPacketSerializer
namespace AVPacketSerializer
{
namespace AVPacketSerializer {
int encode(AVPacket &pkt, char **bytes)
{
int cnt = 0;
......@@ -54,11 +53,9 @@ int encode(AVPacket &pkt, char **bytes)
// pkt.side_data_elems = 0;
wholeSize += sizeof(pkt.side_data_elems);
if (pkt.side_data_elems != 0)
{
if (pkt.side_data_elems != 0) {
spdlog::debug("having side data: {}", pkt.side_data_elems);
for (int i = 0; i < pkt.side_data_elems; i++)
{
for (int i = 0; i < pkt.side_data_elems; i++) {
wholeSize += pkt.side_data[i].size + sizeof(AVPacketSideData::type) + sizeof(AVPacketSideData::size);
}
}
......@@ -80,10 +77,8 @@ int encode(AVPacket &pkt, char **bytes)
//side data
memcpy((*bytes) + cnt, &(pkt.side_data_elems), sizeof(pkt.side_data_elems));
cnt += sizeof(pkt.side_data_elems);
if (pkt.side_data_elems != 0)
{
for (int i = 0; i < pkt.side_data_elems; i++)
{
if (pkt.side_data_elems != 0) {
for (int i = 0; i < pkt.side_data_elems; i++) {
memcpy((*bytes) + cnt, &(pkt.side_data[i].size), sizeof(pkt.side_data[i].size));
cnt += sizeof(pkt.side_data[i].size);
memcpy((*bytes) + cnt, pkt.side_data[i].data, pkt.side_data[i].size);
......@@ -132,8 +127,7 @@ int decode(char *bytes, int len, AVPacket *pkt, long long *ts = nullptr)
//AVPacket *pkt = (AVPacket*)malloc(sizeof(AVPacket));
int ret = 0;
int got = 0;
if (memcmp(PS_MARK_E, bytes + len - strlen(PS_MARK_E), strlen(PS_MARK_E)) != 0 || memcmp(PS_MARK_S, bytes, strlen(PS_MARK_S)))
{
if (memcmp(PS_MARK_E, bytes + len - strlen(PS_MARK_E), strlen(PS_MARK_E)) != 0 || memcmp(PS_MARK_S, bytes, strlen(PS_MARK_S))) {
spdlog::error("invalid packet. len {}", len);
return -1;
}
......@@ -151,11 +145,10 @@ int decode(char *bytes, int len, AVPacket *pkt, long long *ts = nullptr)
memcpy(&pkt->side_data_elems, bytes + got, sizeof(pkt->side_data_elems));
got += sizeof(pkt->side_data_elems);
if(pkt->side_data_elems != 0){
if(pkt->side_data_elems != 0) {
pkt->side_data =(AVPacketSideData*) av_malloc(sizeof(AVPacketSideData) * pkt->side_data_elems );
}
for (int i = 0; i < pkt->side_data_elems; i++)
{
for (int i = 0; i < pkt->side_data_elems; i++) {
memcpy(&(pkt->side_data[i].size), bytes + got, sizeof(pkt->side_data[i].size));
got += sizeof(pkt->side_data[i].size);
pkt->side_data[i].data = (uint8_t *)av_malloc(pkt->side_data[i].size);
......@@ -204,8 +197,7 @@ void mqPacketFree(void *data, void *hint)
}
// AVFormatCtxSerializer
namespace AVFormatCtxSerializer
{
namespace AVFormatCtxSerializer {
/**
* memory layerout
* PS_MARK_S | NUM_STREAMS | AVSTREAM+AVCODEPAR | WHOLESIZE | PS_MARK_E
......@@ -224,26 +216,26 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>())
int numStreams = ctx->nb_streams;
if(ids.size() != 0) {
numStreams = ids.size();
}else{
for(int i = 0; i < numStreams; i++){
}
else {
for(int i = 0; i < numStreams; i++) {
ids.push_back(i);
}
}
spdlog::info("encode num of streams: {}, {}", ctx->nb_streams, numStreams);
for(auto i: ids){
for(auto i: ids) {
spdlog::info("\t sid: {}", i);
// TODO: ignore extradata
// ctx->streams[i]->codecpar->extradata_size = 0;
}
for (auto i:ids)
{
for (auto i:ids) {
wholeSize += sizeof(AVStream);
wholeSize += sizeof(AVCodecParameters);
//extradata
wholeSize += sizeof(ctx->streams[i]->codecpar->extradata_size);
if(ctx->streams[i]->codecpar->extradata_size!=0){
if(ctx->streams[i]->codecpar->extradata_size!=0) {
wholeSize += ctx->streams[i]->codecpar->extradata_size;
}
}
......@@ -257,8 +249,7 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>())
got += strlen(PS_MARK_S);
memcpy((*bytes) + got, (void *)&(numStreams), sizeof(ctx->nb_streams));
got += sizeof(ctx->nb_streams);
for (auto i: ids)
{
for (auto i: ids) {
//
memcpy((*bytes) + got, ctx->streams[i], sizeof(AVStream));
got += sizeof(AVStream);
......@@ -275,7 +266,7 @@ int encode(AVFormatContext *ctx, char **bytes, vector<int> ids = vector<int>())
got += sizeof(wholeSize);
memcpy((*bytes) + got, PS_MARK_E, strlen(PS_MARK_E));
got += strlen(PS_MARK_E);
if(wholeSize != got){
if(wholeSize != got) {
spdlog::error("avctx encode wholesize: {}, should be {}", got, wholeSize);
}
assert(wholeSize == got);
......@@ -288,8 +279,7 @@ int decode(char *bytes, int len, AVFormatContext *pCtx)
int ret = 0;
int got = 0;
memcpy(&ret, bytes +len -strlen(PS_MARK_E) - sizeof(ret), sizeof(ret));
if ((memcmp(PS_MARK_S, bytes + got, strlen(PS_MARK_S)) != 0 && memcmp(PS_MARK_E, bytes + len - strlen(PS_MARK_E), strlen(PS_MARK_E)) != 0)||ret != len)
{
if ((memcmp(PS_MARK_S, bytes + got, strlen(PS_MARK_S)) != 0 && memcmp(PS_MARK_E, bytes + len - strlen(PS_MARK_E), strlen(PS_MARK_E)) != 0)||ret != len) {
spdlog::error("invalid avformatctx: {} {}", ret, len);
return -1;
}
......@@ -301,8 +291,7 @@ int decode(char *bytes, int len, AVFormatContext *pCtx)
pCtx->nb_streams = ret;
spdlog::debug("avctx decode streams:{}", ret);
int numExtra = ret;
for (int i = 0; i < numExtra; i++)
{
for (int i = 0; i < numExtra; i++) {
ret = 0;
pCtx->streams[i] = (AVStream *)av_malloc(sizeof(AVStream));
memcpy(pCtx->streams[i], bytes + got, sizeof(AVStream));
......@@ -334,8 +323,7 @@ int decode(char *bytes, int len, AVFormatContext *pCtx)
void freeCtx(AVFormatContext *pCtx)
{
for (int i = 0; i < pCtx->nb_streams; i++)
{
for (int i = 0; i < pCtx->nb_streams; i++) {
free(pCtx->streams[i]->codecpar);
if(pCtx->streams[i]->codecpar->extradata_size != 0) {
free(pCtx->streams[i]->codecpar->extradata);
......
......@@ -90,7 +90,8 @@ void frame2mat(AVPixelFormat format, const AVFrame * frame, cv::Mat& image)
sws_freeContext(conversion);
}
float getEntropy(cv::Mat &frame){
float getEntropy(cv::Mat &frame)
{
int histSize = 256;
/// Set the ranges ( for B,G,R) )
float range[] = { 0, 256 } ;
......
......@@ -8,7 +8,7 @@ update: 2019/08/23
#ifndef __DATABASE_SL__
#define __DATABASE_SL__
extern "C" {
#include "../vendor/sqlite/sqlite3.h"
#include "../vendor/sqlite/sqlite3.h"
}
#include <string>
......@@ -23,13 +23,13 @@ using namespace std;
using json = nlohmann::json;
namespace DB {
typedef int (*callback)(void*,int,char**,char**);
int exec(void *pUserData, char* fileName, const char* stmt, callback cb);
int getInfo(void *info, int active, const char*fileName);
int clearTable(const char *tableName, const char* fileName);
int setInfo(void* info, const char*fileName);
int loadLocalConfigration(json &config, string fileName);
int saveLocalConfigration(json &config, string fileName);
typedef int (*callback)(void*,int,char**,char**);
int exec(void *pUserData, char* fileName, const char* stmt, callback cb);
int getInfo(void *info, int active, const char*fileName);
int clearTable(const char *tableName, const char* fileName);
int setInfo(void* info, const char*fileName);
int loadLocalConfigration(json &config, string fileName);
int saveLocalConfigration(json &config, string fileName);
}
#endif
\ No newline at end of file
......@@ -10,51 +10,51 @@ using namespace nlohmann;
using namespace std;
namespace LVDB {
#define LVDB_PATH "/opt/lvldb/"
#define LVDB_PATH "/opt/lvldb/"
// sn, config
#define LVDB_FILE_GENERAL LVDB_PATH "general.db"
// sn, config
#define LVDB_FILE_GENERAL LVDB_PATH "general.db"
// slices, log
#define LVDB_FILE_LOG LVDB_PATH"log.db"
// slices, log
#define LVDB_FILE_LOG LVDB_PATH"log.db"
#define LVDB_KEY_SUFFIX_BACK "_bak"
#define LVDB_KEY_SN "SN"
#define LVDB_KEY_CONFIG "CONFIG"
typedef int (*cb_verify_str)(const string&);
typedef int (*cb_verify_json)(const json&);
#define LVDB_KEY_SUFFIX_BACK "_bak"
#define LVDB_KEY_SN "SN"
#define LVDB_KEY_CONFIG "CONFIG"
typedef int (*cb_verify_str)(const string&);
typedef int (*cb_verify_json)(const json&);
int setValue(const string &value, string key, string fileName="", cb_verify_str cb=NULL);
int getValue(string &value, string key, string fileName="", cb_verify_str cb=NULL);
int setValue(const json &value, string key, string fileName="", cb_verify_json cb=NULL);
int getValue(json &value, string key, string fileName="", cb_verify_json cb=NULL);
int setValue(const string &value, string key, string fileName="", cb_verify_str cb=NULL);
int getValue(string &value, string key, string fileName="", cb_verify_str cb=NULL);
int setValue(const json &value, string key, string fileName="", cb_verify_json cb=NULL);
int getValue(json &value, string key, string fileName="", cb_verify_json cb=NULL);
//
json * findConfigModule(json &config, string sn, string moduleName, int iid);
//
int delValue(string key, string fileName);
//
vector<string> getKeys(string fileName = "");
//
json * findConfigModule(json &config, string sn, string moduleName, int iid);
//
int delValue(string key, string fileName);
//
vector<string> getKeys(string fileName = "");
// sn, updatetime, boottime
int setSn(json &info,string fileName=LVDB_FILE_GENERAL);
int getSn(json &info,string fileName=LVDB_FILE_GENERAL);
// sn, updatetime, boottime
int setSn(json &info,string fileName=LVDB_FILE_GENERAL);
int getSn(json &info,string fileName=LVDB_FILE_GENERAL);
// cloudutils::config
int getLocalConfig(json &config, string key = "", string fileName=LVDB_FILE_GENERAL);
int setLocalConfig(json &config, string key = "", string fileName=LVDB_FILE_GENERAL);
// cloudutils::config
int getLocalConfig(json &config, string key = "", string fileName=LVDB_FILE_GENERAL);
int setLocalConfig(json &config, string key = "", string fileName=LVDB_FILE_GENERAL);
// slices
int getSlices(json &slices, string fileName);
int setSlices(json &slices, string fileName);
// slices
int getSlices(json &slices, string fileName);
int setSlices(json &slices, string fileName);
// log
int getLog(json &log, json &writeOptions, string fileName);
int setLog(json &log, json &readOptions, string fileName);
// log
int getLog(json &log, json &writeOptions, string fileName);
int setLog(json &log, json &readOptions, string fileName);
typedef int(*cb_traverse_configration_module)(string modname, json &mod, void *pUser);
int traverseConfigureModules(json &config, cb_traverse_configration_module cb, void *pUser = NULL, string moduleName = "");
typedef int(*cb_traverse_configration_module)(string modname, json &mod, void *pUser);
int traverseConfigureModules(json &config, cb_traverse_configration_module cb, void *pUser = NULL, string moduleName = "");
} // namespace LVDB
#endif
\ No newline at end of file
......@@ -34,8 +34,7 @@ static const size_t default_async_q_size = 8192;
// if a global thread pool doesn't already exist, create it with default queue
// size of 8192 items and single thread.
template<async_overflow_policy OverflowPolicy = async_overflow_policy::block>
struct async_factory_impl
{
struct async_factory_impl {
template<typename Sink, typename... SinkArgs>
static std::shared_ptr<async_logger> create(std::string logger_name, SinkArgs &&... args)
{
......@@ -44,8 +43,7 @@ struct async_factory_impl
// create global thread pool if not already exists..
std::lock_guard<std::recursive_mutex> tp_lock(registry_inst.tp_mutex());
auto tp = registry_inst.get_tp();
if (tp == nullptr)
{
if (tp == nullptr) {
tp = std::make_shared<details::thread_pool>(details::default_async_q_size, 1);
registry_inst.set_tp(tp);
}
......
......@@ -29,8 +29,7 @@
namespace spdlog {
// Async overflow policy - block by default.
enum class async_overflow_policy
{
enum class async_overflow_policy {
block, // Block until message can be enqueued
overrun_oldest // Discard oldest message in the queue if full when trying to
// add new item.
......@@ -40,8 +39,7 @@ namespace details {
class thread_pool;
}
class async_logger final : public std::enable_shared_from_this<async_logger>, public logger
{
class async_logger final : public std::enable_shared_from_this<async_logger>, public logger {
friend class details::thread_pool;
public:
......
......@@ -108,8 +108,7 @@ using level_t = std::atomic<int>;
// Log level enum
namespace level {
enum level_enum
{
enum level_enum {
trace = SPDLOG_LEVEL_TRACE,
debug = SPDLOG_LEVEL_DEBUG,
info = SPDLOG_LEVEL_INFO,
......@@ -127,25 +126,21 @@ enum level_enum
#endif
static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
static const char *short_level_names[]{"T", "D", "I", "W", "E", "C", "O"};
static const char *short_level_names[] {"T", "D", "I", "W", "E", "C", "O"};
inline string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
{
inline string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT {
return level_string_views[l];
}
inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
{
inline const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT {
return short_level_names[l];
}
inline spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT
{
inline spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT {
int level = 0;
for (const auto &level_str : level_string_views)
{
if (level_str == name)
{
if (level_str == name) {
return static_cast<level::level_enum>(level);
}
level++;
......@@ -160,8 +155,7 @@ using level_hasher = std::hash<int>;
// Pattern time - specific time getting to use for pattern_formatter.
// local time by default
//
enum class pattern_time_type
{
enum class pattern_time_type {
local, // log localtime
utc // log utc
};
......@@ -169,8 +163,7 @@ enum class pattern_time_type
//
// Log exception
//
class spdlog_ex : public std::exception
{
class spdlog_ex : public std::exception {
public:
explicit spdlog_ex(std::string msg)
: msg_(std::move(msg))
......@@ -202,8 +195,7 @@ using filename_t = std::wstring;
using filename_t = std::string;
#endif
struct source_loc
{
struct source_loc {
SPDLOG_CONSTEXPR source_loc()
: filename{""}
, line{0}
......
......@@ -31,7 +31,10 @@ inline spdlog::async_logger::async_logger(
inline spdlog::async_logger::async_logger(
std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
: async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy)
: async_logger(std::move(logger_name),
{
std::move(single_sink)
}, std::move(tp), overflow_policy)
{
}
......@@ -41,12 +44,10 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg)
#if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)
incr_msg_counter_(msg);
#endif
if (auto pool_ptr = thread_pool_.lock())
{
if (auto pool_ptr = thread_pool_.lock()) {
pool_ptr->post_log(shared_from_this(), msg, overflow_policy_);
}
else
{
else {
throw spdlog_ex("async log: thread pool doesn't exist anymore");
}
}
......@@ -54,12 +55,10 @@ inline void spdlog::async_logger::sink_it_(details::log_msg &msg)
// send flush request to the thread pool
inline void spdlog::async_logger::flush_()
{
if (auto pool_ptr = thread_pool_.lock())
{
if (auto pool_ptr = thread_pool_.lock()) {
pool_ptr->post_flush(shared_from_this(), overflow_policy_);
}
else
{
else {
throw spdlog_ex("async flush: thread pool doesn't exist anymore");
}
}
......@@ -69,30 +68,24 @@ inline void spdlog::async_logger::flush_()
//
inline void spdlog::async_logger::backend_log_(const details::log_msg &incoming_log_msg)
{
try
{
for (auto &s : sinks_)
{
if (s->should_log(incoming_log_msg.level))
{
try {
for (auto &s : sinks_) {
if (s->should_log(incoming_log_msg.level)) {
s->log(incoming_log_msg);
}
}
}
SPDLOG_CATCH_AND_HANDLE
if (should_flush_(incoming_log_msg))
{
if (should_flush_(incoming_log_msg)) {
backend_flush_();
}
}
inline void spdlog::async_logger::backend_flush_()
{
try
{
for (auto &sink : sinks_)
{
try {
for (auto &sink : sinks_) {
sink->flush();
}
}
......
......@@ -11,8 +11,7 @@
namespace spdlog {
namespace details {
template<typename T>
class circular_q
{
class circular_q {
public:
using item_type = T;
......@@ -28,8 +27,7 @@ public:
v_[tail_] = std::move(item);
tail_ = (tail_ + 1) % max_items_;
if (tail_ == head_) // overrun last item if full
{
if (tail_ == head_) { // overrun last item if full
head_ = (head_ + 1) % max_items_;
++overrun_counter_;
}
......
......@@ -23,8 +23,7 @@
namespace spdlog {
namespace details {
struct console_stdout
{
struct console_stdout {
static std::FILE *stream()
{
return stdout;
......@@ -37,8 +36,7 @@ struct console_stdout
#endif
};
struct console_stderr
{
struct console_stderr {
static std::FILE *stream()
{
return stderr;
......@@ -51,8 +49,7 @@ struct console_stderr
#endif
};
struct console_mutex
{
struct console_mutex {
using mutex_t = std::mutex;
static mutex_t &mutex()
{
......@@ -61,8 +58,7 @@ struct console_mutex
}
};
struct console_nullmutex
{
struct console_nullmutex {
using mutex_t = null_mutex;
static mutex_t &mutex()
{
......
......@@ -22,8 +22,7 @@
namespace spdlog {
namespace details {
class file_helper
{
class file_helper {
public:
const int open_tries = 5;
......@@ -44,10 +43,8 @@ public:
close();
auto *mode = truncate ? SPDLOG_FILENAME_T("wb") : SPDLOG_FILENAME_T("ab");
_filename = fname;
for (int tries = 0; tries < open_tries; ++tries)
{
if (!os::fopen_s(&fd_, fname, mode))
{
for (int tries = 0; tries < open_tries; ++tries) {
if (!os::fopen_s(&fd_, fname, mode)) {
return;
}
......@@ -59,8 +56,7 @@ public:
void reopen(bool truncate)
{
if (_filename.empty())
{
if (_filename.empty()) {
throw spdlog_ex("Failed re opening file - was not opened before");
}
open(_filename, truncate);
......@@ -73,8 +69,7 @@ public:
void close()
{
if (fd_ != nullptr)
{
if (fd_ != nullptr) {
std::fclose(fd_);
fd_ = nullptr;
}
......@@ -84,16 +79,14 @@ public:
{
size_t msg_size = buf.size();
auto data = buf.data();
if (std::fwrite(data, 1, msg_size, fd_) != msg_size)
{
if (std::fwrite(data, 1, msg_size, fd_) != msg_size) {
throw spdlog_ex("Failed writing to file " + os::filename_to_str(_filename), errno);
}
}
size_t size() const
{
if (fd_ == nullptr)
{
if (fd_ == nullptr) {
throw spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(_filename));
}
return os::filesize(fd_);
......@@ -128,15 +121,13 @@ public:
// no valid extension found - return whole path and empty string as
// extension
if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1)
{
if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1) {
return std::make_tuple(fname, spdlog::filename_t());
}
// treat casese like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
auto folder_index = fname.rfind(details::os::folder_sep);
if (folder_index != filename_t::npos && folder_index >= ext_index - 1)
{
if (folder_index != filename_t::npos && folder_index >= ext_index - 1) {
return std::make_tuple(fname, spdlog::filename_t());
}
......
......@@ -14,8 +14,7 @@ namespace details {
namespace fmt_helper {
template<size_t Buffer_Size>
inline spdlog::string_view_t to_string_view(const fmt::basic_memory_buffer<char, Buffer_Size> &buf) SPDLOG_NOEXCEPT
{
inline spdlog::string_view_t to_string_view(const fmt::basic_memory_buffer<char, Buffer_Size> &buf) SPDLOG_NOEXCEPT {
return spdlog::string_view_t(buf.data(), buf.size());
}
......@@ -30,8 +29,7 @@ template<size_t Buffer_Size>
inline void append_string_view(spdlog::string_view_t view, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
{
auto *buf_ptr = view.data();
if (buf_ptr != nullptr)
{
if (buf_ptr != nullptr) {
dest.append(buf_ptr, buf_ptr + view.size());
}
}
......@@ -53,22 +51,18 @@ inline unsigned count_digits(T n)
template<size_t Buffer_Size>
inline void pad2(int n, fmt::basic_memory_buffer<char, Buffer_Size> &dest)
{
if (n > 99)
{
if (n > 99) {
append_int(n, dest);
}
else if (n > 9) // 10-99
{
else if (n > 9) { // 10-99
dest.push_back(static_cast<char>('0' + n / 10));
dest.push_back(static_cast<char>('0' + n % 10));
}
else if (n >= 0) // 0-9
{
else if (n >= 0) { // 0-9
dest.push_back('0');
dest.push_back(static_cast<char>('0' + n));
}
else // negatives (unlikely, but just in case, let fmt deal with it)
{
else { // negatives (unlikely, but just in case, let fmt deal with it)
fmt::format_to(dest, "{:02}", n);
}
}
......@@ -78,8 +72,7 @@ inline void pad_uint(T n, unsigned int width, fmt::basic_memory_buffer<char, Buf
{
static_assert(std::is_unsigned<T>::value, "pad_uint must get unsigned T");
auto digits = count_digits(n);
if (width > digits)
{
if (width > digits) {
const char *zeroes = "0000000000000000000";
dest.append(zeroes, zeroes + width - digits);
}
......
......@@ -13,8 +13,7 @@
namespace spdlog {
namespace details {
struct log_msg
{
struct log_msg {
log_msg(source_loc loc, const std::string *loggers_name, level::level_enum lvl, string_view_t view)
: logger_name(loggers_name)
......
......@@ -37,7 +37,10 @@ inline spdlog::logger::logger(std::string logger_name, sinks_init_list sinks_lis
// ctor with single sink
inline spdlog::logger::logger(std::string logger_name, spdlog::sink_ptr single_sink)
: logger(std::move(logger_name), {std::move(single_sink)})
: logger(std::move(logger_name),
{
std::move(single_sink)
})
{
}
......@@ -45,8 +48,7 @@ inline spdlog::logger::~logger() = default;
inline void spdlog::logger::set_formatter(std::unique_ptr<spdlog::formatter> f)
{
for (auto &sink : sinks_)
{
for (auto &sink : sinks_) {
sink->set_formatter(f->clone());
}
}
......@@ -60,13 +62,11 @@ inline void spdlog::logger::set_pattern(std::string pattern, pattern_time_type t
template<typename... Args>
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *fmt, const Args &... args)
{
if (!should_log(lvl))
{
if (!should_log(lvl)) {
return;
}
try
{
try {
using details::fmt_helper::to_string_view;
fmt::memory_buffer buf;
fmt::format_to(buf, fmt, args...);
......@@ -84,13 +84,11 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *fmt, const Ar
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const char *msg)
{
if (!should_log(lvl))
{
if (!should_log(lvl)) {
return;
}
try
{
try {
details::log_msg log_msg(source, &name_, lvl, spdlog::string_view_t(msg));
sink_it_(log_msg);
}
......@@ -105,12 +103,10 @@ inline void spdlog::logger::log(level::level_enum lvl, const char *msg)
template<class T, typename std::enable_if<std::is_convertible<T, spdlog::string_view_t>::value, T>::type *>
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const T &msg)
{
if (!should_log(lvl))
{
if (!should_log(lvl)) {
return;
}
try
{
try {
details::log_msg log_msg(source, &name_, lvl, msg);
sink_it_(log_msg);
}
......@@ -126,12 +122,10 @@ inline void spdlog::logger::log(level::level_enum lvl, const T &msg)
template<class T, typename std::enable_if<!std::is_convertible<T, spdlog::string_view_t>::value, T>::type *>
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const T &msg)
{
if (!should_log(lvl))
{
if (!should_log(lvl)) {
return;
}
try
{
try {
using details::fmt_helper::to_string_view;
fmt::memory_buffer buf;
fmt::format_to(buf, "{}", msg);
......@@ -224,20 +218,17 @@ inline void spdlog::logger::critical(const T &msg)
inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer &target)
{
int wbuf_size = static_cast<int>(wbuf.size());
if (wbuf_size == 0)
{
if (wbuf_size == 0) {
return;
}
auto result_size = ::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, NULL, 0, NULL, NULL);
if (result_size > 0)
{
if (result_size > 0) {
target.resize(result_size);
::WideCharToMultiByte(CP_UTF8, 0, wbuf.data(), wbuf_size, &target.data()[0], result_size, NULL, NULL);
}
else
{
else {
throw spdlog::spdlog_ex(fmt::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
}
}
......@@ -245,13 +236,11 @@ inline void wbuf_to_utf8buf(const fmt::wmemory_buffer &wbuf, fmt::memory_buffer
template<typename... Args>
inline void spdlog::logger::log(source_loc source, level::level_enum lvl, const wchar_t *fmt, const Args &... args)
{
if (!should_log(lvl))
{
if (!should_log(lvl)) {
return;
}
try
{
try {
// format to wmemory_buffer and convert to utf8
using details::fmt_helper::to_string_view;
fmt::wmemory_buffer wbuf;
......@@ -333,8 +322,7 @@ inline spdlog::log_err_handler spdlog::logger::error_handler() const
inline void spdlog::logger::flush()
{
try
{
try {
flush_();
}
SPDLOG_CATCH_AND_HANDLE
......@@ -380,24 +368,20 @@ inline void spdlog::logger::sink_it_(details::log_msg &msg)
#if defined(SPDLOG_ENABLE_MESSAGE_COUNTER)
incr_msg_counter_(msg);
#endif
for (auto &sink : sinks_)
{
if (sink->should_log(msg.level))
{
for (auto &sink : sinks_) {
if (sink->should_log(msg.level)) {
sink->log(msg);
}
}
if (should_flush_(msg))
{
if (should_flush_(msg)) {
flush_();
}
}
inline void spdlog::logger::flush_()
{
for (auto &sink : sinks_)
{
for (auto &sink : sinks_) {
sink->flush();
}
}
......@@ -405,8 +389,7 @@ inline void spdlog::logger::flush_()
inline void spdlog::logger::default_err_handler_(const std::string &msg)
{
auto now = time(nullptr);
if (now - last_err_time_ < 60)
{
if (now - last_err_time_ < 60) {
return;
}
last_err_time_ = now;
......
......@@ -21,8 +21,7 @@ namespace spdlog {
namespace details {
template<typename T>
class mpmc_blocking_queue
{
class mpmc_blocking_queue {
public:
using item_type = T;
explicit mpmc_blocking_queue(size_t max_items)
......@@ -58,8 +57,7 @@ public:
{
{
std::unique_lock<std::mutex> lock(queue_mutex_);
if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); }))
{
if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); })) {
return false;
}
q_.pop_front(popped_item);
......@@ -94,8 +92,7 @@ public:
bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration)
{
std::unique_lock<std::mutex> lock(queue_mutex_);
if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); }))
{
if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); })) {
return false;
}
q_.pop_front(popped_item);
......
......@@ -10,8 +10,7 @@
namespace spdlog {
namespace details {
struct null_mutex
{
struct null_mutex {
void lock() {}
void unlock() {}
bool try_lock()
......@@ -20,8 +19,7 @@ struct null_mutex
}
};
struct null_atomic_int
{
struct null_atomic_int {
int value;
null_atomic_int() = default;
......
......@@ -57,8 +57,7 @@ namespace spdlog {
namespace details {
namespace os {
inline spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT
{
inline spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT {
#if defined __linux__ && defined SPDLOG_CLOCK_COARSE
timespec ts;
......@@ -70,8 +69,7 @@ inline spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT
return log_clock::now();
#endif
}
inline std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
{
inline std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT {
#ifdef _WIN32
std::tm tm;
......@@ -83,14 +81,12 @@ inline std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
return tm;
}
inline std::tm localtime() SPDLOG_NOEXCEPT
{
inline std::tm localtime() SPDLOG_NOEXCEPT {
std::time_t now_t = time(nullptr);
return localtime(now_t);
}
inline std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
{
inline std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT {
#ifdef _WIN32
std::tm tm;
......@@ -102,8 +98,7 @@ inline std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
return tm;
}
inline std::tm gmtime() SPDLOG_NOEXCEPT
{
inline std::tm gmtime() SPDLOG_NOEXCEPT {
std::time_t now_t = time(nullptr);
return gmtime(now_t);
}
......@@ -137,8 +132,7 @@ inline void prevent_child_fd(FILE *f)
#endif
#else
auto fd = fileno(f);
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
{
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
throw spdlog_ex("fcntl with FD_CLOEXEC failed", errno);
}
#endif
......@@ -158,16 +152,14 @@ inline bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mod
#endif
#ifdef SPDLOG_PREVENT_CHILD_FD
if (*fp != nullptr)
{
if (*fp != nullptr) {
prevent_child_fd(*fp);
}
#endif
return *fp == nullptr;
}
inline int remove(const filename_t &filename) SPDLOG_NOEXCEPT
{
inline int remove(const filename_t &filename) SPDLOG_NOEXCEPT {
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wremove(filename.c_str());
#else
......@@ -175,8 +167,7 @@ inline int remove(const filename_t &filename) SPDLOG_NOEXCEPT
#endif
}
inline int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT
{
inline int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT {
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
return _wrename(filename1.c_str(), filename2.c_str());
#else
......@@ -185,8 +176,7 @@ inline int rename(const filename_t &filename1, const filename_t &filename2) SPDL
}
// Return if file exists
inline bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT
{
inline bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT {
#ifdef _WIN32
#ifdef SPDLOG_WCHAR_FILENAMES
auto attribs = GetFileAttributesW(filename.c_str());
......@@ -203,23 +193,20 @@ inline bool file_exists(const filename_t &filename) SPDLOG_NOEXCEPT
// Return file size according to open FILE* object
inline size_t filesize(FILE *f)
{
if (f == nullptr)
{
if (f == nullptr) {
throw spdlog_ex("Failed getting file size. fd is null");
}
#if defined(_WIN32) && !defined(__CYGWIN__)
int fd = _fileno(f);
#if _WIN64 // 64 bits
__int64 ret = _filelengthi64(fd);
if (ret >= 0)
{
if (ret >= 0) {
return static_cast<size_t>(ret);
}
#else // windows 32 bits
long ret = _filelength(fd);
if (ret >= 0)
{
if (ret >= 0) {
return static_cast<size_t>(ret);
}
#endif
......@@ -229,15 +216,13 @@ inline size_t filesize(FILE *f)
// 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
#if !defined(__FreeBSD__) && !defined(__APPLE__) && (defined(__x86_64__) || defined(__ppc64__)) && !defined(__CYGWIN__)
struct stat64 st;
if (fstat64(fd, &st) == 0)
{
if (fstat64(fd, &st) == 0) {
return static_cast<size_t>(st.st_size);
}
#else // unix 32 bits or cygwin
struct stat st;
if (fstat(fd, &st) == 0)
{
if (fstat(fd, &st) == 0) {
return static_cast<size_t>(st.st_size);
}
#endif
......@@ -261,12 +246,10 @@ inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
throw spdlog::spdlog_ex("Failed getting timezone info. ", errno);
int offset = -tzinfo.Bias;
if (tm.tm_isdst)
{
if (tm.tm_isdst) {
offset -= tzinfo.DaylightBias;
}
else
{
else {
offset -= tzinfo.StandardBias;
}
return offset;
......@@ -274,8 +257,7 @@ inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
#if defined(sun) || defined(__sun) || defined(_AIX)
// 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
struct helper
{
struct helper {
static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime())
{
int local_year = localtm.tm_year + (1900 - 1);
......@@ -313,8 +295,7 @@ inline int utc_minutes_offset(const std::tm &tm = details::os::localtime())
// Return current thread id as size_t
// It exists because the std::this_thread::get_id() is much slower(especially
// under VS 2013)
inline size_t _thread_id() SPDLOG_NOEXCEPT
{
inline size_t _thread_id() SPDLOG_NOEXCEPT {
#ifdef _WIN32
return static_cast<size_t>(::GetCurrentThreadId());
#elif __linux__
......@@ -336,8 +317,7 @@ inline size_t _thread_id() SPDLOG_NOEXCEPT
}
// Return current thread id as size_t (from thread local storage)
inline size_t thread_id() SPDLOG_NOEXCEPT
{
inline size_t thread_id() SPDLOG_NOEXCEPT {
#if defined(SPDLOG_NO_TLS)
return _thread_id();
#else // cache thread id in tls
......@@ -348,8 +328,7 @@ inline size_t thread_id() SPDLOG_NOEXCEPT
// This is avoid msvc issue in sleep_for that happens if the clock changes.
// See https://github.com/gabime/spdlog/issues/609
inline void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT
{
inline void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT {
#if defined(_WIN32)
::Sleep(milliseconds);
#else
......@@ -385,13 +364,13 @@ inline int pid()
// Determine if the terminal supports colors
// Source: https://github.com/agauniyal/rang/
inline bool is_color_terminal() SPDLOG_NOEXCEPT
{
inline bool is_color_terminal() SPDLOG_NOEXCEPT {
#ifdef _WIN32
return true;
#else
static constexpr const char *Terms[] = {
"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"};
"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux", "msys", "putty", "rxvt", "screen", "vt100", "xterm"
};
const char *env_p = std::getenv("TERM");
if (env_p == nullptr)
......@@ -400,15 +379,17 @@ inline bool is_color_terminal() SPDLOG_NOEXCEPT
}
static const bool result =
std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term) { return std::strstr(env_p, term) != nullptr; });
std::any_of(std::begin(Terms), std::end(Terms), [&](const char *term)
{
return std::strstr(env_p, term) != nullptr;
});
return result;
#endif
}
// Detrmine if the terminal attached
// Source: https://github.com/agauniyal/rang/
inline bool in_terminal(FILE *file) SPDLOG_NOEXCEPT
{
inline bool in_terminal(FILE *file) SPDLOG_NOEXCEPT {
#ifdef _WIN32
return _isatty(_fileno(file)) != 0;
......
......@@ -20,23 +20,19 @@
namespace spdlog {
namespace details {
class periodic_worker
{
class periodic_worker {
public:
periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval)
{
active_ = (interval > std::chrono::seconds::zero());
if (!active_)
{
if (!active_) {
return;
}
worker_thread_ = std::thread([this, callback_fun, interval]() {
for (;;)
{
for (;;) {
std::unique_lock<std::mutex> lock(this->mutex_);
if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
{
if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; })) {
return; // active_ == false, so exit this thread
}
callback_fun();
......@@ -50,8 +46,7 @@ public:
// stop the worker thread and join it
~periodic_worker()
{
if (worker_thread_.joinable())
{
if (worker_thread_.joinable()) {
{
std::lock_guard<std::mutex> lock(mutex_);
active_ = false;
......
......@@ -33,8 +33,7 @@ namespace spdlog {
namespace details {
class thread_pool;
class registry
{
class registry {
public:
registry(const registry &) = delete;
registry &operator=(const registry &) = delete;
......@@ -50,16 +49,14 @@ public:
std::lock_guard<std::mutex> lock(logger_map_mutex_);
new_logger->set_formatter(formatter_->clone());
if (err_handler_)
{
if (err_handler_) {
new_logger->set_error_handler(err_handler_);
}
new_logger->set_level(level_);
new_logger->flush_on(flush_level_);
if (automatic_registration_)
{
if (automatic_registration_) {
register_logger_(std::move(new_logger));
}
}
......@@ -92,12 +89,10 @@ public:
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
// remove previous default logger from the map
if (default_logger_ != nullptr)
{
if (default_logger_ != nullptr) {
loggers_.erase(default_logger_->name());
}
if (new_default_logger != nullptr)
{
if (new_default_logger != nullptr) {
loggers_[new_default_logger->name()] = new_default_logger;
}
default_logger_ = std::move(new_default_logger);
......@@ -120,8 +115,7 @@ public:
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
formatter_ = std::move(formatter);
for (auto &l : loggers_)
{
for (auto &l : loggers_) {
l.second->set_formatter(formatter_->clone());
}
}
......@@ -129,8 +123,7 @@ public:
void set_level(level::level_enum log_level)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
for (auto &l : loggers_) {
l.second->set_level(log_level);
}
level_ = log_level;
......@@ -139,8 +132,7 @@ public:
void flush_on(level::level_enum log_level)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
for (auto &l : loggers_) {
l.second->flush_on(log_level);
}
flush_level_ = log_level;
......@@ -156,8 +148,7 @@ public:
void set_error_handler(log_err_handler handler)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
for (auto &l : loggers_) {
l.second->set_error_handler(handler);
}
err_handler_ = handler;
......@@ -166,8 +157,7 @@ public:
void apply_all(const std::function<void(const std::shared_ptr<logger>)> &fun)
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
for (auto &l : loggers_) {
fun(l.second);
}
}
......@@ -175,8 +165,7 @@ public:
void flush_all()
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
for (auto &l : loggers_)
{
for (auto &l : loggers_) {
l.second->flush();
}
}
......@@ -185,8 +174,7 @@ public:
{
std::lock_guard<std::mutex> lock(logger_map_mutex_);
loggers_.erase(logger_name);
if (default_logger_ && default_logger_->name() == logger_name)
{
if (default_logger_ && default_logger_->name() == logger_name) {
default_logger_.reset();
}
}
......@@ -255,8 +243,7 @@ private:
void throw_if_exists_(const std::string &logger_name)
{
if (loggers_.find(logger_name) != loggers_.end())
{
if (loggers_.find(logger_name) != loggers_.end()) {
throw spdlog_ex("logger with name '" + logger_name + "' already exists");
}
}
......
......@@ -10,8 +10,7 @@
namespace spdlog {
class formatter
{
class formatter {
public:
virtual ~formatter() = default;
virtual void format(const details::log_msg &msg, fmt::memory_buffer &dest) = 0;
......
......@@ -19,8 +19,7 @@
namespace spdlog {
namespace sinks {
template<typename Mutex>
class base_sink : public sink
{
class base_sink : public sink {
public:
base_sink() = default;
base_sink(const base_sink &) = delete;
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论