12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976 |
- #include "stdafx.h"
- #include "UploadFSM.h"
- #include <regex>
- #include <fileutil.h>
- #include <array.h>
- #ifdef RVC_OS_WIN
- #include <cstdlib>
- #include <ctime>
- #include "EventCode.h"
- #include "filecryption.h"
- #else
- #include <thread>
- #include "upload.h"
- #include "libtoolkit/path.h"
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <fcntl.h>
- #include <time.h>
- #include <stdio.h>
- #include <cstdio>
- #include <iostream>
- #include <errno.h>
- #include "EventCode.h"
- #endif
- #define UPLOAD_CONTENT_EACH_LEN 2*1024*1024
- UploadFSM::UploadFSM() : m_currUploadFile(NULL)
- {
- m_uploadList = new list<UploadFileInfo*>();
- m_uploadPlanList = new list<UploadPlan *>();
- m_overLenFileList = new list<string>();
- m_eachUploadLen=UPLOAD_CONTENT_EACH_LEN;
- m_uploadMaxNum = 1000;
- m_isOffLine=true;//初始离线状态为true
- m_printPlan = true;//初始化为打印
- }
- UploadFSM::~UploadFSM()
- {
- }
- namespace Task
- {
- struct SendFileTask : public ITaskSp
- {
- UploadFSM* m_fsm;
- explicit SendFileTask(UploadFSM* e) : m_fsm(e) {}
- void Process(){
- //判断是分行url请求还是总行url请求
- //判断是临时文件还是永久文件
- //循环上传
- //登记上传流水或者失败流水
- //根据最终上传结果返回成功还是失败
- CSystemStaticInfo info;
- auto rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- //Dbg("get CSystemStaticInfo fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("get CSystemStaticInfo fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
- m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_FAIL));//失败发送
- return;
- }
- bool isLanTerminal=true;//行内行外标志
- //if(info.strSite.Compare("CMB.LIB",true)==0||info.strSite.Compare("CMB.SSB",true)==0){
- // isLanTerminal=true;
- //}else{
- // isLanTerminal=false;
- //}
- if(strcmp(m_fsm->m_currUploadFile->upload_address_env.c_str(),"BIZ")==0){
- isLanTerminal=true;
- }else{
- isLanTerminal=false;
- }
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- bool hasSend=false;
- if(m_fsm->m_currUploadFile->plan_type=="T"){
- //查询失败统一需要上传
- if(queryTempFile(client,info)){
- hasSend=true;
- }
- }
- //是否需要上传文件
- bool sendOk = false;
- if(!hasSend){
- string errmsg ="";
- if(isLanTerminal){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("上传文件到分行:%s",m_fsm->m_currUploadFile->filePath.c_str());
- }else{
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("上传文件到总行:%s",m_fsm->m_currUploadFile->filePath.c_str());
- }
- string MD5str = ""; //返回的MD5值
- string branchFilePath = ""; //返回的分行保存路径值
- //修改为重试上传机制,防止上传当中网络抖动,避免等待下次上传
- bool isUploadSucc=false;
- for (int i =0 ; i<2;i++ )
- {
- errmsg="";//每次上传前清空错误信息,只记录最后一次的
- if(uploadFile(client,info,MD5str,branchFilePath,errmsg)){
- isUploadSucc = true;
- break;
- }
- Sleep(3000);//等待3秒下次传送
- }
- if(isUploadSucc){
- if(updateState(client,info,isLanTerminal,MD5str,branchFilePath,errmsg)){
- if(operateFile(errmsg)){
- sendOk = true;//成功
- }else{
- m_fsm->m_uploadReport.operateFileFail++;//添加操作失败计数
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("operateFile fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
- addUploadFail(client,info,isLanTerminal,"2",errmsg);//操作失败
- }
- }else{
- m_fsm->m_uploadReport.updateState++;//添加登记失败计数
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("updateState fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
- addUploadFail(client,info,isLanTerminal,"1",errmsg);//登记失败
- }
- }else{
- m_fsm->m_uploadReport.uploadFail++;//添加上传失败计数
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("uploadFile fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
- addUploadFail(client,info,isLanTerminal,"1",errmsg);//上传失败
- }
- }else{
- sendOk=true;
- }
- client->Destory();
- if(sendOk){
- m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_SUCC));//成功发送
- }else{
- m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_FAIL));//失败发送
- }
- }
- //上传文件:断点续传,多次调用
- bool uploadFile(IHttpFunc* client,CSystemStaticInfo info,string &MD5str,string &branchFilePath, string &errmsg){
- string reqUrl;
- unsigned seed;
- seed = time(0);
- srand(seed);
- if(m_fsm->m_branchIpList.size()>0){
- int branchSeq = (rand() % m_fsm->m_branchIpList.size()) + 1;
- map<int,string>::iterator it = m_fsm->m_branchIpList.find(branchSeq);
- if(it != m_fsm->m_branchIpList.end())
- {
- reqUrl = it->second;
- }else{
- //Dbg("uploadFile is fail ,branchIp[%d] is null",branchSeq);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail ,branchIp[%d] is null",branchSeq);
- errmsg = CSimpleStringA::Format("uploadFile is fail ,branchIp[%d] is null",branchSeq).GetData();
- return false;
- }
- }else{
- //Dbg("uploadFile is fail ,branchIp is null");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail ,branchIp is null");
- errmsg = "uploadFile is fail ,branchIp is null";
- return false;
- }
- //解密文件
- unsigned char* pdecdata = NULL;//记得释放内存
- size_t udecheadlen = 0;
- int decOffSet = 0;//文件明文头和密文头的偏移量:可能是负数、零、正数
- char* pHeadJson = NULL;//记得释放内存
- size_t uheadJsonLen = 0;
- #ifdef RVC_OS_WIN
- filecryption_callback_t cb = {0};
- cb.dbg = &Dbg;
- int decRet = rvc_file_decrypt(&pdecdata,&udecheadlen,&decOffSet,&pHeadJson,&uheadJsonLen,m_fsm->m_currUploadFile->filePath.c_str(),&cb);
- #else
- int decRet = 0;
- #endif
- if(decRet!=0){
- //解密报错
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail, decode file fail=%d",decRet);
- errmsg=CSimpleStringA::Format("uploadFile is fail, decode file fail=%d",decRet).GetData();
- #ifdef RVC_OS_WIN
- rvc_free_data((void**)&pdecdata);
- rvc_free_data((void**)&pHeadJson);
- #endif
- m_fsm->m_uploadReport.decodeFail++;//添加解密失败计数
- return false;
- }
- //计算出解密后总长度:
- m_fsm->m_currUploadFile->decFileLen = m_fsm->m_currUploadFile->fileLen-decOffSet;//重新赋值
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("decode file len=%d, decOffSet=%d, decHeadLen=%d, uheadJsonLen=%d",m_fsm->m_currUploadFile->decFileLen,decOffSet,(int)udecheadlen,(int)uheadJsonLen);
- //解密自定义头赋值
- if(pHeadJson!=NULL){
- m_fsm->m_currUploadFile->decHeadJson = pHeadJson;
- }else{
- m_fsm->m_currUploadFile->decHeadJson = "";
- }
- //Dbg("decode file decHeadJson = %s",m_fsm->m_currUploadFile->decHeadJson.c_str());
- //获取服务器文件长度
- unsigned char* contentFirst = new unsigned char[1];
- memset(contentFirst,0,1);
- UploadDataRet respFirst ={0};
- bool is_finish =false; //是否续传
- if(!uploadFileImpl(client,info,reqUrl,contentFirst,0,"",respFirst)){
- delete[] contentFirst;
- errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl first is fail",reqUrl.c_str()).GetData();
- #ifdef RVC_OS_WIN
- rvc_free_data((void**)&pdecdata);
- rvc_free_data((void**)&pHeadJson);
- #endif
- return false;//返回失败
- }else{
- delete[] contentFirst;
- }
- long uploadedLen = respFirst.uploaded_length;//服务器返回已上传的长度
- //Dbg("服务器返回临时长度 uploadedLen = %d",uploadedLen);
- if(uploadedLen>m_fsm->m_currUploadFile->decFileLen){
- //服务器返回长度大于终端文件长度
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail, server filelen [%d] is over terminal decfilelen [%d]",uploadedLen,m_fsm->m_currUploadFile->decFileLen);
- errmsg=CSimpleStringA::Format("uploadFile is fail, server filelen [%d] is over terminal decfilelen [%d]",uploadedLen,m_fsm->m_currUploadFile->decFileLen).GetData();
- #ifdef RVC_OS_WIN
- rvc_free_data((void**)&pdecdata);
- rvc_free_data((void**)&pHeadJson);
- #endif
- return false;
- }
- //密文解密
- if(uploadedLen==0){
- //文件头传输
- if(udecheadlen>0){
- //密文数据,传送首块,传解密字节块
- UploadDataRet firstResp ={0};
- if(!uploadFileImpl(client,info,reqUrl,pdecdata,(long)udecheadlen,"",firstResp)){
- #ifdef RVC_OS_WIN
- rvc_free_data((void**)&pdecdata);
- rvc_free_data((void**)&pHeadJson);
- #endif
- errmsg="uploadFileImpl first data upload is fail";
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFileImpl first data upload is fail, url=%s",reqUrl.c_str());
- return false;//返回错误
- }
- }
- uploadedLen += (long)udecheadlen+decOffSet;//改变文件游标偏移量
- }else{
- //数据传输
- uploadedLen += decOffSet; //改变文件游标偏移量
- }
- #ifdef RVC_OS_WIN
- rvc_free_data((void**)&pdecdata);//释放解密内存
- rvc_free_data((void**)&pHeadJson);
- #endif
- //Dbg("decode file decHeadJson = %s",strHeadJson.c_str());
- if(uploadedLen>m_fsm->m_currUploadFile->fileLen){
- //续传起始位置大于终端文件长度
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail, begin read filelen [%d] is over terminal filelen [%d]",uploadedLen,m_fsm->m_currUploadFile->fileLen);
- errmsg=CSimpleStringA::Format("uploadFile is fail, begin read filelen [%d] is over terminal filelen [%d]",uploadedLen,m_fsm->m_currUploadFile->fileLen).GetData();
- return false;
- }
- if(uploadedLen<0){
- //服务器报错的头文件内容加上偏移量后,极端情况可能会出现负数,设置为零,最后服务端做长度比较不相同,会清空临时文件重传
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile decode uploadedLen beginPos < 0");
- uploadedLen =0;
- }
-
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("文件[%s] 开始传送位置 uploadedLen = %d, decode file len=%d, decOffSet=%d, decHeadLen=%d, uheadJsonLen=%d",m_fsm->m_currUploadFile->filePath.c_str(), uploadedLen, m_fsm->m_currUploadFile->decFileLen,decOffSet,(int)udecheadlen,(int)uheadJsonLen);
- //循环传送数据块
- FILE* pFile =fopen(m_fsm->m_currUploadFile->filePath.c_str(),"rb");
- if(pFile==NULL){
- //读取文件失败;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile is fail, file open fail");
- errmsg="uploadFile is fail, file open fail";
- return false;
- }
- bool uploadSucc= false;
- while(true){
- //续传
- if((m_fsm->m_currUploadFile->fileLen-uploadedLen)>m_fsm->m_eachUploadLen){
- int uploadLen = m_fsm->m_eachUploadLen;//传送数据长度
- unsigned char* content = new unsigned char[uploadLen];
- memset(content,0,uploadLen);
- //从文件拷贝字节
- //Dbg("拷贝字节开始,文件[%s],起始位:%d,拷贝字节数:%d",m_fsm->m_currUploadFile->filePath.c_str(),uploadedLen,uploadLen);
- if(m_fsm->getFileContent(pFile,content,uploadedLen,uploadLen)){
- UploadDataRet resp ={0};
- if(uploadFileImpl(client,info,reqUrl,content,uploadLen,"",resp)){
- delete[] content;
- uploadedLen +=uploadLen;//改变已上传长度
- }else{
- delete[] content;
- errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl continue is fail",reqUrl.c_str()).GetData();
- break;//上传失败
- }
- }else{
- delete[] content;
- errmsg="uploadFile is fail , getFileContent fail";
- break;//获取文件内存失败
- }
- }else{
- //获取最后一次传送时文件长度
- CSimpleStringA filepath = m_fsm->m_currUploadFile->filePath.c_str();
- long fileLastLen = 0;
- if(!m_fsm->GetFileLength(filepath.GetData(),fileLastLen)){
- errmsg="uploadFile is fail , end get file len fail";
- break;//计算sm3出错
- }
-
- string fileLastLenStr= CSimpleStringA::Format("%d",fileLastLen-decOffSet).GetData();//计算出解密后总长度
- //最后一块
- int uploadLen = m_fsm->m_currUploadFile->fileLen-uploadedLen;
- unsigned char* contentEnd;
- if(uploadLen==0){
- //对零的长度特殊处理
- contentEnd = new unsigned char[1];
- memset(contentEnd,0,1);
- }else{
- contentEnd = new unsigned char[uploadLen];
- memset(contentEnd,0,uploadLen);
- }
-
- //Dbg("最后拷贝字节开始,文件[%s],起始位:%d,拷贝字节数:%d",m_fsm->m_currUploadFile->filePath.c_str(),uploadedLen,uploadLen);
- if(m_fsm->getFileContent(pFile,contentEnd,uploadedLen,uploadLen)){
- UploadDataRet respEnd ={0};
- if(uploadFileImpl(client,info,reqUrl,contentEnd,uploadLen,fileLastLenStr,respEnd)){
- delete[] contentEnd;
- if(respEnd.upload_finish){
- uploadSucc =true;//成功
- branchFilePath = respEnd.branchFilePath;//分行保存地址
- }else{
- uploadSucc =false;//失败
- }
- break;
- }else{
- delete[] contentEnd;
- errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl end is fail",reqUrl.c_str()).GetData();
- break;//上传失败
- }
- }else{
- delete[] contentEnd;
- errmsg="uploadFile is fail , end getFileContent fail";
- break;//获取文件内存失败
- }
- }
- }
- if(uploadSucc){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile succ");
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile fail url=%s",reqUrl.c_str());
- }
- if(pFile){
- if(fclose(pFile)!=0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFile")("uploadFile fail, close file fail ,url=%s",reqUrl.c_str());
- errmsg="uploadFile fail, close file fail";
- return false;
- }
- }
- return uploadSucc;
- }
- //上传文件:具体实现
- bool uploadFileImpl(IHttpFunc* client,CSystemStaticInfo info,string httpUrl,unsigned char* fileContent,long fileContentSize,string lastFileLength,UploadDataRet& uploadData){
- UploadFileReq qTempReq;
- UploadFileRet qTempRet;
- qTempRet.m_userCode ="";
- qTempRet.m_errMsg="";
-
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
- rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
- rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
- rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
- rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
- //rootReq["origin_file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();
- rootReq["first_file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->decFileLen).GetData();//加密后需要修改,服务端根据此长度做判断
- rootReq["last_file_length"] = lastFileLength.c_str();//加密后需要修改,最后一次长度跟服务端保存长度做对比
- rootReq["upload_length"] = CSimpleStringA::Format("%d",fileContentSize).GetData();
- //rootReq["first_sm3"] = firstMD5Str.c_str();
- //rootReq["last_sm3"] = lastMD5Str.c_str();
- rootReq["file_head_custom"] = m_fsm->m_currUploadFile->decHeadJson.c_str();//自定义解密的头json格式,可为空
- #ifdef RVC_OS_WIN
- rootReq["system_type"] = "W";//系统标记,代表路径分隔符
- #else
- rootReq["system_type"] = "L";//系统标记,代表路径分隔符
- #endif
- string jsonReq = writer.write(rootReq);
- qTempReq.url = httpUrl;
- qTempReq.paramContent = jsonReq;
- qTempReq.fileName = m_fsm->m_currUploadFile->fileName;
- qTempReq.fileContent = fileContent;
- qTempReq.fileContentSize= fileContentSize;
- qTempReq.m_timeOut = 5*60;//设置超时时间
- //qTempReq.m_printDbg=true;
- //调用上传接口
- //Dbg("测试上传接口:filelen=%d",fileContentSize);
- if(!client->UploadFileBlock(qTempReq,qTempRet)){
- //Dbg("uploadFile http req fail ,url =%s ,fileName = %s",httpUrl.c_str(), m_fsm->m_currUploadFile->fileName.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http req fail ,url =%s ,fileName = %s",httpUrl.c_str(), m_fsm->m_currUploadFile->fileName.c_str());
- return false;
- }
- if(qTempRet.httpCode!=200){
- //Dbg("uploadFile http req fail ,retHttpCode=%d, fileName = %s",qTempRet.httpCode, m_fsm->m_currUploadFile->fileName.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http req fail ,url =%s ,retHttpCode=%d, fileName = %s",httpUrl.c_str(), qTempRet.httpCode, m_fsm->m_currUploadFile->fileName.c_str());
- return false;
- }
- //Dbg("qTempRet=%s",qTempRet.strBody.c_str());
- //解析回应报文
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.strBody, rootRet, false))
- {
- //Dbg("uploadFile http parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->fileName.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->fileName.c_str());
- return false;//解析失败
- }
- uploadData.strBody = qTempRet.strBody;
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- uploadData.uploaded_length= rootRet["data"]["uploaded_length"].asInt();
- uploadData.upload_finish = rootRet["data"]["upload_finish"].asBool();
- uploadData.branchFilePath = rootRet["data"]["branch_file_path"].asCString();
- return true;//返回值
- }else{
- //Dbg("uploadFile http [success][data] is invaild , fileName = %s",m_fsm->m_currUploadFile->fileName.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http [success][data] is invaild ,url =%s, fileName = %s",httpUrl.c_str(),m_fsm->m_currUploadFile->fileName.c_str());
- return false;//无data字段
- }
- }else{
- //失败
- //Dbg("uploadFile http [success] is false, userCode[%s],errmsg[%s],fileName = %s",qTempRet.m_userCode.c_str(),qTempRet.m_errMsg.c_str(),m_fsm->m_currUploadFile->fileName.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("uploadFileImpl")("uploadFile http [success] is false, url[%s],userCode[%s],errmsg[%s],fileName = %s",httpUrl.c_str(),qTempRet.m_userCode.c_str(),qTempRet.m_errMsg.c_str(),m_fsm->m_currUploadFile->fileName.c_str());
- return false;
- }
- }
- //查询临时文件 post
- bool queryTempFile(IHttpFunc* client,CSystemStaticInfo info){
- UploadQueryTempFileReq qTempReq;
- UploadQueryTempFileRet qTempRet;
- qTempRet.m_userCode ="";
- qTempRet.m_errMsg="";
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
- rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
- rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- //qTempReq.m_printDbg = true;
- qTempReq.m_url=m_fsm->m_centerUrl.queryTempFileUrl;//访问地址
- if(!client->Post(qTempReq, qTempRet)){
- //Dbg("queryTempFile http req fail ,fileName = %s, err=%s",m_fsm->m_currUploadFile->filePath.c_str(),qTempRet.m_errMsg.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryTempFile")("queryTempFile http req fail ,fileName = %s, err=%s",m_fsm->m_currUploadFile->filePath.c_str(),qTempRet.m_errMsg.c_str());
- return false;
- }
- //解析报文
- //Dbg("qTempRet=%s",qTempRet.m_retStr.c_str());
- //解析回应报文
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- //Dbg("queryTempFile parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryTempFile")("queryTempFile parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
- m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
- return false;//解析失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- if(rootRet["data"]["upload_flag"].asBool()){
- return true;//查询有
- }else{
- return false;//查询没有
- }
- }else{
- m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
- return false;//无data字段
- }
- }else{
- //Dbg("queryTempFile [success] is false, fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryTempFile")("queryTempFile [success] is false, fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
- m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
- return false;
-
- }
- }
- //登记文件流水状态 post
- bool updateState(IHttpFunc* client,CSystemStaticInfo info,bool isLanTerminal, string MD5str,string branchFilePath, string &errmsg){
- if(!isLanTerminal){
- return true;//行外默认是总行那边登记交易流水,终端不再发送交易流水登记,直接返回成功
- }
- UploadUpdateStateReq updateStateReq;
- UploadUpdateStateRet updateStateRet;
- updateStateRet.m_userCode="";
- updateStateRet.m_errMsg="";
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
- rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
- rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
- rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
- rootReq["branch_file_path"] = branchFilePath.c_str();
- rootReq["file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();
- if(isLanTerminal){
- rootReq["status"] = "1";//分行
- }else{
- rootReq["status"] = "2";//总行
- }
- rootReq["upload_time"] = CSmallDateTime::GetNow().ToTimeString().GetData();
- rootReq["remark"] = "";
- rootReq["sm3"] = MD5str.c_str();
- string jsonReq = writer.write(rootReq);
- updateStateReq.m_reqStr = jsonReq;//请求参数
- updateStateReq.m_url=m_fsm->m_centerUrl.updateStateUrl;//访问地址
- if(!client->Post(updateStateReq, updateStateRet)){
- //Dbg("updateState is fail, sysCode=%d , userCode = %s, errmsg = %s",updateStateRet.m_sysCode, updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("updateState")("updateState is fail, userCode = %s, errmsg = %s",updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
- errmsg = CSimpleStringA::Format("updateState is fail, userCode = %s, errmsg = %s",updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
- return false;
- }
- //解析报文
- //Dbg("updateStateRet=%s",updateStateRet.m_retStr.c_str());
- //解析回应报文
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(updateStateRet.m_retStr, rootRet, false))
- {
- errmsg="return pack parse is fail";
- return false;//解析失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- if(rootRet["data"]["update_flag"].asBool()){
- return true;//登记成功
- }else{
- errmsg="return pack [data][update_flag] is not bool";
- return false;//登记失败
-
- }
- }else{
- errmsg="return pack [data] is null";
- return false;//无data字段
- }
- }else{
- errmsg="return pack [success] is false";
- return false;
- }
- }
- //登记失败文件流水 post
- bool addUploadFail(IHttpFunc* client,CSystemStaticInfo info,bool isLanTerminal,string operation,string errmsg){
- UploadUploadFailReq updateFailReq;
- UploadUploadFailRet updateFailRet;
- updateFailRet.m_userCode="";
- updateFailRet.m_errMsg="";
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
- rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
- rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
- if(isLanTerminal){
- rootReq["stage"] = "1";//分行
- }else{
- rootReq["stage"] = "2";//总行
- }
- rootReq["operation"] = operation;
- rootReq["upload_time"] = CSmallDateTime::GetNow().ToTimeString().GetData();//2021-03-11 10:20:02
- rootReq["reason"] = errmsg.c_str();
- rootReq["remark"] = "";
- string jsonReq = writer.write(rootReq);
- updateFailReq.m_reqStr = jsonReq;//请求参数
- updateFailReq.m_url = m_fsm->m_centerUrl.addUploadFailUrl;//访问地址
- if(!client->Post(updateFailReq, updateFailRet)){
- //Dbg("addUploadFail is fail, sysCode=%d , userCode = %s",updateFailRet.m_sysCode, updateFailRet.m_userCode.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("addUploadFail")("addUploadFail is fail,userCode = %s",updateFailRet.m_userCode.c_str());
- return false;
- }
- //解析报文
- //Dbg("updateFailRet=%s",updateFailRet.m_retStr.c_str());
- //解析回应报文
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(updateFailRet.m_retStr, rootRet, false))
- {
- return false;//解析失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- if(rootRet["data"]["update_flag"].asBool()){
- return true;//登记成功
- }else{
- return false;//登记失败
- }
- }else{
- return false;//无data字段
- }
- }else{
- //Dbg("addUploadFail [success] is false");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("addUploadFail")("addUploadFail [success] is false");
- return false;
- }
- }
-
- //上传后文件处理
- bool operateFile(string &errmsg){
- if(m_fsm->m_currUploadFile->after_deal_type=="D"){
- #ifdef RVC_OS_WIN
- if(remove(m_fsm->m_currUploadFile->filePath.c_str())==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is ok, file =%s",m_fsm->m_currUploadFile->filePath.c_str());
- return true;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(),(int)GetLastError());
- errmsg = CSimpleStringA::Format("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(),(int)GetLastError());
- return false;
- }
- #else
- if (changeFileAtt(m_fsm->m_currUploadFile->filePath.c_str()) == 0) {
- if (remove(m_fsm->m_currUploadFile->filePath.c_str()) == 0) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is ok, file =%s",m_fsm->m_currUploadFile->filePath.c_str());
- return true;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is error,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
- errmsg = CSimpleStringA::Format("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete file is error,changefileAtt fail,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
- errmsg = CSimpleStringA::Format("delete file is error,changefileAtt fail,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
- return false;
- }
- #endif
- }else if(m_fsm->m_currUploadFile->after_deal_type=="M"){
- string destPath="";
- string destDir="";
- //根据路径类型组成最后移动路径
- if(m_fsm->m_currUploadFile->path_type=="R"){
- #ifdef RVC_OS_WIN
- destPath = m_fsm->m_rootPath+"\\"+m_fsm->m_currUploadFile->after_deal_text+"\\"+m_fsm->m_currUploadFile->fileName;
- destDir = m_fsm->m_rootPath+"\\"+m_fsm->m_currUploadFile->after_deal_text;
- #else
- destPath = m_fsm->m_rootPath + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->after_deal_text + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->fileName;
- destDir = m_fsm->m_rootPath + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->after_deal_text;
- #endif
- }else{
- #ifdef RVC_OS_WIN
- destPath = m_fsm->m_currUploadFile->after_deal_text+"\\"+m_fsm->m_currUploadFile->fileName;
- #else
- destPath = m_fsm->m_currUploadFile->after_deal_text + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->fileName;
- #endif
- destDir = m_fsm->m_currUploadFile->after_deal_text;
- }
- string srcPath = m_fsm->m_currUploadFile->filePath;
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file %s to %s",srcPath.c_str(),destPath.c_str());
- //判断是否存在目标文件,如存在,则先删除
- #ifdef RVC_OS_WIN
- if(ExistsFileA(destPath.c_str())){
- if(remove(destPath.c_str())==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is ok [%s]",destPath.c_str());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is error, errno=%d, [%s]",(int)GetLastError(),destPath.c_str());
- errmsg = CSimpleStringA::Format("delete dest file is error, errno=%d, [%s]",(int)GetLastError(),destPath.c_str());
- return false;
- }
- }
- //判断移动目标文件夹是否存在,不存在,则创建
- if(!ExistsDirA(destDir.c_str())){
- if(!CreateDirRecursiveA(destDir.c_str())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("create dest dir [%s] is error, errno=%d",destDir.c_str(),GetLastError());
- errmsg = CSimpleStringA::Format("create dest dir [%s] is error, errno=%d",destDir.c_str(),GetLastError());
- return false;
- }
- }
- //移动文件
- int i;
- int tries = 10;
- bool isSucc = false;
- for (i = 0; i < tries; ++i) {
- if(rename(srcPath.c_str(),destPath.c_str())==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file ok! tries:%d, [%s] to [%s] ", i, srcPath.c_str(),destPath.c_str());
- isSucc = true;
- break;
- } else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file failed! errno:%d, [%s] to [%s] ", (int)GetLastError(), srcPath.c_str(),destPath.c_str());
- errmsg = CSimpleStringA::Format("move file failed! errno:%d, [%s] to [%s] ", (int)GetLastError(), srcPath.c_str(),destPath.c_str());
- Sleep(1000);
- }
- }
- return isSucc;
- #else
- if (ExistsFileA(destPath.c_str())) {
- if (changeFileAtt(destPath.c_str()) == 0) {
- if (remove(destPath.c_str()) == 0) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is ok [%s]",destPath.c_str());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is error, errno=%d, [%s]", errno, destPath.c_str());
- errmsg = CSimpleStringA::Format("delete src file is error, errno=%d, [%s]", errno, destPath.c_str());
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("delete dest file is error,changefileAtt fail ,errno=%d , file=%s ", errno, destPath.c_str());
- errmsg = CSimpleStringA::Format("delete src file is error, changefileAtt fail, errno=%d, file=%s", errno, destPath.c_str());
- return false;
- }
- }
- //判断移动目标文件夹是否存在,不存在,则创建
- if (!ExistsDirA(destDir.c_str())) {
- if (!CreateDirRecursiveA(destDir.c_str())) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("create dest dir [%s] is error, errno=%d", destDir.c_str(), errno);
- errmsg = CSimpleStringA::Format("create dest dir [%s] is error, errno=%d", destDir.c_str(), errno);
- return false;
- }
- }
- //移动文件
- if (changeFileAtt(srcPath.c_str()) == 0)
- {
- int i;
- int tries = 10;
- bool isSucc = false;
- for (i = 0; i < tries; ++i) {
- //rename函数对于跨分支的目录存在拷贝不成功的情况,故采用先拷贝后删除的操作修复此bug
- if (fileutil_copy_file(destPath.c_str(), srcPath.c_str()) == 0) {
- if (remove(srcPath.c_str()) == 0) {
- //Dbg("move ok! tries:%d", i);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file ok! tries:%d, [%s] to [%s] ", i, srcPath.c_str(),destPath.c_str());
- isSucc = true;
- break;
- }
- else {
- //Dbg("move %s -> %s failed! delete src file fail, errno:%d", srcPath.c_str(), destPath.c_str(), errno);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file failed! errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
- errmsg = CSimpleStringA::Format("move file failed! errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
- Sleep(1000);
- }
- }
- else {
- //Dbg("move %s -> %s failed! copy src file fail, errno:%d", srcPath.c_str(), destPath.c_str(), errno);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file failed! copy src file fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
- errmsg = CSimpleStringA::Format("move file failed! copy src file fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
- Sleep(1000);
- }
- }
- return isSucc;
- }
- else {
- //Dbg("move %s -> %s failed! , changefileAtt fail,errno=%d", srcPath.c_str(), destPath.c_str(), errno);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("move file failed! changefileAtt fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
- errmsg = CSimpleStringA::Format("move file failed! changefileAtt fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
- return false;
- }
- #endif
- }else if(m_fsm->m_currUploadFile->after_deal_type=="N"){
- return true;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("operateFile")("file [%s] invalid after_deal_type=%s",m_fsm->m_currUploadFile->fileName.c_str(),m_fsm->m_currUploadFile->after_deal_type.c_str());
- errmsg = CSimpleStringA::Format("invalid after_deal_type=%s",m_fsm->m_currUploadFile->after_deal_type.c_str());
- return false;
- }
- }
- };
- }
- void UploadFSM::OnStateTrans( int iSrcState, int iDstState )
- {
- //Dbg("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnStateTrans")("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
- }
- void UploadFSM::OnSysVarEvent( const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName )
- {
- //Dbg("rx sysvar %s from %s, %s to %s", pszKey, pszEntityName, pszOldValue, pszValue);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnSysVarEvent")("rx sysvar %s from %s, %s to %s", pszKey, pszEntityName, pszOldValue, pszValue);
- if (pszValue[0] == 'O') {
- m_isOffLine = true;
- PostEventFIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
- } else {
- m_isOffLine = false;
- PostEventFIFO(new FSMEvent(USER_EVT_JMP_DISABLE));
- }
- }
- ErrorCodeEnum UploadFSM::OnInit()
- {
- ErrorCodeEnum Error;
- CSimpleStringA checkStr="";
- CSmartPointer<IConfigInfo> spConfig;
- Error = m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
-
- if(Error==Error_Succeed){
- //获取模式控制参数
- m_centerModel = (int)centerModel;//强制总行模式
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("OnInit")("model is centerModel, CenterModel = %d", m_centerModel);
- //增加总行接口Url参数
- CSimpleStringA str="";
- Error = spConfig->ReadConfigValue("upload", "QueryPlanUrl", str);
- if (Error == Error_Succeed)
- {
- //Dbg("[CenterUrl] QueryPlanUrl =%s",str.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] QueryPlanUrl =%s",str.GetData());
- m_centerUrl.queryPlanUrl = str.GetData();
- }
- else
- {
- return Error;
- }
- Error = spConfig->ReadConfigValue("upload", "QueryTempFileUrl", str);
- if (Error == Error_Succeed)
- {
- //Dbg("[CenterUrl] QueryTempFileUrl =%s",str.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] QueryTempFileUrl =%s",str.GetData());
- m_centerUrl.queryTempFileUrl = str.GetData();
- }
- else
- {
- return Error;
- }
- Error = spConfig->ReadConfigValue("upload", "UpdateStateUrl", str);
- if (Error == Error_Succeed)
- {
- //Dbg("[CenterUrl] UpdateStateUrl =%s",str.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] UpdateStateUrl =%s",str.GetData());
- m_centerUrl.updateStateUrl = str.GetData();
- }
- else
- {
- return Error;
- }
- Error = spConfig->ReadConfigValue("upload", "AddUploadFailUrl", str);
- if (Error == Error_Succeed)
- {
- //Dbg("[CenterUrl] AddUploadFailUrl =%s",str.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] AddUploadFailUrl =%s",str.GetData());
- m_centerUrl.addUploadFailUrl = str.GetData();
- }
- else
- {
- return Error;
- }
- Error = spConfig->ReadConfigValue("upload", "EachUploadLen", str);
- if (Error == Error_Succeed)
- {
- //Dbg("[CenterUrl] EachUploadLen =%s",str.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] EachUploadLen =%s",str.GetData());
- if(str.IsNullOrEmpty()){
- m_eachUploadLen = UPLOAD_CONTENT_EACH_LEN;
- }else{
- m_eachUploadLen = atoi(str.GetData())*1024;
- }
- }
- else
- {
- return Error;
- }
- int uploadMaxNum = 0;
- Error = spConfig->ReadConfigValueInt("upload", "UploadMaxNum", uploadMaxNum);
- if (Error == Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("[CenterUrl] UploadMaxNum =%d",uploadMaxNum);
- if(uploadMaxNum<=10){
- m_uploadMaxNum = 1000;
- }else{
- m_uploadMaxNum = uploadMaxNum;
- }
- }
- else
- {
- return Error;
- }
- //获取系统文件根路径
- CSimpleStringA runPath ;
- Error =this->GetEntityBase()->GetFunction()->GetPath("Root",runPath);//例如:C:\\Run /opt/Run
- if(Error_Succeed == Error){
- if(!runPath.IsNullOrEmpty()){
- string runPathStr = runPath.GetData();
- #ifdef RVC_OS_WIN
- int pos = runPathStr.find_last_of('\\');
- #else
- int pos = runPathStr.find_last_of(SPLIT_SLASH);//修改为路径分隔符
- #endif
-
- m_rootPath = runPathStr.substr(0,pos);
- //Dbg("get Root path is %s",m_rootPath.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("get Root path is %s",m_rootPath.c_str());
- }else{
- //Dbg("get Root path is null");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("get Root path is null");
- return Error_Unexpect;
- }
- }else{
- //Dbg("get Root path is error");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("get Root path is error");
- return Error_Unexpect;
- }
- }else{
- return Error;
- }
-
-
- Error = m_pEntity->GetFunction()->RegistSysVarEvent("CallState", this);
-
- if (Error == Error_Succeed) {
- AddStateHooker(this);
- }
- //......
- return Error;
- }
- ErrorCodeEnum UploadFSM::OnExit()
- {
- m_pEntity->GetFunction()->UnregistSysVarEvent("CallState");
- return Error_Succeed;
- }
- void UploadFSM::s0_on_entry()
- {
- CSimpleStringA strValue;
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetSysVar("CallState", strValue);
- if (Error == Error_Succeed) {
- if (strValue[0] == 'O') { // only upload when CallState in offline state
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
- } else {
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_DISABLE));
- }
- }
- }
- void UploadFSM::s0_on_exit()
- {
- }
- unsigned int UploadFSM::s0_on_event( FSMEvent* event )
- {
- return 0;
- }
- void UploadFSM::s1_on_entry()
- {
- ScheduleTimer(8, 30000);
- }
- void UploadFSM::s1_on_exit()
- {
- CancelTimer(8);
- }
- unsigned int UploadFSM::s1_on_event(FSMEvent* event)
- {
- if (event->iEvt == EVT_TIMER) {
- if(m_isOffLine){
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
- }else{
- ScheduleTimer(8, 30000);//继续等待
- }
- }
- return 0;
- }
- void UploadFSM::s2_on_entry()
- {
- m_uploadModel = true;//默认总行上传模式
- //清理上次扫描文件列表,扫描计划,分行ip列表
- if(m_uploadList!=NULL){
- list<UploadFileInfo*>::iterator iter ;
- for(iter=m_uploadList->begin();iter!=m_uploadList->end();++iter){
- delete *iter;
- }
- m_uploadList->clear();
- }
- if(m_uploadPlanList!=NULL){
- list<UploadPlan*>::iterator iter ;
- for(iter=m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
- delete *iter;
- }
- m_uploadPlanList->clear();
- }
- m_branchIpList.clear();
- if(m_centerModel == (int)centerModel){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel");
- //防止url无效,新模式直接停止上传 等待下一次
- if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
- m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel mode ,centerUrl is null , wait for next time");
- ScheduleTimer(1, 120000);
- return ;
- }
- //新模式,查询策略
- if(queryPlan()){
- m_uploadModel = true;
- }else{
- //查询策略失败,等待下一次
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("queryPlan is fail , wait for next time");
- ScheduleTimer(1, 120000);
- return ;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_centerModel is invalid");
- ScheduleTimer(1, 120000);
- return;
- }
- if(m_uploadModel){
- //新模式扫描
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_SCAN));
- }else{
- //旧模式扫描
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_OLD_SCAN));
- }
- }
- void UploadFSM::s2_on_exit()
- {
- CancelTimer(1);
- }
- unsigned int UploadFSM::s2_on_event(FSMEvent* event)
- {
- if (event->iEvt == EVT_TIMER) {
- m_uploadModel = true;//默认是分行上传模式
- //清理上次扫描文件列表,扫描计划,分行ip列表
- if(m_uploadList!=NULL){
- list<UploadFileInfo*>::iterator iter ;
- for(iter=m_uploadList->begin();iter!=m_uploadList->end();++iter){
- delete *iter;
- }
- m_uploadList->clear();
- }
- if(m_uploadPlanList!=NULL){
- list<UploadPlan*>::iterator iter ;
- for(iter=m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
- delete *iter;
- }
- m_uploadPlanList->clear();
- }
- m_branchIpList.clear();
-
- //上传模式确定
- if(m_centerModel == (int)centerModel){
- //Dbg("centerModel");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel");
- //防止url无效,新模式直接停止上传,等待下一次
- if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
- m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
- //Dbg("centerModel mode ,centerUrl is null , wait for next time");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel mode ,centerUrl is null , wait for next time");
- ScheduleTimer(1, 240000);
- return 0;
- }
- //新模式,查询策略
- if(queryPlan()){
- m_uploadModel = true;
- }else{
- //查询策略失败,等待下一次
- //Dbg("queryPlan is fail , wait for next time");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("queryPlan is fail , wait for next time");
- ScheduleTimer(1, 240000);
- return 0;
- }
- }else{
- //Dbg("m_centerModel is invalid");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_centerModel is invalid");
- ScheduleTimer(1, 240000);
- return 0;
- }
- if(m_uploadModel){
- //新模式扫描
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_SCAN));
- }else{
- //旧模式扫描
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_OLD_SCAN));
- }
-
- }else if (event->iEvt == USER_EVT_JMP_NEW_SCAN) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("enter new model upload");
- //新模式
- if (m_uploadList->size() == 0) {
- //重新扫描文件
- scanFile();
- }
- if (m_uploadList->size() == 0) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_uploadList is 0,wait for 8 min retry scan");
- ScheduleTimer(1, 480000);
- } else {
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_UPLOAD));//跳到新的上传状态
- }
- }
- return 0;
- }
- void UploadFSM::s3_on_entry()
- {
- }
- void UploadFSM::s3_on_exit()
- {
- }
- unsigned int UploadFSM::s3_on_event(FSMEvent* event)
- {
- return 0;
- }
- void UploadFSM::s4_on_entry()
- {
- }
- void UploadFSM::s4_on_exit()
- {
- }
- unsigned int UploadFSM::s4_on_event(FSMEvent* event)
- {
- return 0;
- }
- void UploadFSM::s5_on_entry()
- {
- }
- void UploadFSM::s5_on_exit()
- {
- }
- unsigned int UploadFSM::s5_on_event(FSMEvent* event)
- {
- return 0;
- }
- void UploadFSM::s6_on_entry()
- {
- }
- void UploadFSM::s6_on_exit()
- {
- }
- unsigned int UploadFSM::s6_on_event(FSMEvent* event)
- {
- return 0;
- }
- void UploadFSM::s7_on_entry()
- {
- //新上传模式
- m_uploadReport.sum = m_uploadList->size();
- m_uploadReport.succ = 0;
- m_uploadReport.fail = 0;
- m_uploadReport.uploadFail = 0;
- m_uploadReport.updateState = 0;
- m_uploadReport.decodeFail = 0;
- m_uploadReport.operateFileFail= 0;
- m_uploadReport.queryTempFail =0;
- m_uploadReport.isBreak =false;
- //获取一个新文件,发送上传请求线程
- if(m_uploadList->size()>0){
- m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
- m_uploadList->pop_front();//去除首元素
- Task::SendFileTask* task = new Task::SendFileTask(this);
- ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- if (rc != Error_Succeed)
- {
- if(m_currUploadFile!=NULL){
- delete m_currUploadFile;
- m_currUploadFile=NULL;
- }
- LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 30s retry");
- ScheduleTimer(7, 30000);
- }
- }
- }
- void UploadFSM::s7_on_exit()
- {
- if(m_currUploadFile!=NULL){
- delete m_currUploadFile;
- m_currUploadFile=NULL;
- }
- CancelTimer(7);
- }
- unsigned int UploadFSM::s7_on_event(FSMEvent* event)
- {
- if (event->iEvt == USER_EVT_UPLOAD_SUCC) {
- m_uploadReport.succ++;//成功计数
- //获取新的上传文件,发送上传请求线程
- //判断是否已经需要退出
- //无文件,跳出此状态
- if(m_isOffLine){
- if(m_uploadList->size()>0){
- if(m_currUploadFile!=NULL){
- delete m_currUploadFile;
- m_currUploadFile=NULL;
- }
- m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
- m_uploadList->pop_front();//去除首元素
- Task::SendFileTask* task = new Task::SendFileTask(this);
- ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- if (rc != Error_Succeed)
- {
- if(m_currUploadFile!=NULL){
- delete m_currUploadFile;
- m_currUploadFile=NULL;
- }
- m_uploadReport.isBreak =true;
- reportBatchMsg();
- LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 240s retry scan");
- ScheduleTimer(7, 240000);
- }
- }else{
- m_uploadReport.isBreak =false;
- reportBatchMsg();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_uploadList is empty,wait 240s retry scan");
- ScheduleTimer(7, 240000);// goto s2
- }
- }else{
- m_uploadReport.isBreak =true;
- reportBatchMsg();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_isOffLine is false,jump s1");
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_DISABLE));// goto s1
- }
-
- }else if (event->iEvt == USER_EVT_UPLOAD_FAIL) {
- m_uploadReport.fail++;//失败计数
- //获取新的上传文件,发送上传请求线程
- //判断是否已经需要退出
- //无文件,跳出此状态
- if(m_isOffLine){
- Sleep(3000);//上传失败,等待3秒再下一个
- if(m_uploadList->size()>0){
- if(m_currUploadFile!=NULL){
- delete m_currUploadFile;
- m_currUploadFile=NULL;
- }
- m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
- m_uploadList->pop_front();//去除首元素
- Task::SendFileTask* task = new Task::SendFileTask(this);
- ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
- if (rc != Error_Succeed)
- {
- if(m_currUploadFile!=NULL){
- delete m_currUploadFile;
- m_currUploadFile=NULL;
- }
- m_uploadReport.isBreak =true;
- reportBatchMsg();
- LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 240s retry scan");
- ScheduleTimer(7, 240000);
- }
- }else{
- m_uploadReport.isBreak =false;
- reportBatchMsg();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_uploadList is empty,wait 240s retry scan");
- ScheduleTimer(7, 240000);// goto s2
- }
- }else{
- m_uploadReport.isBreak =true;
- reportBatchMsg();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_isOffLine is false,jump s1");
- PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_DISABLE));// goto s1
- }
-
- }else if (event->iEvt == EVT_TIMER) {
- // goto s2
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload ,jump to s2");
- }
-
- return 0;
- }
- //通过
- bool UploadFSM::queryPlan()
- {
- //Dbg("queryPlan");
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan begin");
- IHttpFunc* client;
- client = create_http(HttpsLogCallBack);
- CSystemStaticInfo si;
- ErrorCodeEnum error = this->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
- if(error!=Error_Succeed){
- return false;//获取失败,走旧模式
- }
- UploadQueryPlanReq planReq;
- UploadQueryPlanRet planRet;
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = si.strTerminalID.GetData();
- #ifdef RVC_OS_WIN
- rootReq["os_type"] = "WIN";
- #else
- rootReq["os_type"] = "UOS";
- #endif
-
- string jsonReq = writer.write(rootReq);
-
- planReq.m_reqStr = jsonReq;
- //planReq.m_printDbg = true;
- planReq.m_url = m_centerUrl.queryPlanUrl.c_str();
- if(!client->Post(planReq, planRet)){
- //Dbg("queryPlan http req fail,url is %s",m_centerUrl.queryPlanUrl.c_str());
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_ERROR, CSimpleStringA::Format("queryPlan http req fail,url is %s, err=%s",m_centerUrl.queryPlanUrl.c_str(),planRet.m_errMsg.c_str()).GetData());
- client->Destory();
- return false;//http错误,走旧模式
- }
- client->Destory();
- //Dbg("planRet=%s",planRet.m_retStr.c_str());
- //解析回应报文
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(planRet.m_retStr, rootRet, false))
- {
- //Dbg("queryPlan parse resp is fail");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan parse resp is fail");
- return false;//解析失败,走旧模式
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- if(rootRet["data"]["mode"].asBool()){
- //新模式
- string branchNO = rootRet["data"]["branch_no"].asString();
- //分行服务器列表:可能为空
- if(rootRet["data"]["upload_address"].isMember("upload_url")){
- for(int i =0;i<rootRet["data"]["upload_address"]["upload_url"].size();i++){
- string bUploadUrl = rootRet["data"]["upload_address"]["upload_url"][i].asString();
- m_branchIpList[i+1]=bUploadUrl;
- //Dbg("queryPlan return upload_url=%s",bUploadUrl.c_str());
- if(!bUploadUrl.empty()){
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return upload_url=%s",bUploadUrl.c_str());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return upload_url=");
- }
- }
- }else{
- //Dbg("[data][upload_address][upload_url] is null");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("[data][upload_address][upload_url] is null");
- }
- string env = "";//上传服务器地址属于行内还是行外
- if(rootRet["data"]["upload_address"].isMember("env")){
- env = rootRet["data"]["upload_address"]["env"].asString();
- if(strcmp(env.c_str(),"DMZ")==0||strcmp(env.c_str(),"BIZ")==0){
- }else{
- //Dbg("[data][upload_address][env] is invaild [%s]",env.c_str());
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_DATA_ERROR, CSimpleStringA::Format("queryPlan http req fail, return [data][upload_address][env] is invaild [%s]",env.c_str()).GetData());
- return false;//上传服务ip环境不正确,走旧模式
- }
- }else{
- //Dbg("[data][upload_address][env] is null");
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_DATA_ERROR, CSimpleStringA::Format("queryPlan http req fail, return [data][upload_address][env] is null").GetData());
- return false;//上传服务ip环境为空,走旧模式
- }
- //扫描策略:可能为空
- for (int i =0;i <rootRet["data"]["plan_list"].size();i++){
- UploadPlan* p = new UploadPlan();
- p->plan_id = rootRet["data"]["plan_list"][i]["plan_id"].asString();
- p->branch_no = branchNO;//分行号
- p->plan_type = rootRet["data"]["plan_list"][i]["plan_type"].asString();
- p->file_type = rootRet["data"]["plan_list"][i]["file_type"].asString();
- p->path_type = rootRet["data"]["plan_list"][i]["path_type"].asString();
- #ifdef RVC_OS_WIN
- p->path_name = rootRet["data"]["plan_list"][i]["path_name"].asString();
- #else
- //转义路径里面windows反斜杠'\'为'/'
- //p->path_name = rootRet["data"]["plan_list"][i]["path_name"].asString();
- string pathName = rootRet["data"]["plan_list"][i]["path_name"].asString();
- std::replace(pathName.begin(), pathName.end(), '\\', SPLIT_SLASH);
- p->path_name = pathName.c_str();
- #endif
-
- p->file_name = rootRet["data"]["plan_list"][i]["file_name"].asString();
- p->file_regex = rootRet["data"]["plan_list"][i]["file_regex"].asString();
- p->before_deal_type = rootRet["data"]["plan_list"][i]["before_deal_type"].asString();
- p->after_deal_type = rootRet["data"]["plan_list"][i]["after_deal_type"].asString();
- #ifdef RVC_OS_WIN
- p->after_deal_text = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
- #else
- //转义路径里面windows反斜杠'\'为'/'
- //p->after_deal_text = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
- string afterDealText = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
- std::replace(afterDealText.begin(), afterDealText.end(), '\\', SPLIT_SLASH);
- p->after_deal_text = afterDealText.c_str();
- #endif
- p->file_limit = rootRet["data"]["plan_list"][i]["file_limit"].asInt();
- p->file_length_limit = rootRet["data"]["plan_list"][i]["file_length_limit"].asInt();//增加扫描文件最大长度限制
- if(p->file_length_limit==0){
- //默认扫描文件最大长度设置为200m
- p->file_length_limit = 200;
- }
- p->max_silent = rootRet["data"]["plan_list"][i]["max_silent"].asInt();
- p->upload_address_env = env;
- m_uploadPlanList->push_back(p);
- }
- //行内需要判断分行服务url地址(废弃用终端场所判断,统一由后台服务返回文件上传地址)
- //if(si.strSite.Compare("CMB.LIB",true)==0||si.strSite.Compare("CMB.SSB",true)==0){
- // if(m_branchIpList.size()==0){
- // return false;//告警分行服务ip为空,走旧模式
- // }
- //}
- if(m_branchIpList.size()==0){
- //Dbg("queryPlan return upload_url count is 0");
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_PLAN_DATA_ERROR, CSimpleStringA::Format("queryPlan http req fail, return upload_url count is 0, url is %s",m_centerUrl.queryPlanUrl.c_str()).GetData());
- return false;//上传服务ip为空,走旧模式
- }
-
- if(m_uploadPlanList->size()==0){
- //Dbg("queryPlan return %d plan ",m_uploadPlanList->size());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return %d plan ",m_uploadPlanList->size());
- return true;//等待下一次请求,走新模式
- }
- return true;//明确走新模式
- }else{
- //Dbg("queryPlan return [data].[mode] is false");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return [data].[mode] is false");
- return false;//明确走旧模式
- }
- }else{
- //Dbg("queryPlan return data is null");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return data is null");
- return false;//无data字段,走旧模式
- }
- }else{
- //Dbg("queryPlan return success is false");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("queryPlan")("queryPlan return success is false");
- return false;//服务返回错误,走旧模式
- }
- }
- //通过
- void UploadFSM::scanFile()
- {
- list<UploadPlan*>::iterator iter;
- for(iter = m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
- UploadPlan* up = *iter;
- //构建初始的扫描根路径
- string path="";
- if(up->path_type=="R"){
- #ifdef RVC_OS_WIN
- path = m_rootPath + "\\" + up->path_name;
- #else
- path = m_rootPath + SPLIT_SLASH_STR + up->path_name;
- #endif
- }else if(up->path_type=="A"){
- path=up->path_name;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanFile")("plan path_type is invalid path_type=%s",up->path_type.c_str());
- continue;
- }
- if(m_printPlan){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanFile")("planID=[%s], scanDir=[%s], filter=[%s], max_silent=[%d]",up->plan_id.c_str(),path.c_str(),up->file_name.c_str(),up->max_silent);
- }
- scanDirfresh(up,path.c_str());
- }
- m_printPlan=false;//只打印一次,设置为不打印
- //加入文件超过阈值后告警
- if(m_uploadList->size()>m_uploadMaxNum){
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_MAX_ERROR, CSimpleStringA::Format("upload list num(%d) is over max num",m_uploadList->size()).GetData());
- }
- }
- //通过
- void UploadFSM::scanDirfresh(UploadPlan* plan,const char *path)
- {
- //Dbg("scan dir=%s",path);
- array_header_t *arr_files = fileutil_get_sub_files2_a(path, plan->file_limit);
- if (arr_files) {
- int i;
- for (i = 0; i < arr_files->nelts; ++i){
- char *file_path = ARRAY_IDX(arr_files, i, char*);
- //Dbg("find file src path=%s",file_path);
- //得到文件名
- string fileName = _GetFileName(file_path);
- //Dbg("fileName=%s",fileName.c_str());
- //文件名通配符过滤
- CSimpleStringA strFileFilter = _GetFileName(plan->file_name.c_str());
- //Dbg("strFileFilter=[%s]",strFileFilter.GetData());
- if(!IsFileMatch(strFileFilter.GetData(),fileName.c_str())){
- continue;//继续下一个文件
- }
- //正则表达式过滤
- if(!plan->file_regex.empty()){
- //Dbg("file_regex=[%s]",plan->file_regex.c_str());
- regex e(plan->file_regex.c_str());
- if(!regex_match(fileName.c_str(),e,regex_constants::match_default)){
- continue;//继续下一个文件
- }
- }
- #ifdef RVC_OS_WIN
- //最后修改时间间隔过滤
- WIN32_FILE_ATTRIBUTE_DATA attr;
- if (!GetFileAttributesExA(file_path, GetFileExInfoStandard, &attr)) {
- //Dbg("get local file attrr fail! file_path=%s",file_path);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanDirfresh")("get local file attrr fail! file_path=%s",file_path);
- continue;//继续下一个文件
- }
- //判断文件是否超过最大扫描文件长度
- unsigned long limit = plan->file_length_limit*1024*1024;
- if(attr.nFileSizeLow>limit){
- if (!findOverLenWarn(file_path)) {
- //未找到则告警
- CSimpleStringA warnStr = CSimpleStringA::Format("local file len (%u), over file_length_limit (%d)m, file_path=%s", attr.nFileSizeLow, plan->file_length_limit, file_path);
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_FILE_OVER_LIMIT, warnStr.GetData());
- }
- continue;//继续下一个文件
- }
- FILETIME fttmp;
- SYSTEMTIME filest;
- SYSTEMTIME st;
- if(!FileTimeToLocalFileTime(&attr.ftLastWriteTime,&fttmp)){
- continue;//继续下一个文件
- }
- if(!FileTimeToSystemTime(&fttmp,&filest)){
- continue;//继续下一个文件
- }
- GetLocalTime(&st);
- int nsecondsInterval = (st.wYear-filest.wYear)*32140800+(st.wMonth-filest.wMonth)*2678400+(st.wDay-filest.wDay)*86400+(st.wHour-filest.wHour)*3600+(st.wMinute-filest.wMinute)*60+(st.wSecond-filest.wSecond);
- if(nsecondsInterval<plan->max_silent){
- //Dbg("the time error! file_path=%s",file_path);
- continue;//继续下一个文件,时间不够
- }else{
- //时间已够,判断文件是否能独占锁
- if(!test_zero_ref(file_path)){
- continue;//继续下一个文件
- }
- }
- //得到文件长度
- unsigned long filelen = attr.nFileSizeLow;
- #else
- struct stat attr_of_src;
- if (lstat(file_path, &attr_of_src) != 0) {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanDirfresh")("get local file attrr fail! file_path=%s", file_path);
- continue;//继续下一个文件
- }
- //判断文件是否超过最大扫描文件长度
- unsigned long limit = plan->file_length_limit * 1024 * 1024;
- if (attr_of_src.st_size > limit) {
- CSimpleStringA warnStr = CSimpleStringA::Format("local file len (%u), over file_length_limit (%d)m, file_path=%s", attr_of_src.st_size, plan->file_length_limit, file_path);
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_FILE_OVER_LIMIT, warnStr.GetData());
- continue;//继续下一个文件
- }
- time_t nowTime = time((time_t*)NULL);//当前时间
- if (nowTime > attr_of_src.st_mtime)
- {
- long diff = nowTime - attr_of_src.st_mtime;
- if (diff < plan->max_silent)
- {
- //Dbg("the time error! file_path=%s",file_path);
- continue;//继续下一个文件,时间不够
- }else{
- //时间已够,判断文件是否能独占锁
- if (!test_zero_ref(file_path)) {
- continue;//继续下一个文件
- }
- }
- }else {
- //Dbg("the time error! file_path=%s",file_path);
- continue;//继续下一个文件,时间不够
- }
- //得到文件长度
- unsigned long filelen = attr_of_src.st_size;
- #endif
- //添加扫描文件
- UploadFileInfo* upFile = new UploadFileInfo();
- upFile->fileName = fileName;
- upFile->filePath = file_path;
- if(upFile->filePath.length()>900){
- //路径太长,ECS存储有问题,截取路径,并加入模拟路径前缀:window S:\\ , linux /S/
- #ifdef RVC_OS_WIN
- upFile->fileUploadPath.append("S:\\");
- #else
- upFile->fileUploadPath.append("/S/");
- #endif
- upFile->fileUploadPath.append(fileName.c_str());
- //upFile->fileUploadRelativePath = "S:\\";
- }else{
- //直接赋值
- upFile->fileUploadPath = file_path;
- //upFile->fileUploadRelativePath = upFile->fileUploadPath.substr(0,upFile->fileUploadPath.length()-fileName.length());//截取文件名称的路径
- }
- upFile->BranchFilePath = file_path;
- upFile->fileLen = filelen;
- #ifdef RVC_OS_WIN
- upFile->editTime = CSimpleStringA::Format("%d-%d-%d %d:%d:%d",filest.wYear, filest.wMonth, filest.wDay, filest.wHour, filest.wMinute, filest.wSecond);
- #else
- tm fileTimeTm = { 0 };
- localtime_r(&attr_of_src.st_mtime, &fileTimeTm);
- upFile->editTime = CSimpleStringA::Format("%d-%d-%d %d:%d:%d", fileTimeTm.tm_year+1900, fileTimeTm.tm_mon+1, fileTimeTm.tm_mday, fileTimeTm.tm_hour, fileTimeTm.tm_min, fileTimeTm.tm_sec);
- #endif
- upFile->plan_id = plan->plan_id;
- upFile->branch_no = plan->branch_no;
- upFile->plan_type = plan->plan_type;
- upFile->file_type = plan->file_type;
- upFile->path_type = plan->path_type;
- upFile->path_name = plan->path_name;//因传回路径可能是windows路径斜杠,转义为linux斜杠
- upFile->file_name = plan->file_name;
- upFile->file_regex = plan->file_regex;
- upFile->before_deal_type = plan->before_deal_type;
- upFile->after_deal_type = plan->after_deal_type;
- upFile->after_deal_text = plan->after_deal_text;
- upFile->file_limit = plan->file_limit;
- upFile->file_length_limit = plan->file_length_limit;
- upFile->max_silent = plan->max_silent;
- upFile->upload_address_env = plan->upload_address_env;
- m_uploadList->push_back(upFile);
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("scanDirfresh")("file %s lenth(%d) added!",file_path,filelen);
- }
- toolkit_array_free2(arr_files);
- }
- array_header_t *arr_dir = fileutil_get_sub_dirs_a(path);
- if (arr_dir) {
- int i;
- for (i = 0; i < arr_dir->nelts; ++i) {
- char *dir_path = ARRAY_IDX(arr_dir, i, char*);
- scanDirfresh(plan, dir_path);
- }
- }
- }
- void UploadFSM::HttpsLogCallBack(const char* logtxt)
- {
- //Dbg("%s",logtxt);
- if(logtxt!=NULL){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("HttpsLogCallBack")("http dbg: %s",logtxt);
- }
- }
- bool UploadFSM::IsFileMatch(const char *pszFilter, const char *pszFileName)
- {
- const char *p1 = pszFilter;
- const char *p2 = pszFileName;
- if (p1 == NULL)
- return true;
- if (p2 == NULL)
- return false;
- if (*p1 ==NULL && *p2 ==NULL)
- return true;
- else if (*p1 == NULL)
- return false;
- else if (*p2 == NULL)
- {
- // 查找*p1是否全是*
- while(*p1 == '*')
- p1++;
- if (*p1 == NULL)
- return true;
- else
- return false;
- }
- if (*p1 != '*')
- {
- if (tolower(*p1) != tolower(*p2))
- return false;
- else
- return IsFileMatch(p1+1, p2+1);
- }
- else
- {
- while(*++p1 == '*');
- if (*p1 == NULL)
- return true;
- while (*p2)
- {
- while(tolower(*p1) != tolower(*p2) && *++p2);
- if (*p2 == NULL)
- return false;
- if(IsFileMatch(p1+1, p2+1))
- return true;
- p2++;
- }
- return false;
- }
- }
- ErrorCodeEnum UploadFSM::SM3FileToStr(CSimpleStringA strFilePath, CSimpleStringA &strSM3,bool isSub)
- {
- if(strFilePath.IsNullOrEmpty()){
- return Error_Null;
- }
- int nlen = strlen(strFilePath.GetData());
- char* pchar = new char[nlen+1];
- strcpy(pchar,strFilePath.GetData());
- BYTE md5[32]={0};
- try
- {
- if(SM3File(pchar,md5)){
- delete pchar;
- //获取16进制的字符串
- if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
- //Dbg("sm3国密转16进制字符串失败,file=%s",strFilePath.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3国密转16进制字符串失败,file=%s",strFilePath.GetData());
- return Error_Unexpect;
- }
- return Error_Succeed;
- }else{
- delete pchar;
- //Dbg("sm3国密加密失败,file=%s",strFilePath.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3国密加密失败,file=%s",strFilePath.GetData());
- return Error_Unexpect;
- }
- }
- catch (...)
- {
- delete pchar;
- //Dbg("sm3国密加密异常失败,file=%s",strFilePath.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3国密加密异常失败,file=%s",strFilePath.GetData());
- return Error_Exception;
- }
- }
- ErrorCodeEnum UploadFSM::SM3_Str(CSimpleStringA &strSM3,BYTE * SM3Byte,bool isSub)
- {
- if(SM3Byte == NULL){
- return Error_Exception;
- }
- int SM3_len=64;
- if(isSub){
- SM3_len=32;
- }
- int i;
- char* file_SM3 = (char*)malloc((SM3_len + 1) * sizeof(char));
- if(file_SM3 == NULL)
- {
- fprintf(stderr, "SM3 malloc failed.\n");
- return Error_Exception;
- }
- memset(file_SM3, 0, (SM3_len + 1));
- if(SM3_len == 32)
- {
- for(i=0; i<16; i++)
- { //SM3截取中间16位字节,8-24位字节数,小写
- sprintf(&file_SM3[i*2], "%02x", SM3Byte[i+8]);
- }
- }
- else if(SM3_len == 64)
- {
- for(i=0; i<32; i++)
- {
- sprintf(&file_SM3[i*2], "%02x", SM3Byte[i]);
- }
- }
- strSM3=file_SM3;
- free(file_SM3);
- return Error_Succeed;
- }
- bool UploadFSM::getFileContent(FILE* pFile,unsigned char* content,int beginPos, int contentLen)
- {
- if(pFile==NULL||content==NULL){
- return false;
- }
- #ifdef RVC_OS_WIN
- clearerr(pFile);//尝试先复位错误指针
- #endif
- if(fseek(pFile,beginPos,SEEK_SET)!=0){
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getFileContent")("getFileContent fail,fseek beginPos =%d is error =%d",beginPos,(int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getFileContent")("getFileContent fail,fseek beginPos =%d is error =%d",beginPos, errno);
- #endif
- return false;
- }
- unsigned char* pRead = content;//移动的指针
- int pRemaind = contentLen; //剩余字节数
- int numBytes = 0;
- while(!feof(pFile)&&!ferror(pFile)){
- if(pRemaind<=0){
- break;
- }
- numBytes=(int)fread(pRead,1,pRemaind,pFile);
- //Dbg("读取字节numBytes=%d",numBytes);
- if(numBytes>0){
- pRemaind -=numBytes;
- pRead +=numBytes;
- }
- }
- if(pRemaind==0){
- return true;
- }else{
- //Dbg("getFileContent fail,pRemaind =%d",pRemaind);
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getFileContent")("getFileContent fail,pRemaind =%d, error=%d",pRemaind,(int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getFileContent")("getFileContent fail,pRemaind =%d, error=%d",pRemaind, errno);
- #endif
- return false;
- }
- }
- bool UploadFSM::test_zero_ref(const char *path)
- {
- #ifdef RVC_OS_WIN
- HANDLE hFile = CreateFileA(path,
- GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // try open
- if (hFile != INVALID_HANDLE_VALUE) {
- CloseHandle(hFile);
- return TRUE;
- } else {
- //添加获取句柄失败情况
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_SCANFILE_LOCK_ERROR, CSimpleStringA::Format("test_zero_ref is fail:%s",path).GetData());
- DWORD dwRet = GetLastError();
- return FALSE;
- }
- #else
- //后期改为linux真正的文件锁,现在来看,暂时用不着
- FILE* fp = fopen(path, "rb");
- if (fp != NULL) {
- fclose(fp);
- return true;
- }
- else
- {
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_SCANFILE_LOCK_ERROR, CSimpleStringA::Format("check_zero_ref is fail:%s", path).GetData());
- return false;
- }
- #endif // RVC_OS_WIN
- }
- bool UploadFSM::GetFileLength(const char* filePath,long &fileLen)
- {
- FILE* file = fopen(filePath, "rb");
- if (file!=NULL)
- {
- #ifdef RVC_OS_WIN
- fileLen = filelength(fileno(file));
- fclose(file);
- return true;
- #else
- //取得当前文件流的读取位置
- int cur_pos = ftell(file);
- //将文件流的读取位置设为文件末尾
- if (fseek(file, SEEK_SET, SEEK_END)==0) {
- //获取文件末尾的读取位置,即文件大小
- fileLen = ftell(file);
- //将文件流的读取位置还原为原先的值
- fseek(file, cur_pos, SEEK_SET);
- fclose(file);
- return true;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetFileLength")("fseek file=%s is fail, err=%d", filePath,errno);
- fclose(file);
- return false;
- }
- #endif
-
- } else{
- fileLen = 0;
- return false;
- }
- }
- void UploadFSM::reportBatchMsg()
- {
- CSimpleStringA strReport;
- if(m_uploadReport.fail==0){
- strReport =CSimpleStringA::Format("batch=succ isbreak=%d sum=%d succ=%d fail=%d detail fail: uploadFail=%d updateState=%d operateFileFail=%d (decodeFail=%d queryTempFail=%d)",
- m_uploadReport.isBreak, m_uploadReport.sum, m_uploadReport.succ, m_uploadReport.fail, m_uploadReport.uploadFail, m_uploadReport.updateState,
- m_uploadReport.operateFileFail, m_uploadReport.decodeFail, m_uploadReport.queryTempFail);
- LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
- }else{
- strReport =CSimpleStringA::Format("batch=fail isbreak=%d sum=%d succ=%d fail=%d detail fail: uploadFail=%d updateState=%d operateFileFail=%d (decodeFail=%d queryTempFail=%d)",
- m_uploadReport.isBreak, m_uploadReport.sum, m_uploadReport.succ, m_uploadReport.fail, m_uploadReport.uploadFail, m_uploadReport.updateState,
- m_uploadReport.operateFileFail, m_uploadReport.decodeFail, m_uploadReport.queryTempFail);
- LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
- }
- //LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
- }
- bool UploadFSM::findOverLenWarn(const char* fileName) {
- if (m_overLenFileList != NULL) {
- bool isfind = false;
- list<string>::iterator iter;
- for (iter = m_overLenFileList->begin(); iter != m_overLenFileList->end(); ++iter) {
- string fileStr = *iter;
- if (strcmp(fileName, fileStr.c_str()) == 0) {
- isfind = true;
- break;
- }
- }
- if (!isfind) {
- //未找到,加入队列
- m_overLenFileList->push_back(fileName);
- }
- return isfind;
- }
- return false;
- }
|