UploadFSM.cpp 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908
  1. #include "stdafx.h"
  2. #include "UploadFSM.h"
  3. #include <regex>
  4. #include <fileutil.h>
  5. #include <array.h>
  6. #ifdef RVC_OS_WIN
  7. #include <cstdlib>
  8. #include <ctime>
  9. #include "EventCode.h"
  10. #else
  11. #include <thread>
  12. #include "upload.h"
  13. #include "path.h"
  14. #include <sys/stat.h>
  15. #include <sys/types.h>
  16. #include <fcntl.h>
  17. #include <time.h>
  18. #include <stdio.h>
  19. #include <cstdio>
  20. #include <iostream>
  21. #include <errno.h>
  22. #include "EventCode.h"
  23. #endif
  24. #define UPLOAD_CONTENT_EACH_LEN 512*1024
  25. #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/
  26. #define QUERY_PLAN_URL "https://accessproxy-service.paasst.cmbchina.cn/uploadservice/api/plan/query"
  27. #define QUERY_TEMP_FILE_URL "https://accessproxy-service.paasst.cmbchina.cn/uploadservice/api/upload/query/status"
  28. #define UPDATE_STATE_URL "https://accessproxy-service.paasst.cmbchina.cn/uploadservice/api/upload/update/status"
  29. #define ADD_UPLOAD_FAIL_URL "https://accessproxy-service.paasst.cmbchina.cn/uploadservice/api/upload/fail"
  30. #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
  31. #define QUERY_PLAN_URL "https://uploadservice.paasuat.cmbchina.cn/api/plan/query"
  32. #define QUERY_TEMP_FILE_URL "https://uploadservice.paasuat.cmbchina.cn/api/upload/query/status"
  33. #define UPDATE_STATE_URL "https://uploadservice.paasuat.cmbchina.cn/api/upload/update/status"
  34. #define ADD_UPLOAD_FAIL_URL "https://uploadservice.paasuat.cmbchina.cn/api/upload/fail"
  35. #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
  36. #define QUERY_PLAN_URL "https://uploadservice.paas.cmbchina.cn/api/plan/query"
  37. #define QUERY_TEMP_FILE_URL "https://uploadservice.paas.cmbchina.cn/api/upload/query/status"
  38. #define UPDATE_STATE_URL "https://uploadservice.paas.cmbchina.cn/api/upload/update/status"
  39. #define ADD_UPLOAD_FAIL_URL "https://uploadservice.paas.cmbchina.cn/api/upload/fail"
  40. #else/*DevOps流水线编译,Dev环境&本地编译等非DevOps环境*/
  41. #define QUERY_PLAN_URL "https://accessproxy-service.paasst.cmbchina.cn/uploadservice/api/plan/query"
  42. #define QUERY_TEMP_FILE_URL "https://accessproxy-service.paasst.cmbchina.cn/uploadservice/api/upload/query/status"
  43. #define UPDATE_STATE_URL "https://accessproxy-service.paasst.cmbchina.cn/uploadservice/api/upload/update/status"
  44. #define ADD_UPLOAD_FAIL_URL "https://accessproxy-service.paasst.cmbchina.cn/uploadservice/api/upload/fail"
  45. #endif
  46. UploadFSM::UploadFSM() : m_currUploadFile(NULL)
  47. {
  48. m_uploadList = new list<UploadFileInfo*>();
  49. m_uploadPlanList = new list<UploadPlan *>();
  50. m_overLenFileList = new list<string>();
  51. m_eachUploadLen=UPLOAD_CONTENT_EACH_LEN;
  52. m_uploadMaxNum = 200;
  53. m_isOffLine=true;//初始离线状态为true
  54. m_printPlan = true;//初始化为打印
  55. }
  56. UploadFSM::~UploadFSM()
  57. {
  58. }
  59. namespace Task
  60. {
  61. struct SendFileTask : public ITaskSp
  62. {
  63. UploadFSM* m_fsm;
  64. explicit SendFileTask(UploadFSM* e) : m_fsm(e) {}
  65. void Process(){
  66. //判断是分行url请求还是总行url请求
  67. //判断是临时文件还是永久文件
  68. //循环上传
  69. //登记上传流水或者失败流水
  70. //根据最终上传结果返回成功还是失败
  71. CSystemStaticInfo info;
  72. auto rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  73. if (rc != Error_Succeed)
  74. {
  75. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("get CSystemStaticInfo fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  76. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_FAIL));//失败发送
  77. return;
  78. }
  79. bool isLanTerminal=true;//行内行外标志
  80. if(strcmp(m_fsm->m_currUploadFile->upload_address_env.c_str(),"BIZ")==0){
  81. isLanTerminal=true;
  82. }else{
  83. isLanTerminal=false;
  84. }
  85. IHttpFunc* client;
  86. client = create_http(m_fsm->HttpsLogCallBack);
  87. bool hasSend=false;
  88. if(m_fsm->m_currUploadFile->plan_type=="T"){
  89. //查询失败统一需要上传
  90. if(queryTempFile(client,info)){
  91. hasSend=true;
  92. }
  93. }
  94. //是否需要上传文件
  95. bool sendOk = false;
  96. if(!hasSend){
  97. string errmsg ="";
  98. if(isLanTerminal){
  99. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("上传文件到分行:%s",m_fsm->m_currUploadFile->filePath.c_str());
  100. }else{
  101. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("上传文件到总行:%s",m_fsm->m_currUploadFile->filePath.c_str());
  102. }
  103. string MD5str = ""; //返回的MD5值
  104. string branchFilePath = ""; //返回的分行保存路径值
  105. //修改为重试上传机制,防止上传当中网络抖动,避免等待下次上传
  106. bool isUploadSucc=false;
  107. for (int i =0 ; i<2;i++ )
  108. {
  109. errmsg="";//每次上传前清空错误信息,只记录最后一次的
  110. if(uploadFile(client,info,MD5str,branchFilePath,errmsg)){
  111. isUploadSucc = true;
  112. break;
  113. }
  114. Sleep(3000);//等待3秒下次传送
  115. }
  116. if(isUploadSucc){
  117. if(updateState(client,info,isLanTerminal,MD5str,branchFilePath,errmsg)){
  118. if(operateFile(errmsg)){
  119. sendOk = true;//成功
  120. }else{
  121. m_fsm->m_uploadReport.operateFileFail++;//添加操作失败计数
  122. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("operateFile fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  123. addUploadFail(client,info,isLanTerminal,"2",errmsg);//操作失败
  124. }
  125. }else{
  126. m_fsm->m_uploadReport.updateState++;//添加登记失败计数
  127. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("updateState fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  128. addUploadFail(client,info,isLanTerminal,"1",errmsg);//登记失败
  129. }
  130. }else{
  131. m_fsm->m_uploadReport.uploadFail++;//添加上传失败计数
  132. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendFileTask")("uploadFile fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  133. addUploadFail(client,info,isLanTerminal,"1",errmsg);//上传失败
  134. }
  135. }else{
  136. sendOk=true;
  137. }
  138. client->Destory();
  139. if(sendOk){
  140. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_SUCC));//成功发送
  141. }else{
  142. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_FAIL));//失败发送
  143. }
  144. }
  145. //上传文件:断点续传,多次调用
  146. bool uploadFile(IHttpFunc* client,CSystemStaticInfo info,string &MD5str,string &branchFilePath, string &errmsg){
  147. string reqUrl;
  148. unsigned seed;
  149. seed = time(0);
  150. srand(seed);
  151. if(m_fsm->m_branchIpList.size()>0){
  152. int branchSeq = (rand() % m_fsm->m_branchIpList.size()) + 1;
  153. map<int,string>::iterator it = m_fsm->m_branchIpList.find(branchSeq);
  154. if(it != m_fsm->m_branchIpList.end())
  155. {
  156. reqUrl = it->second;
  157. }else{
  158. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile is fail ,branchIp[%d] is null",branchSeq);
  159. errmsg = CSimpleStringA::Format("uploadFile is fail ,branchIp[%d] is null",branchSeq).GetData();
  160. return false;
  161. }
  162. }else{
  163. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile is fail ,branchIp is null");
  164. errmsg = "uploadFile is fail ,branchIp is null";
  165. return false;
  166. }
  167. //获取服务器文件长度
  168. unsigned char* contentFirst = new unsigned char[1];
  169. memset(contentFirst,0,1);
  170. UploadDataRet respFirst ={0};
  171. bool is_finish =false; //是否续传
  172. if(!uploadFileImpl(client,info,reqUrl,contentFirst,0,"",respFirst)){
  173. delete[] contentFirst;
  174. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl first is fail",reqUrl.c_str()).GetData();
  175. return false;//返回失败
  176. }else{
  177. delete[] contentFirst;
  178. }
  179. long uploadedLen = respFirst.uploaded_length;//服务器返回已上传的长度
  180. if(uploadedLen>m_fsm->m_currUploadFile->fileLen){
  181. //服务器返回长度大于终端文件长度
  182. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile is fail, server filelen [%d] is over terminal filelen [%d]",uploadedLen,m_fsm->m_currUploadFile->fileLen);
  183. errmsg=CSimpleStringA::Format("uploadFile is fail, server filelen [%d] is over terminal filelen [%d]",uploadedLen,m_fsm->m_currUploadFile->fileLen).GetData();
  184. return false;
  185. }
  186. if (uploadedLen < 0) {
  187. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile uploadedLen beginPos < 0");
  188. errmsg = CSimpleStringA::Format("uploadFile is fail, server filelen [%d] is <0", uploadedLen).GetData();
  189. return false;
  190. }
  191. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("文件[%s] 开始传送位置 uploadedLen = %d, file len=%d",m_fsm->m_currUploadFile->filePath.c_str(), uploadedLen, m_fsm->m_currUploadFile->fileLen);
  192. //循环传送数据块
  193. FILE* pFile =fopen(m_fsm->m_currUploadFile->filePath.c_str(),"rb");
  194. if(pFile==NULL){
  195. //读取文件失败;
  196. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile is fail, file open fail");
  197. errmsg="uploadFile is fail, file open fail";
  198. return false;
  199. }
  200. //获取首次文件hash
  201. CSimpleStringA firstSM3Str = "";
  202. if (Error_Succeed == m_fsm->SM3FileToStr(m_fsm->m_currUploadFile->filePath.c_str(), firstSM3Str, false)) {
  203. m_fsm->m_currUploadFile->firstMD5Str = firstSM3Str.GetData();
  204. m_fsm->m_currUploadFile->lastMD5Str = "";
  205. }
  206. else {
  207. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile is fail, get file first SM3 hash fail");
  208. errmsg = "uploadFile is fail , get file first SM3 hash fail";
  209. return false;
  210. }
  211. bool uploadSucc= false;
  212. while(true){
  213. //续传
  214. if((m_fsm->m_currUploadFile->fileLen-uploadedLen)>m_fsm->m_eachUploadLen){
  215. int uploadLen = m_fsm->m_eachUploadLen;//传送数据长度
  216. unsigned char* content = new unsigned char[uploadLen];
  217. memset(content,0,uploadLen);
  218. //从文件拷贝字节
  219. if(m_fsm->getFileContent(pFile,content,uploadedLen,uploadLen)){
  220. UploadDataRet resp ={0};
  221. if(uploadFileImpl(client,info,reqUrl,content,uploadLen,"",resp)){
  222. delete[] content;
  223. uploadedLen +=uploadLen;//改变已上传长度
  224. }else{
  225. delete[] content;
  226. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl continue is fail",reqUrl.c_str()).GetData();
  227. break;//上传失败
  228. }
  229. }else{
  230. delete[] content;
  231. errmsg="uploadFile is fail , getFileContent fail";
  232. break;//获取文件内存失败
  233. }
  234. }else{
  235. //获取最后一次传送时文件长度
  236. CSimpleStringA filepath = m_fsm->m_currUploadFile->filePath.c_str();
  237. long fileLastLen = 0;
  238. if(!m_fsm->GetFileLength(filepath.GetData(),fileLastLen)){
  239. errmsg="uploadFile is fail , end get file len fail";
  240. break;//计算sm3出错
  241. }
  242. string fileLastLenStr= CSimpleStringA::Format("%d",fileLastLen).GetData();//计算出解密后总长度
  243. //获取最后文件hash
  244. CSimpleStringA lastSM3Str = "";
  245. if(Error_Succeed == m_fsm->SM3FileToStr(filepath.GetData(), lastSM3Str, false)) {
  246. m_fsm->m_currUploadFile->lastMD5Str = lastSM3Str.GetData();
  247. }
  248. else {
  249. errmsg = "uploadFile is fail , get file last SM3 hash fail";
  250. break;//计算sm3出错
  251. }
  252. //最后一块
  253. int uploadLen = m_fsm->m_currUploadFile->fileLen-uploadedLen;
  254. unsigned char* contentEnd;
  255. if(uploadLen==0){
  256. //对零的长度特殊处理
  257. contentEnd = new unsigned char[1];
  258. memset(contentEnd,0,1);
  259. }else{
  260. contentEnd = new unsigned char[uploadLen];
  261. memset(contentEnd,0,uploadLen);
  262. }
  263. if(m_fsm->getFileContent(pFile,contentEnd,uploadedLen,uploadLen)){
  264. UploadDataRet respEnd ={0};
  265. if(uploadFileImpl(client,info,reqUrl,contentEnd,uploadLen,fileLastLenStr,respEnd)){
  266. delete[] contentEnd;
  267. if(respEnd.upload_finish){
  268. uploadSucc =true;//成功
  269. branchFilePath = respEnd.branchFilePath;//分行保存地址
  270. }else{
  271. uploadSucc =false;//失败
  272. }
  273. break;
  274. }else{
  275. delete[] contentEnd;
  276. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl end is fail",reqUrl.c_str()).GetData();
  277. break;//上传失败
  278. }
  279. }else{
  280. delete[] contentEnd;
  281. errmsg="uploadFile is fail , end getFileContent fail";
  282. break;//获取文件内存失败
  283. }
  284. }
  285. }
  286. if(uploadSucc){
  287. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile succ");
  288. }else{
  289. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile fail url=%s",reqUrl.c_str());
  290. }
  291. if(pFile){
  292. if(fclose(pFile)!=0){
  293. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile fail, close file fail ,url=%s",reqUrl.c_str());
  294. errmsg="uploadFile fail, close file fail";
  295. return false;
  296. }
  297. }
  298. return uploadSucc;
  299. }
  300. //上传文件:具体实现
  301. bool uploadFileImpl(IHttpFunc* client,CSystemStaticInfo info,string httpUrl,unsigned char* fileContent,long fileContentSize,string lastFileLength,UploadDataRet& uploadData){
  302. UploadFileReq qTempReq;
  303. UploadFileRet qTempRet;
  304. qTempRet.m_userCode ="";
  305. qTempRet.m_errMsg="";
  306. Json::Value rootReq;
  307. Json::FastWriter writer;
  308. rootReq["terminal_no"] = info.strTerminalID.GetData();
  309. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  310. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  311. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  312. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  313. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  314. //rootReq["origin_file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();
  315. rootReq["first_file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();//加密后需要修改,服务端根据此长度做判断
  316. rootReq["last_file_length"] = lastFileLength.c_str();//加密后需要修改,最后一次长度跟服务端保存长度做对比
  317. rootReq["upload_length"] = CSimpleStringA::Format("%d",fileContentSize).GetData();
  318. rootReq["first_sm3"] = m_fsm->m_currUploadFile->firstMD5Str.c_str();
  319. rootReq["last_sm3"] = m_fsm->m_currUploadFile->lastMD5Str.c_str();
  320. rootReq["file_head_custom"] = "";//自定义解密的头json格式,可为空
  321. #ifdef RVC_OS_WIN
  322. rootReq["system_type"] = "W";//系统标记,代表路径分隔符
  323. #else
  324. rootReq["system_type"] = "L";//系统标记,代表路径分隔符
  325. #endif
  326. string jsonReq = writer.write(rootReq);
  327. qTempReq.url = httpUrl;
  328. qTempReq.paramContent = jsonReq;
  329. qTempReq.fileName = m_fsm->m_currUploadFile->fileName;
  330. qTempReq.fileContent = fileContent;
  331. qTempReq.fileContentSize= fileContentSize;
  332. qTempReq.m_timeOut = 5*60;//设置超时时间
  333. //qTempReq.m_printDbg=true;
  334. //调用上传接口
  335. //最后一次上传时,文件hash和长度告警
  336. if (m_fsm->m_currUploadFile->lastMD5Str.length() != 0) {
  337. //LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_FILE_INFO, CSimpleStringA::Format("upload %s file size is %s byte,sm3 digest is %s.", m_fsm->m_currUploadFile->fileName.c_str(), lastFileLength.c_str(), m_fsm->m_currUploadFile->lastMD5Str.c_str()).GetData());
  338. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("upload %s file size is %s byte,sm3 digest is %s.", m_fsm->m_currUploadFile->fileName.c_str(), lastFileLength.c_str(), m_fsm->m_currUploadFile->lastMD5Str.c_str());
  339. }
  340. PROCESS_LINK_CONTEXT("LR0402104UploadFile")
  341. if (!client->UploadFileBlock(qTempReq, qTempRet, &nextLink)) {
  342. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile http req fail ,url =%s ,fileName = %s",httpUrl.c_str(), m_fsm->m_currUploadFile->fileName.c_str());
  343. return false;
  344. }
  345. if(qTempRet.httpCode!=200){
  346. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile http req fail ,url =%s ,retHttpCode=%d, fileName = %s",httpUrl.c_str(), qTempRet.httpCode, m_fsm->m_currUploadFile->fileName.c_str());
  347. return false;
  348. }
  349. //解析回应报文
  350. Json::Reader reader;
  351. Json::Value rootRet;
  352. if (!reader.parse(qTempRet.strBody, rootRet, false))
  353. {
  354. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile http parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->fileName.c_str());
  355. return false;//解析失败
  356. }
  357. uploadData.strBody = qTempRet.strBody;
  358. bool isSucc = rootRet["success"].asBool();
  359. if(isSucc){
  360. if(rootRet.isMember("data")){
  361. uploadData.uploaded_length= rootRet["data"]["uploaded_length"].asInt();
  362. uploadData.upload_finish = rootRet["data"]["upload_finish"].asBool();
  363. uploadData.branchFilePath = rootRet["data"]["branch_file_path"].asCString();
  364. return true;//返回值
  365. }else{
  366. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile http [success][data] is invaild ,url =%s, fileName = %s",httpUrl.c_str(),m_fsm->m_currUploadFile->fileName.c_str());
  367. return false;//无data字段
  368. }
  369. }else{
  370. //失败
  371. if (m_fsm->m_currUploadFile->lastMD5Str.length() == 0) {
  372. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("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());
  373. }
  374. else {
  375. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("uploadFile http [success] is false, url[%s],userCode[%s],errmsg[%s],fileName = %s,first_sm3 =[%s],last_sm3=[%s]", httpUrl.c_str(), qTempRet.m_userCode.c_str(), qTempRet.m_errMsg.c_str(), m_fsm->m_currUploadFile->fileName.c_str(), m_fsm->m_currUploadFile->firstMD5Str.c_str(), m_fsm->m_currUploadFile->lastMD5Str.c_str());
  376. }
  377. return false;
  378. }
  379. }
  380. //查询临时文件 post
  381. bool queryTempFile(IHttpFunc* client,CSystemStaticInfo info){
  382. UploadQueryTempFileReq qTempReq;
  383. UploadQueryTempFileRet qTempRet;
  384. qTempRet.m_userCode ="";
  385. qTempRet.m_errMsg="";
  386. Json::Value rootReq;
  387. Json::FastWriter writer;
  388. rootReq["terminal_no"] = info.strTerminalID.GetData();
  389. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  390. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  391. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  392. string jsonReq = writer.write(rootReq);
  393. qTempReq.m_reqStr = jsonReq;//请求参数
  394. //qTempReq.m_printDbg = true;
  395. qTempReq.m_url=m_fsm->m_centerUrl.queryTempFileUrl;//访问地址
  396. PROCESS_LINK_CONTEXT("LR0402104QueryTempFile")
  397. if(!client->Post(qTempReq, qTempRet, &nextLink)){
  398. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryTempFile http req fail ,fileName = %s, err=%s",m_fsm->m_currUploadFile->filePath.c_str(),qTempRet.m_errMsg.c_str());
  399. return false;
  400. }
  401. //解析报文
  402. //解析回应报文
  403. Json::Reader reader;
  404. Json::Value rootRet;
  405. if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  406. {
  407. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryTempFile parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
  408. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  409. return false;//解析失败
  410. }
  411. bool isSucc = rootRet["success"].asBool();
  412. if(isSucc){
  413. if(rootRet.isMember("data")){
  414. if(rootRet["data"]["upload_flag"].asBool()){
  415. return true;//查询有
  416. }else{
  417. return false;//查询没有
  418. }
  419. }else{
  420. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  421. return false;//无data字段
  422. }
  423. }else{
  424. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryTempFile [success] is false, fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
  425. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  426. return false;
  427. }
  428. }
  429. //登记文件流水状态 post
  430. bool updateState(IHttpFunc* client,CSystemStaticInfo info,bool isLanTerminal, string MD5str,string branchFilePath, string &errmsg){
  431. if(!isLanTerminal){
  432. return true;//行外默认是总行那边登记交易流水,终端不再发送交易流水登记,直接返回成功
  433. }
  434. UploadUpdateStateReq updateStateReq;
  435. UploadUpdateStateRet updateStateRet;
  436. updateStateRet.m_userCode="";
  437. updateStateRet.m_errMsg="";
  438. Json::Value rootReq;
  439. Json::FastWriter writer;
  440. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  441. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  442. rootReq["terminal_no"] = info.strTerminalID.GetData();
  443. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  444. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  445. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  446. rootReq["branch_file_path"] = branchFilePath.c_str();
  447. rootReq["file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();
  448. if(isLanTerminal){
  449. rootReq["status"] = "1";//分行
  450. }else{
  451. rootReq["status"] = "2";//总行
  452. }
  453. rootReq["upload_time"] = CSmallDateTime::GetNow().ToTimeString().GetData();
  454. rootReq["remark"] = "";
  455. rootReq["sm3"] = MD5str.c_str();
  456. string jsonReq = writer.write(rootReq);
  457. updateStateReq.m_reqStr = jsonReq;//请求参数
  458. updateStateReq.m_url=m_fsm->m_centerUrl.updateStateUrl;//访问地址
  459. PROCESS_LINK_CONTEXT("LR0402104UpdateState")
  460. if(!client->Post(updateStateReq, updateStateRet, &nextLink)){
  461. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("updateState is fail, userCode = %s, errmsg = %s",updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
  462. errmsg = CSimpleStringA::Format("updateState is fail, userCode = %s, errmsg = %s",updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
  463. return false;
  464. }
  465. //解析报文
  466. //解析回应报文
  467. Json::Reader reader;
  468. Json::Value rootRet;
  469. if (!reader.parse(updateStateRet.m_retStr, rootRet, false))
  470. {
  471. errmsg="return pack parse is fail";
  472. return false;//解析失败
  473. }
  474. bool isSucc = rootRet["success"].asBool();
  475. if(isSucc){
  476. if(rootRet.isMember("data")){
  477. if(rootRet["data"]["update_flag"].asBool()){
  478. return true;//登记成功
  479. }else{
  480. errmsg="return pack [data][update_flag] is not bool";
  481. return false;//登记失败
  482. }
  483. }else{
  484. errmsg="return pack [data] is null";
  485. return false;//无data字段
  486. }
  487. }else{
  488. errmsg="return pack [success] is false";
  489. return false;
  490. }
  491. }
  492. //登记失败文件流水 post
  493. bool addUploadFail(IHttpFunc* client,CSystemStaticInfo info,bool isLanTerminal,string operation,string errmsg){
  494. UploadUploadFailReq updateFailReq;
  495. UploadUploadFailRet updateFailRet;
  496. updateFailRet.m_userCode="";
  497. updateFailRet.m_errMsg="";
  498. Json::Value rootReq;
  499. Json::FastWriter writer;
  500. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  501. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  502. rootReq["terminal_no"] = info.strTerminalID.GetData();
  503. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  504. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  505. if(isLanTerminal){
  506. rootReq["stage"] = "1";//分行
  507. }else{
  508. rootReq["stage"] = "2";//总行
  509. }
  510. rootReq["operation"] = operation;
  511. rootReq["upload_time"] = CSmallDateTime::GetNow().ToTimeString().GetData();//2021-03-11 10:20:02
  512. rootReq["reason"] = errmsg.c_str();
  513. rootReq["remark"] = "";
  514. string jsonReq = writer.write(rootReq);
  515. updateFailReq.m_reqStr = jsonReq;//请求参数
  516. updateFailReq.m_url = m_fsm->m_centerUrl.addUploadFailUrl;//访问地址
  517. PROCESS_LINK_CONTEXT("LR0402104UpdateFail")
  518. if(!client->Post(updateFailReq, updateFailRet, &nextLink)){
  519. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("addUploadFail is fail,userCode = %s",updateFailRet.m_userCode.c_str());
  520. return false;
  521. }
  522. //解析报文
  523. //解析回应报文
  524. Json::Reader reader;
  525. Json::Value rootRet;
  526. if (!reader.parse(updateFailRet.m_retStr, rootRet, false))
  527. {
  528. return false;//解析失败
  529. }
  530. bool isSucc = rootRet["success"].asBool();
  531. if(isSucc){
  532. if(rootRet.isMember("data")){
  533. if(rootRet["data"]["update_flag"].asBool()){
  534. return true;//登记成功
  535. }else{
  536. return false;//登记失败
  537. }
  538. }else{
  539. return false;//无data字段
  540. }
  541. }else{
  542. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("addUploadFail [success] is false");
  543. return false;
  544. }
  545. }
  546. //上传后文件处理
  547. bool operateFile(string &errmsg){
  548. if(m_fsm->m_currUploadFile->after_deal_type=="D"){
  549. #ifdef RVC_OS_WIN
  550. if(remove(m_fsm->m_currUploadFile->filePath.c_str())==0){
  551. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file is ok, file =%s",m_fsm->m_currUploadFile->filePath.c_str());
  552. return true;
  553. }else{
  554. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(),(int)GetLastError());
  555. errmsg = CSimpleStringA::Format("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(),(int)GetLastError());
  556. return false;
  557. }
  558. #else
  559. if (changeFileAtt(m_fsm->m_currUploadFile->filePath.c_str()) == 0) {
  560. if (remove(m_fsm->m_currUploadFile->filePath.c_str()) == 0) {
  561. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file is ok, file =%s",m_fsm->m_currUploadFile->filePath.c_str());
  562. return true;
  563. }
  564. else {
  565. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file is error,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  566. errmsg = CSimpleStringA::Format("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  567. return false;
  568. }
  569. }
  570. else {
  571. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file is error,changefileAtt fail,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  572. errmsg = CSimpleStringA::Format("delete file is error,changefileAtt fail,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  573. return false;
  574. }
  575. #endif
  576. }else if(m_fsm->m_currUploadFile->after_deal_type=="M"){
  577. string destPath="";
  578. string destDir="";
  579. //根据路径类型组成最后移动路径
  580. if(m_fsm->m_currUploadFile->path_type=="R"){
  581. #ifdef RVC_OS_WIN
  582. destPath = m_fsm->m_rootPath+"\\"+m_fsm->m_currUploadFile->after_deal_text+"\\"+m_fsm->m_currUploadFile->fileName;
  583. destDir = m_fsm->m_rootPath+"\\"+m_fsm->m_currUploadFile->after_deal_text;
  584. #else
  585. destPath = m_fsm->m_rootPath + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->after_deal_text + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->fileName;
  586. destDir = m_fsm->m_rootPath + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->after_deal_text;
  587. #endif
  588. }else{
  589. #ifdef RVC_OS_WIN
  590. destPath = m_fsm->m_currUploadFile->after_deal_text+"\\"+m_fsm->m_currUploadFile->fileName;
  591. #else
  592. destPath = m_fsm->m_currUploadFile->after_deal_text + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->fileName;
  593. #endif
  594. destDir = m_fsm->m_currUploadFile->after_deal_text;
  595. }
  596. string srcPath = m_fsm->m_currUploadFile->filePath;
  597. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("move file %s to %s",srcPath.c_str(),destPath.c_str());
  598. //判断是否存在目标文件,如存在,则先删除
  599. #ifdef RVC_OS_WIN
  600. if(ExistsFileA(destPath.c_str())){
  601. if(remove(destPath.c_str())==0){
  602. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete dest file is ok [%s]",destPath.c_str());
  603. }else{
  604. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete dest file is error, errno=%d, [%s]",(int)GetLastError(),destPath.c_str());
  605. errmsg = CSimpleStringA::Format("delete dest file is error, errno=%d, [%s]",(int)GetLastError(),destPath.c_str());
  606. return false;
  607. }
  608. }
  609. //判断移动目标文件夹是否存在,不存在,则创建
  610. if(!ExistsDirA(destDir.c_str())){
  611. if(!CreateDirRecursiveA(destDir.c_str())){
  612. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create dest dir [%s] is error, errno=%d",destDir.c_str(),GetLastError());
  613. errmsg = CSimpleStringA::Format("create dest dir [%s] is error, errno=%d",destDir.c_str(),GetLastError());
  614. return false;
  615. }
  616. }
  617. //移动文件
  618. int i;
  619. int tries = 10;
  620. bool isSucc = false;
  621. for (i = 0; i < tries; ++i) {
  622. if(rename(srcPath.c_str(),destPath.c_str())==0){
  623. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("move file ok! tries:%d, [%s] to [%s] ", i, srcPath.c_str(),destPath.c_str());
  624. isSucc = true;
  625. break;
  626. } else {
  627. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("move file failed! errno:%d, [%s] to [%s] ", (int)GetLastError(), srcPath.c_str(),destPath.c_str());
  628. errmsg = CSimpleStringA::Format("move file failed! errno:%d, [%s] to [%s] ", (int)GetLastError(), srcPath.c_str(),destPath.c_str());
  629. Sleep(1000);
  630. }
  631. }
  632. return isSucc;
  633. #else
  634. if (ExistsFileA(destPath.c_str())) {
  635. if (changeFileAtt(destPath.c_str()) == 0) {
  636. if (remove(destPath.c_str()) == 0) {
  637. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete dest file is ok [%s]",destPath.c_str());
  638. }
  639. else {
  640. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete dest file is error, errno=%d, [%s]", errno, destPath.c_str());
  641. errmsg = CSimpleStringA::Format("delete src file is error, errno=%d, [%s]", errno, destPath.c_str());
  642. return false;
  643. }
  644. }
  645. else {
  646. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete dest file is error,changefileAtt fail ,errno=%d , file=%s ", errno, destPath.c_str());
  647. errmsg = CSimpleStringA::Format("delete src file is error, changefileAtt fail, errno=%d, file=%s", errno, destPath.c_str());
  648. return false;
  649. }
  650. }
  651. //判断移动目标文件夹是否存在,不存在,则创建
  652. if (!ExistsDirA(destDir.c_str())) {
  653. if (!CreateDirRecursiveA(destDir.c_str())) {
  654. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create dest dir [%s] is error, errno=%d", destDir.c_str(), errno);
  655. errmsg = CSimpleStringA::Format("create dest dir [%s] is error, errno=%d", destDir.c_str(), errno);
  656. return false;
  657. }
  658. }
  659. //移动文件
  660. if (changeFileAtt(srcPath.c_str()) == 0)
  661. {
  662. int i;
  663. int tries = 10;
  664. bool isSucc = false;
  665. for (i = 0; i < tries; ++i) {
  666. //rename函数对于跨分支的目录存在拷贝不成功的情况,故采用先拷贝后删除的操作修复此bug
  667. if (fileutil_copy_file(destPath.c_str(), srcPath.c_str()) == 0) {
  668. if (remove(srcPath.c_str()) == 0) {
  669. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("move file ok! tries:%d, [%s] to [%s] ", i, srcPath.c_str(),destPath.c_str());
  670. isSucc = true;
  671. break;
  672. }
  673. else {
  674. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("move file failed! errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  675. errmsg = CSimpleStringA::Format("move file failed! errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  676. Sleep(1000);
  677. }
  678. }
  679. else {
  680. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("move file failed! copy src file fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  681. errmsg = CSimpleStringA::Format("move file failed! copy src file fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  682. Sleep(1000);
  683. }
  684. }
  685. return isSucc;
  686. }
  687. else {
  688. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("move file failed! changefileAtt fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  689. errmsg = CSimpleStringA::Format("move file failed! changefileAtt fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  690. return false;
  691. }
  692. #endif
  693. }else if(m_fsm->m_currUploadFile->after_deal_type=="N"){
  694. return true;
  695. }else{
  696. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("file [%s] invalid after_deal_type=%s",m_fsm->m_currUploadFile->fileName.c_str(),m_fsm->m_currUploadFile->after_deal_type.c_str());
  697. errmsg = CSimpleStringA::Format("invalid after_deal_type=%s",m_fsm->m_currUploadFile->after_deal_type.c_str());
  698. return false;
  699. }
  700. }
  701. };
  702. }
  703. void UploadFSM::OnStateTrans( int iSrcState, int iDstState )
  704. {
  705. DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
  706. }
  707. void UploadFSM::OnSysVarEvent( const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName )
  708. {
  709. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("rx sysvar %s from %s, %s to %s", pszKey, pszEntityName, pszOldValue, pszValue);
  710. if (pszValue[0] == 'O') {
  711. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("rx sysvar %s from %s, %s to %s", pszKey, pszEntityName, pszOldValue, pszValue);
  712. m_isOffLine = true;
  713. PostEventFIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  714. } else {
  715. if (m_isOffLine) {
  716. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("rx sysvar %s from %s, %s to %s", pszKey, pszEntityName, pszOldValue, pszValue);
  717. }
  718. m_isOffLine = false;
  719. PostEventFIFO(new FSMEvent(USER_EVT_JMP_DISABLE));
  720. }
  721. }
  722. ErrorCodeEnum UploadFSM::OnInit()
  723. {
  724. ErrorCodeEnum Error;
  725. CSimpleStringA checkStr="";
  726. CSmartPointer<IConfigInfo> spConfig;
  727. Error = m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  728. if(Error==Error_Succeed){
  729. //获取模式控制参数
  730. m_centerModel = (int)centerModel;//强制总行模式
  731. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("model is centerModel, CenterModel = %d", m_centerModel);
  732. m_centerUrl.queryPlanUrl = QUERY_PLAN_URL;
  733. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init read queryPlanUrl=%s", m_centerUrl.queryPlanUrl.c_str());
  734. m_centerUrl.queryTempFileUrl = QUERY_TEMP_FILE_URL;
  735. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init read queryTempFileUrl=%s", m_centerUrl.queryTempFileUrl.c_str());
  736. m_centerUrl.updateStateUrl = UPDATE_STATE_URL;
  737. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init read updateStateUrl=%s", m_centerUrl.updateStateUrl.c_str());
  738. m_centerUrl.addUploadFailUrl = ADD_UPLOAD_FAIL_URL;
  739. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init read addUploadFailUrl=%s", m_centerUrl.addUploadFailUrl.c_str());
  740. //增加总行接口Url参数
  741. CSimpleStringA str="";
  742. //Error = spConfig->ReadConfigValue("upload", "QueryPlanUrl", str);
  743. //if (Error == Error_Succeed)
  744. //{
  745. // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("[CenterUrl] QueryPlanUrl =%s",str.GetData());
  746. // m_centerUrl.queryPlanUrl = str.GetData();
  747. //}
  748. //else
  749. //{
  750. // return Error;
  751. //}
  752. //Error = spConfig->ReadConfigValue("upload", "QueryTempFileUrl", str);
  753. //if (Error == Error_Succeed)
  754. //{
  755. // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("[CenterUrl] QueryTempFileUrl =%s",str.GetData());
  756. // m_centerUrl.queryTempFileUrl = str.GetData();
  757. //}
  758. //else
  759. //{
  760. // return Error;
  761. //}
  762. //Error = spConfig->ReadConfigValue("upload", "UpdateStateUrl", str);
  763. //if (Error == Error_Succeed)
  764. //{
  765. // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("[CenterUrl] UpdateStateUrl =%s",str.GetData());
  766. // m_centerUrl.updateStateUrl = str.GetData();
  767. //}
  768. //else
  769. //{
  770. // return Error;
  771. //}
  772. //Error = spConfig->ReadConfigValue("upload", "AddUploadFailUrl", str);
  773. //if (Error == Error_Succeed)
  774. //{
  775. // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("[CenterUrl] AddUploadFailUrl =%s",str.GetData());
  776. // m_centerUrl.addUploadFailUrl = str.GetData();
  777. //}
  778. //else
  779. //{
  780. // return Error;
  781. //}
  782. Error = spConfig->ReadConfigValue("upload", "EachUploadLen", str);
  783. if (Error == Error_Succeed)
  784. {
  785. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("[CenterUrl] EachUploadLen =%s",str.GetData());
  786. if(str.IsNullOrEmpty()){
  787. m_eachUploadLen = UPLOAD_CONTENT_EACH_LEN;
  788. }else{
  789. m_eachUploadLen = atoi(str.GetData())*1024;
  790. }
  791. }
  792. else
  793. {
  794. return Error;
  795. }
  796. int uploadMaxNum = 0;
  797. Error = spConfig->ReadConfigValueInt("upload", "UploadMaxNum", uploadMaxNum);
  798. if (Error == Error_Succeed)
  799. {
  800. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("[CenterUrl] UploadMaxNum =%d",uploadMaxNum);
  801. if(uploadMaxNum<=10){
  802. m_uploadMaxNum = 200;
  803. }else{
  804. m_uploadMaxNum = uploadMaxNum;
  805. }
  806. }
  807. else
  808. {
  809. return Error;
  810. }
  811. //获取系统文件根路径
  812. CSimpleStringA runPath ;
  813. Error =this->GetEntityBase()->GetFunction()->GetPath("rvc",runPath);//例如:C:\\Run /opt/Run
  814. if(Error_Succeed == Error){
  815. if(!runPath.IsNullOrEmpty()){
  816. string runPathStr = runPath.GetData();
  817. #ifdef RVC_OS_WIN
  818. int pos = runPathStr.find_last_of('\\');
  819. #else
  820. int pos = runPathStr.find_last_of(SPLIT_SLASH);//修改为路径分隔符
  821. #endif
  822. m_rootPath = runPathStr.substr(0,pos);
  823. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("get rvc path is %s",m_rootPath.c_str());
  824. }else{
  825. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("get rvc path is null");
  826. return Error_Unexpect;
  827. }
  828. }else{
  829. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("get rvc path is error");
  830. return Error_Unexpect;
  831. }
  832. }else{
  833. return Error;
  834. }
  835. Error = m_pEntity->GetFunction()->RegistSysVarEvent("CallState", this);
  836. if (Error == Error_Succeed) {
  837. AddStateHooker(this);
  838. }
  839. //......
  840. return Error;
  841. }
  842. ErrorCodeEnum UploadFSM::OnExit()
  843. {
  844. m_pEntity->GetFunction()->UnregistSysVarEvent("CallState");
  845. return Error_Succeed;
  846. }
  847. void UploadFSM::s0_on_entry()
  848. {
  849. CSimpleStringA strValue;
  850. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetSysVar("CallState", strValue);
  851. if (Error == Error_Succeed) {
  852. if (strValue[0] == 'O') { // only upload when CallState in offline state
  853. PostEventLIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  854. } else {
  855. PostEventLIFO(new FSMEvent(USER_EVT_JMP_DISABLE));
  856. }
  857. }
  858. }
  859. void UploadFSM::s0_on_exit()
  860. {
  861. }
  862. unsigned int UploadFSM::s0_on_event( FSMEvent* event )
  863. {
  864. return 0;
  865. }
  866. void UploadFSM::s1_on_entry()
  867. {
  868. ScheduleTimer(8, 30000);
  869. }
  870. void UploadFSM::s1_on_exit()
  871. {
  872. CancelTimer(8);
  873. }
  874. unsigned int UploadFSM::s1_on_event(FSMEvent* event)
  875. {
  876. if (event->iEvt == EVT_TIMER) {
  877. if(m_isOffLine){
  878. PostEventLIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  879. }else{
  880. ScheduleTimer(8, 30000);//继续等待
  881. }
  882. }
  883. return 0;
  884. }
  885. void UploadFSM::s2_on_entry()
  886. {
  887. m_uploadModel = true;//默认总行上传模式
  888. //清理上次扫描文件列表,扫描计划,分行ip列表
  889. if(m_uploadList!=NULL){
  890. list<UploadFileInfo*>::iterator iter ;
  891. for(iter=m_uploadList->begin();iter!=m_uploadList->end();++iter){
  892. delete *iter;
  893. }
  894. m_uploadList->clear();
  895. }
  896. if(m_uploadPlanList!=NULL){
  897. list<UploadPlan*>::iterator iter ;
  898. for(iter=m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  899. delete *iter;
  900. }
  901. m_uploadPlanList->clear();
  902. }
  903. m_branchIpList.clear();
  904. if(m_centerModel == (int)centerModel){
  905. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel");
  906. //防止url无效,新模式直接停止上传 等待下一次
  907. if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
  908. m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
  909. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel mode ,centerUrl is null , wait for next time");
  910. ScheduleTimer(1, 120000);
  911. return ;
  912. }
  913. //新模式,查询策略
  914. if(queryPlan()){
  915. m_uploadModel = true;
  916. }else{
  917. //查询策略失败,等待下一次
  918. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("queryPlan is fail , wait for next time");
  919. ScheduleTimer(1, 120000);
  920. return ;
  921. }
  922. }else{
  923. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_centerModel is invalid");
  924. ScheduleTimer(1, 120000);
  925. return;
  926. }
  927. if(m_uploadModel){
  928. //新模式扫描
  929. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_SCAN));
  930. }else{
  931. //旧模式扫描
  932. PostEventLIFO(new FSMEvent(USER_EVT_JMP_OLD_SCAN));
  933. }
  934. }
  935. void UploadFSM::s2_on_exit()
  936. {
  937. CancelTimer(1);
  938. }
  939. unsigned int UploadFSM::s2_on_event(FSMEvent* event)
  940. {
  941. if (event->iEvt == EVT_TIMER) {
  942. m_uploadModel = true;//默认是分行上传模式
  943. //清理上次扫描文件列表,扫描计划,分行ip列表
  944. if(m_uploadList!=NULL){
  945. list<UploadFileInfo*>::iterator iter ;
  946. for(iter=m_uploadList->begin();iter!=m_uploadList->end();++iter){
  947. delete *iter;
  948. }
  949. m_uploadList->clear();
  950. }
  951. if(m_uploadPlanList!=NULL){
  952. list<UploadPlan*>::iterator iter ;
  953. for(iter=m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  954. delete *iter;
  955. }
  956. m_uploadPlanList->clear();
  957. }
  958. m_branchIpList.clear();
  959. //上传模式确定
  960. if(m_centerModel == (int)centerModel){
  961. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel");
  962. //防止url无效,新模式直接停止上传,等待下一次
  963. if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
  964. m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
  965. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("centerModel mode ,centerUrl is null , wait for next time");
  966. ScheduleTimer(1, 240000);
  967. return 0;
  968. }
  969. //新模式,查询策略
  970. if(queryPlan()){
  971. m_uploadModel = true;
  972. }else{
  973. //查询策略失败,等待下一次
  974. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("queryPlan is fail , wait for next time");
  975. ScheduleTimer(1, 240000);
  976. return 0;
  977. }
  978. }else{
  979. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("m_centerModel is invalid");
  980. ScheduleTimer(1, 240000);
  981. return 0;
  982. }
  983. if(m_uploadModel){
  984. //新模式扫描
  985. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_SCAN));
  986. }else{
  987. //旧模式扫描
  988. PostEventLIFO(new FSMEvent(USER_EVT_JMP_OLD_SCAN));
  989. }
  990. }else if (event->iEvt == USER_EVT_JMP_NEW_SCAN) {
  991. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("enter new model upload");
  992. //新模式
  993. if (m_uploadList->size() == 0) {
  994. //重新扫描文件
  995. scanFile();
  996. }
  997. if (m_uploadList->size() == 0) {
  998. DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("m_uploadList is 0,wait for 8 min retry scan");
  999. ScheduleTimer(1, 480000);
  1000. } else {
  1001. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_UPLOAD));//跳到新的上传状态
  1002. }
  1003. }
  1004. return 0;
  1005. }
  1006. void UploadFSM::s3_on_entry()
  1007. {
  1008. }
  1009. void UploadFSM::s3_on_exit()
  1010. {
  1011. }
  1012. unsigned int UploadFSM::s3_on_event(FSMEvent* event)
  1013. {
  1014. return 0;
  1015. }
  1016. void UploadFSM::s4_on_entry()
  1017. {
  1018. }
  1019. void UploadFSM::s4_on_exit()
  1020. {
  1021. }
  1022. unsigned int UploadFSM::s4_on_event(FSMEvent* event)
  1023. {
  1024. return 0;
  1025. }
  1026. void UploadFSM::s5_on_entry()
  1027. {
  1028. }
  1029. void UploadFSM::s5_on_exit()
  1030. {
  1031. }
  1032. unsigned int UploadFSM::s5_on_event(FSMEvent* event)
  1033. {
  1034. return 0;
  1035. }
  1036. void UploadFSM::s6_on_entry()
  1037. {
  1038. }
  1039. void UploadFSM::s6_on_exit()
  1040. {
  1041. }
  1042. unsigned int UploadFSM::s6_on_event(FSMEvent* event)
  1043. {
  1044. return 0;
  1045. }
  1046. void UploadFSM::s7_on_entry()
  1047. {
  1048. //新上传模式
  1049. m_uploadReport.sum = m_uploadList->size();
  1050. m_uploadReport.succ = 0;
  1051. m_uploadReport.fail = 0;
  1052. m_uploadReport.uploadFail = 0;
  1053. m_uploadReport.updateState = 0;
  1054. m_uploadReport.decodeFail = 0;
  1055. m_uploadReport.operateFileFail= 0;
  1056. m_uploadReport.queryTempFail =0;
  1057. m_uploadReport.isBreak =false;
  1058. //获取一个新文件,发送上传请求线程
  1059. if(m_uploadList->size()>0){
  1060. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1061. m_uploadList->pop_front();//去除首元素
  1062. Task::SendFileTask* task = new Task::SendFileTask(this);
  1063. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1064. if (rc != Error_Succeed)
  1065. {
  1066. if(m_currUploadFile!=NULL){
  1067. delete m_currUploadFile;
  1068. m_currUploadFile=NULL;
  1069. }
  1070. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 30s retry");
  1071. ScheduleTimer(7, 30000);
  1072. }
  1073. }
  1074. }
  1075. void UploadFSM::s7_on_exit()
  1076. {
  1077. if(m_currUploadFile!=NULL){
  1078. delete m_currUploadFile;
  1079. m_currUploadFile=NULL;
  1080. }
  1081. CancelTimer(7);
  1082. }
  1083. unsigned int UploadFSM::s7_on_event(FSMEvent* event)
  1084. {
  1085. if (event->iEvt == USER_EVT_UPLOAD_SUCC) {
  1086. m_uploadReport.succ++;//成功计数
  1087. //获取新的上传文件,发送上传请求线程
  1088. //判断是否已经需要退出
  1089. //无文件,跳出此状态
  1090. if(m_isOffLine){
  1091. if(m_uploadList->size()>0){
  1092. if(m_currUploadFile!=NULL){
  1093. delete m_currUploadFile;
  1094. m_currUploadFile=NULL;
  1095. }
  1096. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1097. m_uploadList->pop_front();//去除首元素
  1098. Task::SendFileTask* task = new Task::SendFileTask(this);
  1099. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1100. if (rc != Error_Succeed)
  1101. {
  1102. if(m_currUploadFile!=NULL){
  1103. delete m_currUploadFile;
  1104. m_currUploadFile=NULL;
  1105. }
  1106. m_uploadReport.isBreak =true;
  1107. reportBatchMsg();
  1108. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 240s retry scan");
  1109. ScheduleTimer(7, 240000);
  1110. }
  1111. }else{
  1112. m_uploadReport.isBreak =false;
  1113. reportBatchMsg();
  1114. DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("NewUpload m_uploadList is empty,wait 240s retry scan");
  1115. ScheduleTimer(7, 240000);// goto s2
  1116. }
  1117. }else{
  1118. m_uploadReport.isBreak =true;
  1119. reportBatchMsg();
  1120. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_isOffLine is false,jump s1");
  1121. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_DISABLE));// goto s1
  1122. }
  1123. }else if (event->iEvt == USER_EVT_UPLOAD_FAIL) {
  1124. m_uploadReport.fail++;//失败计数
  1125. //获取新的上传文件,发送上传请求线程
  1126. //判断是否已经需要退出
  1127. //无文件,跳出此状态
  1128. if(m_isOffLine){
  1129. Sleep(3000);//上传失败,等待3秒再下一个
  1130. if(m_uploadList->size()>0){
  1131. if(m_currUploadFile!=NULL){
  1132. delete m_currUploadFile;
  1133. m_currUploadFile=NULL;
  1134. }
  1135. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1136. m_uploadList->pop_front();//去除首元素
  1137. Task::SendFileTask* task = new Task::SendFileTask(this);
  1138. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1139. if (rc != Error_Succeed)
  1140. {
  1141. if(m_currUploadFile!=NULL){
  1142. delete m_currUploadFile;
  1143. m_currUploadFile=NULL;
  1144. }
  1145. m_uploadReport.isBreak =true;
  1146. reportBatchMsg();
  1147. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 240s retry scan");
  1148. ScheduleTimer(7, 240000);
  1149. }
  1150. }else{
  1151. m_uploadReport.isBreak =false;
  1152. reportBatchMsg();
  1153. DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("NewUpload m_uploadList is empty,wait 240s retry scan");
  1154. ScheduleTimer(7, 240000);// goto s2
  1155. }
  1156. }else{
  1157. m_uploadReport.isBreak =true;
  1158. reportBatchMsg();
  1159. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("NewUpload m_isOffLine is false,jump s1");
  1160. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_DISABLE));// goto s1
  1161. }
  1162. }else if (event->iEvt == EVT_TIMER) {
  1163. // goto s2
  1164. DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("NewUpload ,jump to s2");
  1165. }
  1166. return 0;
  1167. }
  1168. //通过
  1169. bool UploadFSM::queryPlan()
  1170. {
  1171. IHttpFunc* client;
  1172. client = create_http(HttpsLogCallBack);
  1173. CSystemStaticInfo si;
  1174. ErrorCodeEnum error = this->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  1175. if(error!=Error_Succeed){
  1176. return false;//获取失败,走旧模式
  1177. }
  1178. UploadQueryPlanReq planReq;
  1179. UploadQueryPlanRet planRet;
  1180. Json::Value rootReq;
  1181. Json::FastWriter writer;
  1182. rootReq["terminal_no"] = si.strTerminalID.GetData();
  1183. #ifdef RVC_OS_WIN
  1184. rootReq["os_type"] = "WIN";
  1185. #else
  1186. rootReq["os_type"] = "UOS";
  1187. #endif
  1188. string jsonReq = writer.write(rootReq);
  1189. planReq.m_reqStr = jsonReq;
  1190. //planReq.m_printDbg = true;
  1191. planReq.m_url = m_centerUrl.queryPlanUrl.c_str();
  1192. PROCESS_LINK_CONTEXT("LR0402104QueryPlan")
  1193. if(!client->Post(planReq, planRet, &nextLink)){
  1194. 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());
  1195. client->Destory();
  1196. return false;//http错误,走旧模式
  1197. }
  1198. client->Destory();
  1199. //解析回应报文
  1200. Json::Reader reader;
  1201. Json::Value rootRet;
  1202. if (!reader.parse(planRet.m_retStr, rootRet, false))
  1203. {
  1204. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryPlan parse resp is fail");
  1205. return false;//解析失败,走旧模式
  1206. }
  1207. bool isSucc = rootRet["success"].asBool();
  1208. if(isSucc){
  1209. if(rootRet.isMember("data")){
  1210. if(rootRet["data"]["mode"].asBool()){
  1211. //新模式
  1212. string branchNO = rootRet["data"]["branch_no"].asString();
  1213. //分行服务器列表:可能为空
  1214. if(rootRet["data"]["upload_address"].isMember("upload_url")){
  1215. for(int i =0;i<rootRet["data"]["upload_address"]["upload_url"].size();i++){
  1216. string bUploadUrl = rootRet["data"]["upload_address"]["upload_url"][i].asString();
  1217. m_branchIpList[i+1]=bUploadUrl;
  1218. if(!bUploadUrl.empty()){
  1219. // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryPlan return upload_url=%s",bUploadUrl.c_str());
  1220. }else{
  1221. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryPlan return upload_url=");
  1222. }
  1223. }
  1224. }else{
  1225. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("[data][upload_address][upload_url] is null");
  1226. }
  1227. string env = "";//上传服务器地址属于行内还是行外
  1228. if(rootRet["data"]["upload_address"].isMember("env")){
  1229. env = rootRet["data"]["upload_address"]["env"].asString();
  1230. if(strcmp(env.c_str(),"DMZ")==0||strcmp(env.c_str(),"BIZ")==0){
  1231. }else{
  1232. 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());
  1233. return false;//上传服务ip环境不正确,走旧模式
  1234. }
  1235. }else{
  1236. 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());
  1237. return false;//上传服务ip环境为空,走旧模式
  1238. }
  1239. //扫描策略:可能为空
  1240. for (int i =0;i <rootRet["data"]["plan_list"].size();i++){
  1241. UploadPlan* p = new UploadPlan();
  1242. p->plan_id = rootRet["data"]["plan_list"][i]["plan_id"].asString();
  1243. p->branch_no = branchNO;//分行号
  1244. p->plan_type = rootRet["data"]["plan_list"][i]["plan_type"].asString();
  1245. p->file_type = rootRet["data"]["plan_list"][i]["file_type"].asString();
  1246. p->path_type = rootRet["data"]["plan_list"][i]["path_type"].asString();
  1247. #ifdef RVC_OS_WIN
  1248. p->path_name = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1249. #else
  1250. //转义路径里面windows反斜杠'\'为'/'
  1251. //p->path_name = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1252. string pathName = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1253. std::replace(pathName.begin(), pathName.end(), '\\', SPLIT_SLASH);
  1254. p->path_name = pathName.c_str();
  1255. #endif
  1256. p->file_name = rootRet["data"]["plan_list"][i]["file_name"].asString();
  1257. p->file_regex = rootRet["data"]["plan_list"][i]["file_regex"].asString();
  1258. p->before_deal_type = rootRet["data"]["plan_list"][i]["before_deal_type"].asString();
  1259. p->after_deal_type = rootRet["data"]["plan_list"][i]["after_deal_type"].asString();
  1260. #ifdef RVC_OS_WIN
  1261. p->after_deal_text = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1262. #else
  1263. //转义路径里面windows反斜杠'\'为'/'
  1264. //p->after_deal_text = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1265. string afterDealText = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1266. std::replace(afterDealText.begin(), afterDealText.end(), '\\', SPLIT_SLASH);
  1267. p->after_deal_text = afterDealText.c_str();
  1268. #endif
  1269. p->file_limit = rootRet["data"]["plan_list"][i]["file_limit"].asInt();
  1270. if (p->file_limit <= 0) {
  1271. //默认文件最大扫描个数为1000
  1272. p->file_length_limit = 1000;
  1273. }
  1274. p->file_length_limit = rootRet["data"]["plan_list"][i]["file_length_limit"].asInt();//增加扫描文件最大长度限制
  1275. if(p->file_length_limit==0){
  1276. //默认扫描文件最大长度设置为200m
  1277. p->file_length_limit = 200;
  1278. }
  1279. p->max_silent = rootRet["data"]["plan_list"][i]["max_silent"].asInt();
  1280. if (p->max_silent <= 0) {
  1281. //默认文件流逝时间间隔为900s
  1282. p->file_length_limit = 900;
  1283. }
  1284. p->upload_address_env = env;
  1285. m_uploadPlanList->push_back(p);
  1286. }
  1287. if(m_branchIpList.size()==0){
  1288. 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());
  1289. return false;//上传服务ip为空,走旧模式
  1290. }
  1291. if(m_uploadPlanList->size()==0){
  1292. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryPlan return %d plan ",m_uploadPlanList->size());
  1293. return true;//等待下一次请求,走新模式
  1294. }
  1295. return true;//明确走新模式
  1296. }else{
  1297. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryPlan return [data].[mode] is false");
  1298. return false;//明确走旧模式
  1299. }
  1300. }else{
  1301. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryPlan return data is null");
  1302. return false;//无data字段,走旧模式
  1303. }
  1304. }else{
  1305. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("queryPlan return success is false");
  1306. return false;//服务返回错误,走旧模式
  1307. }
  1308. }
  1309. //通过
  1310. void UploadFSM::scanFile()
  1311. {
  1312. list<UploadPlan*>::iterator iter;
  1313. for(iter = m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  1314. UploadPlan* up = *iter;
  1315. //构建初始的扫描根路径
  1316. string path="";
  1317. if(up->path_type=="R"){
  1318. #ifdef RVC_OS_WIN
  1319. path = m_rootPath + "\\" + up->path_name;
  1320. #else
  1321. path = m_rootPath + SPLIT_SLASH_STR + up->path_name;
  1322. #endif
  1323. }else if(up->path_type=="A"){
  1324. path=up->path_name;
  1325. }else{
  1326. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("plan path_type is invalid path_type=%s",up->path_type.c_str());
  1327. continue;
  1328. }
  1329. if(m_printPlan){
  1330. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("planID=[%s], scanDir=[%s], filter=[%s], file_limit=[%d], max_silent=[%d]",up->plan_id.c_str(),path.c_str(),up->file_name.c_str(),up->file_limit,up->max_silent);
  1331. }
  1332. scanDirfresh(up,path.c_str());
  1333. }
  1334. m_printPlan=false;//只打印一次,设置为不打印
  1335. //加入文件超过阈值后告警
  1336. if(m_uploadList->size()>m_uploadMaxNum){
  1337. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_MAX_ERROR, CSimpleStringA::Format("upload list num(%d) is over max num",m_uploadList->size()).GetData());
  1338. }
  1339. }
  1340. //通过
  1341. void UploadFSM::scanDirfresh(UploadPlan* plan,const char *path)
  1342. {
  1343. array_header_t *arr_files = fileutil_get_sub_files2_a(path, plan->file_limit);
  1344. if (arr_files) {
  1345. int i;
  1346. for (i = 0; i < arr_files->nelts; ++i){
  1347. char *file_path = ARRAY_IDX(arr_files, i, char*);
  1348. //得到文件名
  1349. string fileName = _GetFileName(file_path);
  1350. //文件名通配符过滤
  1351. CSimpleStringA strFileFilter = _GetFileName(plan->file_name.c_str());
  1352. if(!IsFileMatch(strFileFilter.GetData(),fileName.c_str())){
  1353. continue;//继续下一个文件
  1354. }
  1355. //正则表达式过滤
  1356. if(!plan->file_regex.empty()){
  1357. regex e(plan->file_regex.c_str());
  1358. if(!regex_match(fileName.c_str(),e,regex_constants::match_default)){
  1359. continue;//继续下一个文件
  1360. }
  1361. }
  1362. #ifdef RVC_OS_WIN
  1363. //最后修改时间间隔过滤
  1364. WIN32_FILE_ATTRIBUTE_DATA attr;
  1365. if (!GetFileAttributesExA(file_path, GetFileExInfoStandard, &attr)) {
  1366. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get local file attrr fail! file_path=%s",file_path);
  1367. continue;//继续下一个文件
  1368. }
  1369. //判断文件是否超过最大扫描文件长度
  1370. unsigned long limit = plan->file_length_limit*1024*1024;
  1371. if(attr.nFileSizeLow>limit){
  1372. if (!findOverLenWarn(file_path)) {
  1373. //未找到则告警
  1374. 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);
  1375. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_FILE_OVER_LIMIT, warnStr.GetData());
  1376. }
  1377. continue;//继续下一个文件
  1378. }
  1379. FILETIME fttmp;
  1380. SYSTEMTIME filest;
  1381. SYSTEMTIME st;
  1382. if(!FileTimeToLocalFileTime(&attr.ftLastWriteTime,&fttmp)){
  1383. continue;//继续下一个文件
  1384. }
  1385. if(!FileTimeToSystemTime(&fttmp,&filest)){
  1386. continue;//继续下一个文件
  1387. }
  1388. GetLocalTime(&st);
  1389. 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);
  1390. if(nsecondsInterval<plan->max_silent){
  1391. continue;//继续下一个文件,时间不够
  1392. }else{
  1393. //时间已够,判断文件是否能独占锁
  1394. if(!test_zero_ref(file_path)){
  1395. continue;//继续下一个文件
  1396. }
  1397. }
  1398. //得到文件长度
  1399. unsigned long filelen = attr.nFileSizeLow;
  1400. #else
  1401. struct stat attr_of_src;
  1402. if (lstat(file_path, &attr_of_src) != 0) {
  1403. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get local file attrr fail! file_path=%s", file_path);
  1404. continue;//继续下一个文件
  1405. }
  1406. //判断文件是否超过最大扫描文件长度
  1407. unsigned long limit = plan->file_length_limit * 1024 * 1024;
  1408. if (attr_of_src.st_size > limit) {
  1409. 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);
  1410. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_FILE_OVER_LIMIT, warnStr.GetData());
  1411. continue;//继续下一个文件
  1412. }
  1413. time_t nowTime = time((time_t*)NULL);//当前时间
  1414. if (nowTime > attr_of_src.st_mtime)
  1415. {
  1416. long diff = nowTime - attr_of_src.st_mtime;
  1417. if (diff < plan->max_silent)
  1418. {
  1419. continue;//继续下一个文件,时间不够
  1420. }else{
  1421. //时间已够,判断文件是否能独占锁
  1422. if (!test_zero_ref(file_path)) {
  1423. continue;//继续下一个文件
  1424. }
  1425. }
  1426. }else {
  1427. continue;//继续下一个文件,时间不够
  1428. }
  1429. //得到文件长度
  1430. unsigned long filelen = attr_of_src.st_size;
  1431. #endif
  1432. //添加扫描文件
  1433. UploadFileInfo* upFile = new UploadFileInfo();
  1434. upFile->firstMD5Str = "";
  1435. upFile->lastMD5Str = "";
  1436. upFile->fileName = fileName;
  1437. upFile->filePath = file_path;
  1438. if(upFile->filePath.length()>900){
  1439. //路径太长,ECS存储有问题,截取路径,并加入模拟路径前缀:window S:\\ , linux /S/
  1440. #ifdef RVC_OS_WIN
  1441. upFile->fileUploadPath.append("S:\\");
  1442. #else
  1443. upFile->fileUploadPath.append("/S/");
  1444. #endif
  1445. upFile->fileUploadPath.append(fileName.c_str());
  1446. //upFile->fileUploadRelativePath = "S:\\";
  1447. }else{
  1448. //直接赋值
  1449. upFile->fileUploadPath = file_path;
  1450. //upFile->fileUploadRelativePath = upFile->fileUploadPath.substr(0,upFile->fileUploadPath.length()-fileName.length());//截取文件名称的路径
  1451. }
  1452. upFile->BranchFilePath = file_path;
  1453. upFile->fileLen = filelen;
  1454. #ifdef RVC_OS_WIN
  1455. upFile->editTime = CSimpleStringA::Format("%d-%d-%d %d:%d:%d",filest.wYear, filest.wMonth, filest.wDay, filest.wHour, filest.wMinute, filest.wSecond);
  1456. #else
  1457. tm fileTimeTm = { 0 };
  1458. localtime_r(&attr_of_src.st_mtime, &fileTimeTm);
  1459. 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);
  1460. #endif
  1461. upFile->plan_id = plan->plan_id;
  1462. upFile->branch_no = plan->branch_no;
  1463. upFile->plan_type = plan->plan_type;
  1464. upFile->file_type = plan->file_type;
  1465. upFile->path_type = plan->path_type;
  1466. upFile->path_name = plan->path_name;//因传回路径可能是windows路径斜杠,转义为linux斜杠
  1467. upFile->file_name = plan->file_name;
  1468. upFile->file_regex = plan->file_regex;
  1469. upFile->before_deal_type = plan->before_deal_type;
  1470. upFile->after_deal_type = plan->after_deal_type;
  1471. upFile->after_deal_text = plan->after_deal_text;
  1472. upFile->file_limit = plan->file_limit;
  1473. upFile->file_length_limit = plan->file_length_limit;
  1474. upFile->max_silent = plan->max_silent;
  1475. upFile->upload_address_env = plan->upload_address_env;
  1476. m_uploadList->push_back(upFile);
  1477. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("file %s lenth(%d) added!",file_path,filelen);
  1478. }
  1479. toolkit_array_free2(arr_files);
  1480. }
  1481. array_header_t *arr_dir = fileutil_get_sub_dirs_a(path);
  1482. if (arr_dir) {
  1483. int i;
  1484. for (i = 0; i < arr_dir->nelts; ++i) {
  1485. char *dir_path = ARRAY_IDX(arr_dir, i, char*);
  1486. scanDirfresh(plan, dir_path);
  1487. }
  1488. }
  1489. }
  1490. void UploadFSM::HttpsLogCallBack(const char* logtxt)
  1491. {
  1492. if(logtxt!=NULL){
  1493. DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("http dbg: %s",logtxt);
  1494. }
  1495. }
  1496. bool UploadFSM::IsFileMatch(const char *pszFilter, const char *pszFileName)
  1497. {
  1498. const char *p1 = pszFilter;
  1499. const char *p2 = pszFileName;
  1500. if (p1 == NULL)
  1501. return true;
  1502. if (p2 == NULL)
  1503. return false;
  1504. if (*p1 ==NULL && *p2 ==NULL)
  1505. return true;
  1506. else if (*p1 == NULL)
  1507. return false;
  1508. else if (*p2 == NULL)
  1509. {
  1510. // 查找*p1是否全是*
  1511. while(*p1 == '*')
  1512. p1++;
  1513. if (*p1 == NULL)
  1514. return true;
  1515. else
  1516. return false;
  1517. }
  1518. if (*p1 != '*')
  1519. {
  1520. if (tolower(*p1) != tolower(*p2))
  1521. return false;
  1522. else
  1523. return IsFileMatch(p1+1, p2+1);
  1524. }
  1525. else
  1526. {
  1527. while(*++p1 == '*');
  1528. if (*p1 == NULL)
  1529. return true;
  1530. while (*p2)
  1531. {
  1532. while(tolower(*p1) != tolower(*p2) && *++p2);
  1533. if (*p2 == NULL)
  1534. return false;
  1535. if(IsFileMatch(p1+1, p2+1))
  1536. return true;
  1537. p2++;
  1538. }
  1539. return false;
  1540. }
  1541. }
  1542. ErrorCodeEnum UploadFSM::SM3FileToStr(CSimpleStringA strFilePath, CSimpleStringA &strSM3,bool isSub)
  1543. {
  1544. if(strFilePath.IsNullOrEmpty()){
  1545. return Error_Null;
  1546. }
  1547. int nlen = strlen(strFilePath.GetData());
  1548. char* pchar = new char[nlen+1];
  1549. strcpy(pchar,strFilePath.GetData());
  1550. BYTE md5[32]={0};
  1551. try
  1552. {
  1553. if(SM3File(pchar,md5)){
  1554. delete pchar;
  1555. //获取16进制的字符串
  1556. if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
  1557. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("sm3国密转16进制字符串失败,file=%s",strFilePath.GetData());
  1558. return Error_Unexpect;
  1559. }
  1560. return Error_Succeed;
  1561. }else{
  1562. delete pchar;
  1563. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("sm3国密加密失败,file=%s",strFilePath.GetData());
  1564. return Error_Unexpect;
  1565. }
  1566. }
  1567. catch (...)
  1568. {
  1569. delete pchar;
  1570. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("sm3国密加密异常失败,file=%s",strFilePath.GetData());
  1571. return Error_Exception;
  1572. }
  1573. }
  1574. ErrorCodeEnum UploadFSM::SM3_Str(CSimpleStringA &strSM3,BYTE * SM3Byte,bool isSub)
  1575. {
  1576. if(SM3Byte == NULL){
  1577. return Error_Exception;
  1578. }
  1579. int SM3_len=64;
  1580. if(isSub){
  1581. SM3_len=32;
  1582. }
  1583. int i;
  1584. char* file_SM3 = (char*)malloc((SM3_len + 1) * sizeof(char));
  1585. if(file_SM3 == NULL)
  1586. {
  1587. fprintf(stderr, "SM3 malloc failed.\n");
  1588. return Error_Exception;
  1589. }
  1590. memset(file_SM3, 0, (SM3_len + 1));
  1591. if(SM3_len == 32)
  1592. {
  1593. for(i=0; i<16; i++)
  1594. { //SM3截取中间16位字节,8-24位字节数,小写
  1595. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i+8]);
  1596. }
  1597. }
  1598. else if(SM3_len == 64)
  1599. {
  1600. for(i=0; i<32; i++)
  1601. {
  1602. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i]);
  1603. }
  1604. }
  1605. strSM3=file_SM3;
  1606. free(file_SM3);
  1607. return Error_Succeed;
  1608. }
  1609. bool UploadFSM::getFileContent(FILE* pFile,unsigned char* content,int beginPos, int contentLen)
  1610. {
  1611. if(pFile==NULL||content==NULL){
  1612. return false;
  1613. }
  1614. #ifdef RVC_OS_WIN
  1615. clearerr(pFile);//尝试先复位错误指针
  1616. #endif
  1617. if(fseek(pFile,beginPos,SEEK_SET)!=0){
  1618. #ifdef RVC_OS_WIN
  1619. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("getFileContent fail,fseek beginPos =%d is error =%d",beginPos,(int)GetLastError());
  1620. #else
  1621. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("getFileContent fail,fseek beginPos =%d is error =%d",beginPos, errno);
  1622. #endif
  1623. return false;
  1624. }
  1625. unsigned char* pRead = content;//移动的指针
  1626. int pRemaind = contentLen; //剩余字节数
  1627. int numBytes = 0;
  1628. while(!feof(pFile)&&!ferror(pFile)){
  1629. if(pRemaind<=0){
  1630. break;
  1631. }
  1632. numBytes=(int)fread(pRead,1,pRemaind,pFile);
  1633. if(numBytes>0){
  1634. pRemaind -=numBytes;
  1635. pRead +=numBytes;
  1636. }
  1637. }
  1638. if(pRemaind==0){
  1639. return true;
  1640. }else{
  1641. #ifdef RVC_OS_WIN
  1642. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("getFileContent fail,pRemaind =%d, error=%d",pRemaind,(int)GetLastError());
  1643. #else
  1644. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("getFileContent fail,pRemaind =%d, error=%d",pRemaind, errno);
  1645. #endif
  1646. return false;
  1647. }
  1648. }
  1649. bool UploadFSM::test_zero_ref(const char *path)
  1650. {
  1651. #ifdef RVC_OS_WIN
  1652. HANDLE hFile = CreateFileA(path,
  1653. GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // try open
  1654. if (hFile != INVALID_HANDLE_VALUE) {
  1655. CloseHandle(hFile);
  1656. return TRUE;
  1657. } else {
  1658. //添加获取句柄失败情况
  1659. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_SCANFILE_LOCK_ERROR, CSimpleStringA::Format("test_zero_ref is fail:%s",path).GetData());
  1660. DWORD dwRet = GetLastError();
  1661. return FALSE;
  1662. }
  1663. #else
  1664. //后期改为linux真正的文件锁,现在来看,暂时用不着
  1665. FILE* fp = fopen(path, "rb");
  1666. if (fp != NULL) {
  1667. fclose(fp);
  1668. return true;
  1669. }
  1670. else
  1671. {
  1672. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_SCANFILE_LOCK_ERROR, CSimpleStringA::Format("check_zero_ref is fail:%s", path).GetData());
  1673. return false;
  1674. }
  1675. #endif // RVC_OS_WIN
  1676. }
  1677. bool UploadFSM::GetFileLength(const char* filePath,long &fileLen)
  1678. {
  1679. FILE* file = fopen(filePath, "rb");
  1680. if (file!=NULL)
  1681. {
  1682. #ifdef RVC_OS_WIN
  1683. fileLen = filelength(fileno(file));
  1684. fclose(file);
  1685. return true;
  1686. #else
  1687. //取得当前文件流的读取位置
  1688. int cur_pos = ftell(file);
  1689. //将文件流的读取位置设为文件末尾
  1690. if (fseek(file, SEEK_SET, SEEK_END)==0) {
  1691. //获取文件末尾的读取位置,即文件大小
  1692. fileLen = ftell(file);
  1693. //将文件流的读取位置还原为原先的值
  1694. fseek(file, cur_pos, SEEK_SET);
  1695. fclose(file);
  1696. return true;
  1697. }
  1698. else {
  1699. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("fseek file=%s is fail, err=%d", filePath,errno);
  1700. fclose(file);
  1701. return false;
  1702. }
  1703. #endif
  1704. } else{
  1705. fileLen = 0;
  1706. return false;
  1707. }
  1708. }
  1709. void UploadFSM::reportBatchMsg()
  1710. {
  1711. CSimpleStringA strReport;
  1712. if(m_uploadReport.fail==0){
  1713. 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)",
  1714. m_uploadReport.isBreak, m_uploadReport.sum, m_uploadReport.succ, m_uploadReport.fail, m_uploadReport.uploadFail, m_uploadReport.updateState,
  1715. m_uploadReport.operateFileFail, m_uploadReport.decodeFail, m_uploadReport.queryTempFail);
  1716. //LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
  1717. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)(strReport.GetData());
  1718. }else{
  1719. 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)",
  1720. m_uploadReport.isBreak, m_uploadReport.sum, m_uploadReport.succ, m_uploadReport.fail, m_uploadReport.uploadFail, m_uploadReport.updateState,
  1721. m_uploadReport.operateFileFail, m_uploadReport.decodeFail, m_uploadReport.queryTempFail);
  1722. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
  1723. }
  1724. //LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
  1725. }
  1726. bool UploadFSM::findOverLenWarn(const char* fileName) {
  1727. if (m_overLenFileList != NULL) {
  1728. bool isfind = false;
  1729. list<string>::iterator iter;
  1730. for (iter = m_overLenFileList->begin(); iter != m_overLenFileList->end(); ++iter) {
  1731. string fileStr = *iter;
  1732. if (strcmp(fileName, fileStr.c_str()) == 0) {
  1733. isfind = true;
  1734. break;
  1735. }
  1736. }
  1737. if (!isfind) {
  1738. //未找到,加入队列
  1739. m_overLenFileList->push_back(fileName);
  1740. }
  1741. return isfind;
  1742. }
  1743. return false;
  1744. }