UploadFSM.cpp 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889
  1. #include "stdafx.h"
  2. #include "UploadFSM.h"
  3. #include <thread>
  4. #include "upload.h"
  5. #include "libtoolkit/path.h"
  6. #include <regex>
  7. #include <fileutil.h>
  8. #include <array.h>
  9. #ifdef RVC_OS_WIN
  10. #include <cstdlib>
  11. #include <ctime>
  12. #include "..\EventCode.h"
  13. #include "..\..\other\libfilecryption\filecryption.h"
  14. #else
  15. #include <sys/stat.h>
  16. #include <sys/types.h>
  17. #include <fcntl.h>
  18. #include <time.h>
  19. #include <stdio.h>
  20. #include <cstdio>
  21. #include <iostream>
  22. #include <errno.h>
  23. #include "EventCode.h"
  24. #endif
  25. #define UPLOAD_CONTENT_EACH_LEN 2*1024*1024
  26. UploadFSM::UploadFSM() : m_pConnection(NULL),m_currUploadFile(NULL)
  27. {
  28. m_uploadList = new list<UploadFileInfo*>();
  29. m_uploadPlanList = new list<UploadPlan *>();
  30. m_eachUploadLen=UPLOAD_CONTENT_EACH_LEN;
  31. m_uploadMaxNum = 1000;
  32. m_isOffLine=true;//初始离线状态为true
  33. m_printPlan = true;//初始化为打印
  34. }
  35. UploadFSM::~UploadFSM()
  36. {
  37. #ifndef _WIN32
  38. if (m_uploading_handle) {
  39. fclose(m_uploading_handle);
  40. m_uploading_handle = NULL;
  41. }
  42. #endif //NOT _WIN32
  43. }
  44. namespace Task
  45. {
  46. struct SendFileTask : public ITaskSp
  47. {
  48. UploadFSM* m_fsm;
  49. explicit SendFileTask(UploadFSM* e) : m_fsm(e) {}
  50. void Process() {
  51. //判断是分行url请求还是总行url请求
  52. //判断是临时文件还是永久文件
  53. //循环上传
  54. //登记上传流水或者失败流水
  55. //根据最终上传结果返回成功还是失败
  56. CSystemStaticInfo info;
  57. auto rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  58. if (rc != Error_Succeed)
  59. {
  60. Dbg("get CSystemStaticInfo fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  61. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_FAIL));//失败发送
  62. return;
  63. }
  64. bool isLanTerminal=true;//行内行外标志
  65. //if(info.strSite.Compare("CMB.LIB",true)==0||info.strSite.Compare("CMB.SSB",true)==0){
  66. // isLanTerminal=true;
  67. //}else{
  68. // isLanTerminal=false;
  69. //}
  70. if(strcmp(m_fsm->m_currUploadFile->upload_address_env.c_str(),"BIZ")==0){
  71. isLanTerminal=true;
  72. }else{
  73. isLanTerminal=false;
  74. }
  75. IHttpFunc* client;
  76. client = create_http(m_fsm->HttpsLogCallBack);
  77. bool hasSend=false;
  78. if(m_fsm->m_currUploadFile->plan_type=="T"){
  79. //查询失败统一需要上传
  80. if(queryTempFile(client,info)){
  81. hasSend=true;
  82. }
  83. }
  84. //是否需要上传文件
  85. bool sendOk = false;
  86. if(!hasSend){
  87. string errmsg ="";
  88. if(isLanTerminal){
  89. //Dbg("上传文件到分行:%s",m_fsm->m_currUploadFile->filePath.c_str());
  90. }else{
  91. //Dbg("上传文件到总行:%s",m_fsm->m_currUploadFile->filePath.c_str());
  92. }
  93. string MD5str = ""; //返回的MD5值
  94. string branchFilePath = ""; //返回的分行保存路径值
  95. //修改为重试上传机制,防止上传当中网络抖动,避免等待下次上传
  96. bool isUploadSucc=false;
  97. for (int i =0 ; i<2;i++ )
  98. {
  99. errmsg="";//每次上传前清空错误信息,只记录最后一次的
  100. if(uploadFile(client,info,MD5str,branchFilePath,errmsg)){
  101. isUploadSucc = true;
  102. break;
  103. }
  104. Sleep(3000);//等待3秒下次传送
  105. }
  106. if(isUploadSucc){
  107. if(updateState(client,info,isLanTerminal,MD5str,branchFilePath,errmsg)){
  108. if(operateFile(errmsg)){
  109. sendOk = true;//成功
  110. }else{
  111. m_fsm->m_uploadReport.operateFileFail++;//添加操作失败计数
  112. Dbg("operateFile fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  113. addUploadFail(client,info,isLanTerminal,"2",errmsg);//操作失败
  114. }
  115. }else{
  116. m_fsm->m_uploadReport.updateState++;//添加登记失败计数
  117. Dbg("updateState fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  118. addUploadFail(client,info,isLanTerminal,"1",errmsg);//登记失败
  119. }
  120. }else{
  121. m_fsm->m_uploadReport.uploadFail++;//添加上传失败计数
  122. Dbg("uploadFile fail,file = %s",m_fsm->m_currUploadFile->filePath.c_str());
  123. addUploadFail(client,info,isLanTerminal,"1",errmsg);//上传失败
  124. }
  125. }else{
  126. sendOk=true;
  127. }
  128. client->Destory();
  129. if(sendOk){
  130. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_SUCC));//成功发送
  131. }else{
  132. m_fsm->PostEventFIFO(new FSMEvent(USER_EVT_UPLOAD_FAIL));//失败发送
  133. }
  134. }
  135. //上传文件:断点续传,多次调用
  136. bool uploadFile(IHttpFunc* client,CSystemStaticInfo info,string &MD5str,string &branchFilePath, string &errmsg){
  137. string reqUrl;
  138. unsigned seed;
  139. seed = time(0);
  140. srand(seed);
  141. if(m_fsm->m_branchIpList.size()>0){
  142. int branchSeq = (rand() % m_fsm->m_branchIpList.size()) + 1;
  143. map<int,string>::iterator it = m_fsm->m_branchIpList.find(branchSeq);
  144. if(it != m_fsm->m_branchIpList.end())
  145. {
  146. reqUrl = it->second;
  147. }else{
  148. Dbg("uploadFile is fail ,branchIp[%d] is null",branchSeq);
  149. errmsg = CSimpleStringA::Format("uploadFile is fail ,branchIp[%d] is null",branchSeq).GetData();
  150. return false;
  151. }
  152. }else{
  153. Dbg("uploadFile is fail ,branchIp is null");
  154. errmsg = "uploadFile is fail ,branchIp is null";
  155. return false;
  156. }
  157. //解密文件
  158. unsigned char* pdecdata = NULL;//记得释放内存
  159. size_t udecheadlen = 0;
  160. int decOffSet = 0;//文件明文头和密文头的偏移量:可能是负数、零、正数
  161. char* pHeadJson = NULL;//记得释放内存
  162. size_t uheadJsonLen = 0;
  163. #ifdef RVC_OS_WIN
  164. filecryption_callback_t cb = {0};
  165. cb.dbg = &Dbg;
  166. int decRet = rvc_file_decrypt(&pdecdata,&udecheadlen,&decOffSet,&pHeadJson,&uheadJsonLen,m_fsm->m_currUploadFile->filePath.c_str(),&cb);
  167. #else
  168. int decRet = 0;
  169. #endif
  170. if(decRet!=0){
  171. //解密报错
  172. Dbg("uploadFile is fail, decode file fail=%d",decRet);
  173. errmsg=CSimpleStringA::Format("uploadFile is fail, decode file fail=%d",decRet).GetData();
  174. #ifdef RVC_OS_WIN
  175. rvc_free_data((void**)&pdecdata);
  176. rvc_free_data((void**)&pHeadJson);
  177. #endif
  178. m_fsm->m_uploadReport.decodeFail++;//添加解密失败计数
  179. return false;
  180. }
  181. //计算出解密后总长度:
  182. m_fsm->m_currUploadFile->decFileLen = m_fsm->m_currUploadFile->fileLen-decOffSet;//重新赋值
  183. //Dbg("decode file len=%d, decOffSet=%d, decHeadLen=%d, uheadJsonLen=%d",m_fsm->m_currUploadFile->decFileLen,decOffSet,(int)udecheadlen,(int)uheadJsonLen);
  184. //解密自定义头赋值
  185. if(pHeadJson!=NULL){
  186. m_fsm->m_currUploadFile->decHeadJson = pHeadJson;
  187. }else{
  188. m_fsm->m_currUploadFile->decHeadJson = "";
  189. }
  190. //Dbg("decode file decHeadJson = %s",m_fsm->m_currUploadFile->decHeadJson.c_str());
  191. //获取服务器文件长度
  192. unsigned char* contentFirst = new unsigned char[1];
  193. memset(contentFirst,0,1);
  194. UploadDataRet respFirst ={0};
  195. bool is_finish =false; //是否续传
  196. if(!uploadFileImpl(client,info,reqUrl,contentFirst,0,"",respFirst)){
  197. delete[] contentFirst;
  198. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl first is fail",reqUrl.c_str()).GetData();
  199. #ifdef RVC_OS_WIN
  200. rvc_free_data((void**)&pdecdata);
  201. rvc_free_data((void**)&pHeadJson);
  202. #endif
  203. return false;//返回失败
  204. }else{
  205. delete[] contentFirst;
  206. }
  207. long uploadedLen = respFirst.uploaded_length;//服务器返回已上传的长度
  208. //Dbg("服务器返回临时长度 uploadedLen = %d",uploadedLen);
  209. if(uploadedLen>m_fsm->m_currUploadFile->decFileLen){
  210. //服务器返回长度大于终端文件长度
  211. Dbg("uploadFile is fail, server filelen [%d] is over terminal decfilelen [%d]",uploadedLen,m_fsm->m_currUploadFile->decFileLen);
  212. errmsg=CSimpleStringA::Format("uploadFile is fail, server filelen [%d] is over terminal decfilelen [%d]",uploadedLen,m_fsm->m_currUploadFile->decFileLen).GetData();
  213. #ifdef RVC_OS_WIN
  214. rvc_free_data((void**)&pdecdata);
  215. rvc_free_data((void**)&pHeadJson);
  216. #endif
  217. return false;
  218. }
  219. //密文解密
  220. if(uploadedLen==0){
  221. //文件头传输
  222. if(udecheadlen>0){
  223. //密文数据,传送首块,传解密字节块
  224. UploadDataRet firstResp ={0};
  225. if(!uploadFileImpl(client,info,reqUrl,pdecdata,(long)udecheadlen,"",firstResp)){
  226. #ifdef RVC_OS_WIN
  227. rvc_free_data((void**)&pdecdata);
  228. rvc_free_data((void**)&pHeadJson);
  229. #endif
  230. errmsg="uploadFileImpl first data upload is fail";
  231. Dbg("uploadFileImpl first data upload is fail, url=%s",reqUrl.c_str());
  232. return false;//返回错误
  233. }
  234. }
  235. uploadedLen += (long)udecheadlen+decOffSet;//改变文件游标偏移量
  236. }else{
  237. //数据传输
  238. uploadedLen += decOffSet; //改变文件游标偏移量
  239. }
  240. #ifdef RVC_OS_WIN
  241. rvc_free_data((void**)&pdecdata);//释放解密内存
  242. rvc_free_data((void**)&pHeadJson);
  243. #endif
  244. //Dbg("decode file decHeadJson = %s",strHeadJson.c_str());
  245. if(uploadedLen>m_fsm->m_currUploadFile->fileLen){
  246. //续传起始位置大于终端文件长度
  247. Dbg("uploadFile is fail, begin read filelen [%d] is over terminal filelen [%d]",uploadedLen,m_fsm->m_currUploadFile->fileLen);
  248. errmsg=CSimpleStringA::Format("uploadFile is fail, begin read filelen [%d] is over terminal filelen [%d]",uploadedLen,m_fsm->m_currUploadFile->fileLen).GetData();
  249. return false;
  250. }
  251. if(uploadedLen<0){
  252. //服务器报错的头文件内容加上偏移量后,极端情况可能会出现负数,设置为零,最后服务端做长度比较不相同,会清空临时文件重传
  253. Dbg("uploadFile decode uploadedLen beginPos < 0");
  254. uploadedLen =0;
  255. }
  256. //Dbg("文件开始传送位置 uploadedLen = %d",uploadedLen);
  257. Dbg("文件[%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);
  258. //循环传送数据块
  259. FILE* pFile =fopen(m_fsm->m_currUploadFile->filePath.c_str(),"rb");
  260. if(pFile==NULL){
  261. //读取文件失败;
  262. Dbg("uploadFile is fail, file open fail");
  263. errmsg="uploadFile is fail, file open fail";
  264. return false;
  265. }
  266. bool uploadSucc= false;
  267. while(true){
  268. //续传
  269. if((m_fsm->m_currUploadFile->fileLen-uploadedLen)>m_fsm->m_eachUploadLen){
  270. int uploadLen = m_fsm->m_eachUploadLen;//传送数据长度
  271. unsigned char* content = new unsigned char[uploadLen];
  272. memset(content,0,uploadLen);
  273. //从文件拷贝字节
  274. //Dbg("拷贝字节开始,文件[%s],起始位:%d,拷贝字节数:%d",m_fsm->m_currUploadFile->filePath.c_str(),uploadedLen,uploadLen);
  275. if(m_fsm->getFileContent(pFile,content,uploadedLen,uploadLen)){
  276. UploadDataRet resp ={0};
  277. if(uploadFileImpl(client,info,reqUrl,content,uploadLen,"",resp)){
  278. delete[] content;
  279. uploadedLen +=uploadLen;//改变已上传长度
  280. }else{
  281. delete[] content;
  282. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl continue is fail",reqUrl.c_str()).GetData();
  283. break;//上传失败
  284. }
  285. }else{
  286. delete[] content;
  287. errmsg="uploadFile is fail , getFileContent fail";
  288. break;//获取文件内存失败
  289. }
  290. }else{
  291. //获取最后一次传送时文件长度
  292. CSimpleStringA filepath = m_fsm->m_currUploadFile->filePath.c_str();
  293. long fileLastLen = 0;
  294. if(!m_fsm->GetFileLength(filepath.GetData(),fileLastLen)){
  295. errmsg="uploadFile is fail , end get file len fail";
  296. break;//计算sm3出错
  297. }
  298. string fileLastLenStr= CSimpleStringA::Format("%d",fileLastLen-decOffSet).GetData();//计算出解密后总长度
  299. //最后一块
  300. int uploadLen = m_fsm->m_currUploadFile->fileLen-uploadedLen;
  301. unsigned char* contentEnd;
  302. if(uploadLen==0){
  303. //对零的长度特殊处理
  304. contentEnd = new unsigned char[1];
  305. memset(contentEnd,0,1);
  306. }else{
  307. contentEnd = new unsigned char[uploadLen];
  308. memset(contentEnd,0,uploadLen);
  309. }
  310. //Dbg("最后拷贝字节开始,文件[%s],起始位:%d,拷贝字节数:%d",m_fsm->m_currUploadFile->filePath.c_str(),uploadedLen,uploadLen);
  311. if(m_fsm->getFileContent(pFile,contentEnd,uploadedLen,uploadLen)){
  312. UploadDataRet respEnd ={0};
  313. if(uploadFileImpl(client,info,reqUrl,contentEnd,uploadLen,fileLastLenStr,respEnd)){
  314. delete[] contentEnd;
  315. if(respEnd.upload_finish){
  316. uploadSucc =true;//成功
  317. branchFilePath = respEnd.branchFilePath;//分行保存地址
  318. }else{
  319. uploadSucc =false;//失败
  320. }
  321. break;
  322. }else{
  323. delete[] contentEnd;
  324. errmsg=CSimpleStringA::Format("url=%s, uploadFileImpl end is fail",reqUrl.c_str()).GetData();
  325. break;//上传失败
  326. }
  327. }else{
  328. delete[] contentEnd;
  329. errmsg="uploadFile is fail , end getFileContent fail";
  330. break;//获取文件内存失败
  331. }
  332. }
  333. }
  334. if(uploadSucc){
  335. Dbg("uploadFile succ");
  336. }else{
  337. Dbg("uploadFile fail url=%s",reqUrl.c_str());
  338. }
  339. if(pFile){
  340. if(fclose(pFile)!=0){
  341. Dbg("uploadFile fail, close file fail ,url=%s",reqUrl.c_str());
  342. errmsg="uploadFile fail, close file fail";
  343. return false;
  344. }
  345. }
  346. return uploadSucc;
  347. }
  348. //上传文件:具体实现
  349. bool uploadFileImpl(IHttpFunc* client,CSystemStaticInfo info,string httpUrl,unsigned char* fileContent,long fileContentSize,string lastFileLength,UploadDataRet& uploadData){
  350. UploadFileReq qTempReq;
  351. UploadFileRet qTempRet;
  352. qTempRet.m_userCode ="";
  353. qTempRet.m_errMsg="";
  354. Json::Value rootReq;
  355. Json::FastWriter writer;
  356. rootReq["terminal_no"] = info.strTerminalID.GetData();
  357. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  358. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  359. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  360. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  361. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  362. //rootReq["origin_file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();
  363. rootReq["first_file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->decFileLen).GetData();//加密后需要修改,服务端根据此长度做判断
  364. rootReq["last_file_length"] = lastFileLength.c_str();//加密后需要修改,最后一次长度跟服务端保存长度做对比
  365. rootReq["upload_length"] = CSimpleStringA::Format("%d",fileContentSize).GetData();
  366. //rootReq["first_sm3"] = firstMD5Str.c_str();
  367. //rootReq["last_sm3"] = lastMD5Str.c_str();
  368. rootReq["file_head_custom"] = m_fsm->m_currUploadFile->decHeadJson.c_str();//自定义解密的头json格式,可为空
  369. #ifdef RVC_OS_WIN
  370. rootReq["system_type"] = "W";//系统标记,代表路径分隔符
  371. #else
  372. rootReq["system_type"] = "L";//系统标记,代表路径分隔符
  373. #endif
  374. string jsonReq = writer.write(rootReq);
  375. qTempReq.url = httpUrl;
  376. qTempReq.paramContent = jsonReq;
  377. qTempReq.fileName = m_fsm->m_currUploadFile->fileName;
  378. qTempReq.fileContent = fileContent;
  379. qTempReq.fileContentSize= fileContentSize;
  380. qTempReq.m_timeOut = 5*60;//设置超时时间
  381. //qTempReq.m_printDbg=true;
  382. //调用上传接口
  383. //Dbg("测试上传接口:filelen=%d",fileContentSize);
  384. if(!client->UploadFileBlock(qTempReq,qTempRet)){
  385. Dbg("uploadFile http req fail ,url =%s ,fileName = %s",httpUrl.c_str(), m_fsm->m_currUploadFile->fileName.c_str());
  386. return false;
  387. }
  388. if(qTempRet.httpCode!=200){
  389. Dbg("uploadFile http req fail ,retHttpCode=%d, fileName = %s",qTempRet.httpCode, m_fsm->m_currUploadFile->fileName.c_str());
  390. return false;
  391. }
  392. //Dbg("qTempRet=%s",qTempRet.strBody.c_str());
  393. //解析回应报文
  394. Json::Reader reader;
  395. Json::Value rootRet;
  396. if (!reader.parse(qTempRet.strBody, rootRet, false))
  397. {
  398. Dbg("uploadFile http parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->fileName.c_str());
  399. return false;//解析失败
  400. }
  401. uploadData.strBody = qTempRet.strBody;
  402. bool isSucc = rootRet["success"].asBool();
  403. if(isSucc){
  404. if(rootRet.isMember("data")){
  405. uploadData.uploaded_length= rootRet["data"]["uploaded_length"].asInt();
  406. uploadData.upload_finish = rootRet["data"]["upload_finish"].asBool();
  407. uploadData.branchFilePath = rootRet["data"]["branch_file_path"].asCString();
  408. return true;//返回值
  409. }else{
  410. Dbg("uploadFile http [success][data] is invaild , fileName = %s",m_fsm->m_currUploadFile->fileName.c_str());
  411. return false;//无data字段
  412. }
  413. }else{
  414. //失败
  415. 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());
  416. return false;
  417. }
  418. }
  419. //查询临时文件 post
  420. bool queryTempFile(IHttpFunc* client,CSystemStaticInfo info){
  421. UploadQueryTempFileReq qTempReq;
  422. UploadQueryTempFileRet qTempRet;
  423. qTempRet.m_userCode ="";
  424. qTempRet.m_errMsg="";
  425. Json::Value rootReq;
  426. Json::FastWriter writer;
  427. rootReq["terminal_no"] = info.strTerminalID.GetData();
  428. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  429. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  430. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  431. string jsonReq = writer.write(rootReq);
  432. qTempReq.m_reqStr = jsonReq;//请求参数
  433. //qTempReq.m_printDbg = true;
  434. qTempReq.m_url=m_fsm->m_centerUrl.queryTempFileUrl;//访问地址
  435. if(!client->Post(qTempReq, qTempRet)){
  436. Dbg("queryTempFile http req fail ,fileName = %s, err=%s",m_fsm->m_currUploadFile->filePath.c_str(),qTempRet.m_errMsg.c_str());
  437. return false;
  438. }
  439. //解析报文
  440. //Dbg("qTempRet=%s",qTempRet.m_retStr.c_str());
  441. //解析回应报文
  442. Json::Reader reader;
  443. Json::Value rootRet;
  444. if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  445. {
  446. Dbg("queryTempFile parse resp is fail,fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
  447. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  448. return false;//解析失败
  449. }
  450. bool isSucc = rootRet["success"].asBool();
  451. if(isSucc){
  452. if(rootRet.isMember("data")){
  453. if(rootRet["data"]["upload_flag"].asBool()){
  454. return true;//查询有
  455. }else{
  456. return false;//查询没有
  457. }
  458. }else{
  459. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  460. return false;//无data字段
  461. }
  462. }else{
  463. Dbg("queryTempFile [success] is false, fileName = %s",m_fsm->m_currUploadFile->filePath.c_str());
  464. m_fsm->m_uploadReport.queryTempFail++;//添加查询临时失败计数
  465. return false;
  466. }
  467. }
  468. //登记文件流水状态 post
  469. bool updateState(IHttpFunc* client,CSystemStaticInfo info,bool isLanTerminal, string MD5str,string branchFilePath, string &errmsg){
  470. if(!isLanTerminal){
  471. return true;//行外默认是总行那边登记交易流水,终端不再发送交易流水登记,直接返回成功
  472. }
  473. UploadUpdateStateReq updateStateReq;
  474. UploadUpdateStateRet updateStateRet;
  475. updateStateRet.m_userCode="";
  476. updateStateRet.m_errMsg="";
  477. Json::Value rootReq;
  478. Json::FastWriter writer;
  479. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  480. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  481. rootReq["terminal_no"] = info.strTerminalID.GetData();
  482. rootReq["file_type"] = m_fsm->m_currUploadFile->file_type.c_str();
  483. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  484. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  485. rootReq["branch_file_path"] = branchFilePath.c_str();
  486. rootReq["file_length"] = CSimpleStringA::Format("%d",m_fsm->m_currUploadFile->fileLen).GetData();
  487. if(isLanTerminal){
  488. rootReq["status"] = "1";//分行
  489. }else{
  490. rootReq["status"] = "2";//总行
  491. }
  492. rootReq["upload_time"] = CSmallDateTime::GetNow().ToTimeString().GetData();
  493. rootReq["remark"] = "";
  494. rootReq["sm3"] = MD5str.c_str();
  495. string jsonReq = writer.write(rootReq);
  496. updateStateReq.m_reqStr = jsonReq;//请求参数
  497. updateStateReq.m_url=m_fsm->m_centerUrl.updateStateUrl;//访问地址
  498. if(!client->Post(updateStateReq, updateStateRet)){
  499. Dbg("updateState is fail, sysCode=%d , userCode = %s, errmsg = %s",updateStateRet.m_sysCode, updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
  500. errmsg = CSimpleStringA::Format("updateState is fail, sysCode=%d , userCode = %s, errmsg = %s",updateStateRet.m_sysCode, updateStateRet.m_userCode.c_str(), updateStateRet.m_errMsg.c_str());
  501. return false;
  502. }
  503. //解析报文
  504. //Dbg("updateStateRet=%s",updateStateRet.m_retStr.c_str());
  505. //解析回应报文
  506. Json::Reader reader;
  507. Json::Value rootRet;
  508. if (!reader.parse(updateStateRet.m_retStr, rootRet, false))
  509. {
  510. errmsg="return pack parse is fail";
  511. return false;//解析失败
  512. }
  513. bool isSucc = rootRet["success"].asBool();
  514. if(isSucc){
  515. if(rootRet.isMember("data")){
  516. if(rootRet["data"]["update_flag"].asBool()){
  517. return true;//登记成功
  518. }else{
  519. errmsg="return pack [data][update_flag] is not bool";
  520. return false;//登记失败
  521. }
  522. }else{
  523. errmsg="return pack [data] is null";
  524. return false;//无data字段
  525. }
  526. }else{
  527. errmsg="return pack [success] is false";
  528. return false;
  529. }
  530. }
  531. //登记失败文件流水 post
  532. bool addUploadFail(IHttpFunc* client,CSystemStaticInfo info,bool isLanTerminal,string operation,string errmsg){
  533. UploadUploadFailReq updateFailReq;
  534. UploadUploadFailRet updateFailRet;
  535. updateFailRet.m_userCode="";
  536. updateFailRet.m_errMsg="";
  537. Json::Value rootReq;
  538. Json::FastWriter writer;
  539. rootReq["plan_id"] = m_fsm->m_currUploadFile->plan_id.c_str();
  540. rootReq["branch_no"] = m_fsm->m_currUploadFile->branch_no.c_str();
  541. rootReq["terminal_no"] = info.strTerminalID.GetData();
  542. rootReq["file_name"] = m_fsm->m_currUploadFile->fileName.c_str();
  543. rootReq["file_path"] = m_fsm->m_currUploadFile->fileUploadPath.c_str();
  544. if(isLanTerminal){
  545. rootReq["stage"] = "1";//分行
  546. }else{
  547. rootReq["stage"] = "2";//总行
  548. }
  549. rootReq["operation"] = operation;
  550. rootReq["upload_time"] = CSmallDateTime::GetNow().ToTimeString().GetData();//2021-03-11 10:20:02
  551. rootReq["reason"] = errmsg.c_str();
  552. rootReq["remark"] = "";
  553. string jsonReq = writer.write(rootReq);
  554. updateFailReq.m_reqStr = jsonReq;//请求参数
  555. updateFailReq.m_url = m_fsm->m_centerUrl.addUploadFailUrl;//访问地址
  556. if(!client->Post(updateFailReq, updateFailRet)){
  557. Dbg("addUploadFail is fail, sysCode=%d , userCode = %s",updateFailRet.m_sysCode, updateFailRet.m_userCode.c_str());
  558. return false;
  559. }
  560. //解析报文
  561. //Dbg("updateFailRet=%s",updateFailRet.m_retStr.c_str());
  562. //解析回应报文
  563. Json::Reader reader;
  564. Json::Value rootRet;
  565. if (!reader.parse(updateFailRet.m_retStr, rootRet, false))
  566. {
  567. return false;//解析失败
  568. }
  569. bool isSucc = rootRet["success"].asBool();
  570. if(isSucc){
  571. if(rootRet.isMember("data")){
  572. if(rootRet["data"]["update_flag"].asBool()){
  573. return true;//登记成功
  574. }else{
  575. return false;//登记失败
  576. }
  577. }else{
  578. return false;//无data字段
  579. }
  580. }else{
  581. Dbg("addUploadFail [success] is false");
  582. return false;
  583. }
  584. }
  585. //上传后文件处理
  586. bool operateFile(string &errmsg){
  587. if(m_fsm->m_currUploadFile->after_deal_type=="D"){
  588. //Dbg("delete file %s",m_fsm->m_currUploadFile->fileName.c_str());
  589. #ifdef RVC_OS_WIN
  590. if(remove(m_fsm->m_currUploadFile->filePath.c_str())==0){
  591. Dbg("delete file is ok");
  592. return true;
  593. }else{
  594. Dbg("delete file is error, errno=%d",GetLastError());
  595. errmsg = CSimpleStringA::Format("delete file is error, errno=%d",GetLastError());
  596. return false;
  597. }
  598. #else
  599. if (changeFileAtt(m_fsm->m_currUploadFile->filePath.c_str()) == 0) {
  600. if (remove(m_fsm->m_currUploadFile->filePath.c_str()) == 0) {
  601. Dbg("delete file is ok, file =%s",m_fsm->m_currUploadFile->filePath.c_str());
  602. return true;
  603. }
  604. else {
  605. Dbg("delete file is error,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  606. errmsg = CSimpleStringA::Format("delete file is error, file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  607. return false;
  608. }
  609. }
  610. else {
  611. Dbg("delete file is error,changefileAtt fail,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  612. errmsg = CSimpleStringA::Format("delete file is error,changefileAtt fail,file =%s, errno=%d",m_fsm->m_currUploadFile->filePath.c_str(), errno);
  613. return false;
  614. }
  615. #endif
  616. }else if(m_fsm->m_currUploadFile->after_deal_type=="M"){
  617. string destPath="";
  618. string destDir="";
  619. //根据路径类型组成最后移动路径
  620. if(m_fsm->m_currUploadFile->path_type=="R"){
  621. #ifdef RVC_OS_WIN
  622. destPath = m_fsm->m_rootPath+"\\"+m_fsm->m_currUploadFile->after_deal_text+"\\"+m_fsm->m_currUploadFile->fileName;
  623. destDir = m_fsm->m_rootPath+"\\"+m_fsm->m_currUploadFile->after_deal_text;
  624. #else
  625. destPath = m_fsm->m_rootPath + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->after_deal_text + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->fileName;
  626. destDir = m_fsm->m_rootPath + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->after_deal_text;
  627. #endif
  628. }else{
  629. #ifdef RVC_OS_WIN
  630. destPath = m_fsm->m_currUploadFile->after_deal_text+"\\"+m_fsm->m_currUploadFile->fileName;
  631. #else
  632. destPath = m_fsm->m_currUploadFile->after_deal_text + SPLIT_SLASH_STR + m_fsm->m_currUploadFile->fileName;
  633. #endif
  634. destDir = m_fsm->m_currUploadFile->after_deal_text;
  635. }
  636. string srcPath = m_fsm->m_currUploadFile->filePath;
  637. //Dbg("move file %s to %s",srcPath.c_str(),destPath.c_str());
  638. //判断是否存在目标文件,如存在,则先删除
  639. #ifdef RVC_OS_WIN
  640. if(ExistsFileA(destPath.c_str())){
  641. if(remove(destPath.c_str())==0){
  642. Dbg("delete dest file is ok [%s]",destPath.c_str());
  643. }else{
  644. Dbg("delete dest file is error, errno=%d, [%s]",(int)GetLastError(),destPath.c_str());
  645. errmsg = CSimpleStringA::Format("delete dest file is error, errno=%d, [%s]",(int)GetLastError(),destPath.c_str());
  646. return false;
  647. }
  648. }
  649. //判断移动目标文件夹是否存在,不存在,则创建
  650. if(!ExistsDirA(destDir.c_str())){
  651. if(!CreateDirRecursiveA(destDir.c_str())){
  652. Dbg("create dest dir [%s] is error, errno=%d",destDir.c_str(),GetLastError());
  653. errmsg = CSimpleStringA::Format("create dest dir [%s] is error, errno=%d",destDir.c_str(),GetLastError());
  654. return false;
  655. }
  656. }
  657. //移动文件
  658. int i;
  659. int tries = 10;
  660. bool isSucc = false;
  661. for (i = 0; i < tries; ++i) {
  662. if(rename(srcPath.c_str(),destPath.c_str())==0){
  663. Dbg("move file ok! tries:%d, [%s] to [%s] ", i, srcPath.c_str(),destPath.c_str());
  664. isSucc = true;
  665. break;
  666. } else {
  667. Dbg("move file failed! errno:%d, [%s] to [%s] ", (int)GetLastError(), srcPath.c_str(),destPath.c_str());
  668. errmsg = CSimpleStringA::Format("move file failed! errno:%d, [%s] to [%s] ", (int)GetLastError(), srcPath.c_str(),destPath.c_str());
  669. Sleep(1000);
  670. }
  671. }
  672. return isSucc;
  673. #else
  674. if (ExistsFileA(destPath.c_str())) {
  675. if (changeFileAtt(destPath.c_str()) == 0) {
  676. if (remove(destPath.c_str()) == 0) {
  677. Dbg("delete dest file is ok [%s]",destPath.c_str());
  678. }
  679. else {
  680. Dbg("delete dest file is error, errno=%d, [%s]", errno, destPath.c_str());
  681. errmsg = CSimpleStringA::Format("delete src file is error, errno=%d, [%s]", errno, destPath.c_str());
  682. return false;
  683. }
  684. }
  685. else {
  686. Dbg("delete dest file is error,changefileAtt fail ,errno=%d , file=%s ", errno, destPath.c_str());
  687. errmsg = CSimpleStringA::Format("delete src file is error, changefileAtt fail, errno=%d, file=%s", errno, destPath.c_str());
  688. return false;
  689. }
  690. }
  691. //判断移动目标文件夹是否存在,不存在,则创建
  692. if (!ExistsDirA(destDir.c_str())) {
  693. if (!CreateDirRecursiveA(destDir.c_str())) {
  694. Dbg("create dest dir [%s] is error, errno=%d", destDir.c_str(), errno);
  695. errmsg = CSimpleStringA::Format("create dest dir [%s] is error, errno=%d", destDir.c_str(), errno);
  696. return false;
  697. }
  698. }
  699. //移动文件
  700. if (changeFileAtt(srcPath.c_str()) == 0)
  701. {
  702. int i;
  703. int tries = 10;
  704. bool isSucc = false;
  705. for (i = 0; i < tries; ++i) {
  706. //rename函数对于跨分支的目录存在拷贝不成功的情况,故采用先拷贝后删除的操作修复此bug
  707. if (fileutil_copy_file(destPath.c_str(), srcPath.c_str()) == 0) {
  708. if (remove(srcPath.c_str()) == 0) {
  709. //Dbg("move ok! tries:%d", i);
  710. Dbg("move file ok! tries:%d, [%s] to [%s] ", i, srcPath.c_str(),destPath.c_str());
  711. isSucc = true;
  712. break;
  713. }
  714. else {
  715. //Dbg("move %s -> %s failed! delete src file fail, errno:%d", srcPath.c_str(), destPath.c_str(), errno);
  716. Dbg("move file failed! errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  717. errmsg = CSimpleStringA::Format("move file failed! errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  718. Sleep(1000);
  719. }
  720. }
  721. else {
  722. //Dbg("move %s -> %s failed! copy src file fail, errno:%d", srcPath.c_str(), destPath.c_str(), errno);
  723. Dbg("move file failed! copy src file fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  724. errmsg = CSimpleStringA::Format("move file failed! copy src file fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  725. Sleep(1000);
  726. }
  727. }
  728. return isSucc;
  729. }
  730. else {
  731. //Dbg("move %s -> %s failed! , changefileAtt fail,errno=%d", srcPath.c_str(), destPath.c_str(), errno);
  732. Dbg("move file failed! changefileAtt fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  733. errmsg = CSimpleStringA::Format("move file failed! changefileAtt fail, errno:%d, [%s] to [%s] ", errno, srcPath.c_str(),destPath.c_str());
  734. return false;
  735. }
  736. #endif
  737. }else if(m_fsm->m_currUploadFile->after_deal_type=="N"){
  738. return true;
  739. }else{
  740. Dbg("file [%s] invalid after_deal_type=%s",m_fsm->m_currUploadFile->fileName.c_str(),m_fsm->m_currUploadFile->after_deal_type.c_str());
  741. errmsg = CSimpleStringA::Format("invalid after_deal_type=%s",m_fsm->m_currUploadFile->after_deal_type.c_str());
  742. return false;
  743. }
  744. }
  745. };
  746. }
  747. void UploadFSM::OnStateTrans( int iSrcState, int iDstState )
  748. {
  749. Dbg("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
  750. }
  751. void UploadFSM::OnSysVarEvent( const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName )
  752. {
  753. Dbg("rx sysvar %s from %s, %s to %s", pszKey, pszEntityName, pszOldValue, pszValue);
  754. if (pszValue[0] == 'O') {
  755. m_isOffLine = true;
  756. PostEventFIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  757. } else {
  758. m_isOffLine = false;
  759. PostEventFIFO(new FSMEvent(USER_EVT_JMP_DISABLE));
  760. }
  761. }
  762. ErrorCodeEnum UploadFSM::OnInit()
  763. {
  764. ErrorCodeEnum Error;
  765. /** 交易受限功能代码废弃
  766. Error = LoadServerConfigFromCenterSetting();
  767. if (Error != Error_Succeed)
  768. {
  769. LogWarn(Severity_High, Error, 0, "从集中配置读取配置信息失败");
  770. return Error;
  771. }
  772. */
  773. INIT_LIST_HEAD(&m_updir_list);
  774. /**交易受限功能代码废弃
  775. m_check_dir = new list<CSimpleStringA>();
  776. m_uploadDateList = new list<CSimpleStringA>();
  777. {
  778. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();;
  779. CSmartPointer<IConfigInfo> spConfig;
  780. Error = spFunction->OpenConfig(Config_Run, spConfig);
  781. if (Error == Error_Succeed) {
  782. CSimpleStringA dateList ="";
  783. Error = spConfig->ReadConfigValue("uploadDate", "dateList", dateList);
  784. bool bError= false;
  785. if(Error == Error_Succeed){
  786. CAutoArray<CSimpleStringA> dList = dateList.Split(',');
  787. for(int i=0; i<dList.GetCount(); i++){
  788. //当读入的日期大于10天,则不加载后续的日期,防止后续日期字符串太长
  789. if(i>=10){
  790. break;
  791. }
  792. CSimpleStringA strDate = dList[i];
  793. //判断日期长度,只读入正确的日期参数,防止读入文件是错误的参数
  794. if(strDate.GetLength()==10){
  795. m_uploadDateList->push_back(strDate);
  796. Dbg("upload.ini uploadDate/dateList is: %s ",strDate.GetData());
  797. }else{
  798. Dbg("upload.ini uploadDate/dateList param is error : %s ",strDate.GetData());
  799. bError=true;
  800. }
  801. }
  802. //重置错误的参数文件
  803. if(bError){
  804. if(SaveUploadDate()==Error_Succeed){
  805. Dbg("upload.ini param reset is Success!");
  806. }else{
  807. Dbg("upload.ini param reset is fail!");
  808. }
  809. }
  810. }else{
  811. Dbg("read upload.ini param uploadDate/dateList fail!");
  812. return Error;
  813. }
  814. }else{
  815. Dbg("open runcfg upload.ini fail, please check out upload.ini!");
  816. return Error;
  817. }
  818. }
  819. */
  820. CSimpleStringA checkStr="";
  821. CSmartPointer<IConfigInfo> spConfig;
  822. Error = m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  823. if(Error==Error_Succeed){
  824. //获取模式控制参数
  825. Error = spConfig->ReadConfigValueInt("upload", "CenterModel",m_centerModel);
  826. if (Error_Succeed != Error)
  827. {
  828. Dbg("get m_centerModel from CenterSetting.ini failed");
  829. return Error;
  830. }
  831. if(m_centerModel==(int)branchModel||m_centerModel==(int)mixModel){
  832. Dbg("model is branchModel or mixModel,CenterModel = %d",m_centerModel);
  833. CSmartPointer<IConfigInfo> spConfig_software;
  834. Error = m_pEntity->GetFunction()->OpenConfig(Config_Software, spConfig_software);
  835. Error = (ErrorCodeEnum)upload_create(&m_updir_list, m_pEntity->GetFunction().GetRawPointer(), spConfig_software.GetRawPointer(),checkStr);
  836. if (Error != Error_Succeed) {
  837. Dbg("load main config failed!");
  838. return Error;
  839. }else{
  840. /**交易受限功能代码废弃
  841. Dbg("checkdirStr is %s",checkStr.GetData());
  842. char *p, *c;
  843. char checkType_str[1024];
  844. strcpy(checkType_str, (LPCSTR)checkStr);
  845. p = strtok_s(checkType_str, ", ", &c);
  846. while (p) {
  847. CSimpleStringA str = p;
  848. m_check_dir->push_back(str);
  849. Dbg("checkdir is %s",str.GetData());
  850. p = strtok_s(NULL, ", ", &c);
  851. }
  852. */
  853. }
  854. }else if(m_centerModel==(int)centerModel){
  855. Dbg("model is centerModel, CenterModel = %d",m_centerModel);
  856. }else{
  857. Dbg("model is invalid ,CenterModel =%d",m_centerModel);
  858. return Error_Unexpect;
  859. }
  860. //增加总行接口Url参数
  861. CSimpleStringA str="";
  862. Error = spConfig->ReadConfigValue("upload", "QueryPlanUrl", str);
  863. if (Error == Error_Succeed)
  864. {
  865. Dbg("[CenterUrl] QueryPlanUrl =%s",str.GetData());
  866. m_centerUrl.queryPlanUrl = str.GetData();
  867. }
  868. else
  869. {
  870. return Error;
  871. }
  872. Error = spConfig->ReadConfigValue("upload", "QueryTempFileUrl", str);
  873. if (Error == Error_Succeed)
  874. {
  875. Dbg("[CenterUrl] QueryTempFileUrl =%s",str.GetData());
  876. m_centerUrl.queryTempFileUrl = str.GetData();
  877. }
  878. else
  879. {
  880. return Error;
  881. }
  882. Error = spConfig->ReadConfigValue("upload", "UpdateStateUrl", str);
  883. if (Error == Error_Succeed)
  884. {
  885. Dbg("[CenterUrl] UpdateStateUrl =%s",str.GetData());
  886. m_centerUrl.updateStateUrl = str.GetData();
  887. }
  888. else
  889. {
  890. return Error;
  891. }
  892. Error = spConfig->ReadConfigValue("upload", "AddUploadFailUrl", str);
  893. if (Error == Error_Succeed)
  894. {
  895. Dbg("[CenterUrl] AddUploadFailUrl =%s",str.GetData());
  896. m_centerUrl.addUploadFailUrl = str.GetData();
  897. }
  898. else
  899. {
  900. return Error;
  901. }
  902. Error = spConfig->ReadConfigValue("upload", "EachUploadLen", str);
  903. if (Error == Error_Succeed)
  904. {
  905. Dbg("[CenterUrl] EachUploadLen =%s",str.GetData());
  906. if(str.IsNullOrEmpty()){
  907. m_eachUploadLen = UPLOAD_CONTENT_EACH_LEN;
  908. }else{
  909. m_eachUploadLen = atoi(str.GetData())*1024;
  910. }
  911. }
  912. else
  913. {
  914. return Error;
  915. }
  916. int uploadMaxNum = 0;
  917. Error = spConfig->ReadConfigValueInt("upload", "UploadMaxNum", uploadMaxNum);
  918. if (Error == Error_Succeed)
  919. {
  920. Dbg("[CenterUrl] UploadMaxNum =%d",uploadMaxNum);
  921. if(uploadMaxNum<=10){
  922. m_uploadMaxNum = 1000;
  923. }else{
  924. m_uploadMaxNum = uploadMaxNum;
  925. }
  926. }
  927. else
  928. {
  929. return Error;
  930. }
  931. //Error = spConfig->ReadConfigValue("upload", "UploadCenterUrl", str);
  932. //if (Error == Error_Succeed)
  933. //{
  934. // Dbg("[CenterUrl] UploadCenterUrl =%s",str.GetData());
  935. // m_centerUrl.uploadCenterUrl = str.GetData();
  936. //}
  937. //else
  938. //{
  939. // return Error;
  940. //}
  941. //获取系统文件根路径
  942. CSimpleStringA runPath ;
  943. Error =this->GetEntityBase()->GetFunction()->GetPath("Root",runPath);//例如:C:\\Run /opt/Run
  944. if(Error_Succeed == Error){
  945. if(!runPath.IsNullOrEmpty()){
  946. string runPathStr = runPath.GetData();
  947. int pos = runPathStr.find_last_of(SPLIT_SLASH);//修改为路径分隔符
  948. m_rootPath = runPathStr.substr(0,pos);
  949. Dbg("get Root path is %s",m_rootPath.c_str());
  950. }else{
  951. Dbg("get Root path is null");
  952. return Error_Unexpect;
  953. }
  954. }else{
  955. Dbg("get Root path is error");
  956. return Error_Unexpect;
  957. }
  958. }else{
  959. return Error;
  960. }
  961. /**交易受限功能代码废弃
  962. //初始化临界区
  963. InitializeCriticalSection(&m_cs);
  964. m_dBeginTime=0;
  965. m_dEndTime=0;
  966. m_iSpeed=0;
  967. */
  968. Error = m_pEntity->GetFunction()->RegistSysVarEvent("CallState", this);
  969. if (Error == Error_Succeed) {
  970. AddStateHooker(this);
  971. }
  972. //......
  973. return Error;
  974. }
  975. ErrorCodeEnum UploadFSM::OnExit()
  976. {
  977. //释放临界区
  978. /**交易受限功能代码废弃
  979. DeleteCriticalSection(&m_cs);
  980. m_uploadDateList->clear();
  981. */
  982. m_pEntity->GetFunction()->UnregistSysVarEvent("CallState");
  983. return Error_Succeed;
  984. }
  985. void UploadFSM::s0_on_entry()
  986. {
  987. CSimpleStringA strValue;
  988. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetSysVar("CallState", strValue);
  989. if (Error == Error_Succeed) {
  990. if (strValue[0] == 'O') { // only upload when CallState in offline state
  991. PostEventFIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  992. } else {
  993. PostEventLIFO(new FSMEvent(USER_EVT_JMP_DISABLE));
  994. }
  995. }
  996. }
  997. void UploadFSM::s0_on_exit()
  998. {
  999. }
  1000. unsigned int UploadFSM::s0_on_event( FSMEvent* event )
  1001. {
  1002. return 0;
  1003. }
  1004. void UploadFSM::s1_on_entry()
  1005. {
  1006. ScheduleTimer(8, 30000);
  1007. }
  1008. void UploadFSM::s1_on_exit()
  1009. {
  1010. CancelTimer(8);
  1011. }
  1012. unsigned int UploadFSM::s1_on_event(FSMEvent* event)
  1013. {
  1014. if (event->iEvt == EVT_TIMER) {
  1015. if(m_isOffLine){
  1016. PostEventLIFO(new FSMEvent(USER_EVT_JMP_ENABLE));
  1017. }else{
  1018. ScheduleTimer(8, 30000);//继续等待
  1019. }
  1020. }
  1021. return 0;
  1022. }
  1023. void UploadFSM::s2_on_entry()
  1024. {
  1025. m_uploadModel = false;//默认是分行上传模式
  1026. //清理上次扫描文件列表,扫描计划,分行ip列表
  1027. if(m_uploadList!=NULL){
  1028. list<UploadFileInfo*>::iterator iter ;
  1029. for(iter=m_uploadList->begin();iter!=m_uploadList->end();++iter){
  1030. delete *iter;
  1031. }
  1032. m_uploadList->clear();
  1033. }
  1034. if(m_uploadPlanList!=NULL){
  1035. list<UploadPlan*>::iterator iter ;
  1036. for(iter=m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  1037. delete *iter;
  1038. }
  1039. m_uploadPlanList->clear();
  1040. }
  1041. m_branchIpList.clear();
  1042. while(true){
  1043. file_t* f = find_first_upload_file();
  1044. if (f == NULL) {
  1045. break;//链表为空
  1046. }else{
  1047. updir_del_file(f);//销毁对象
  1048. }
  1049. }
  1050. //上传模式确定
  1051. if(m_centerModel==(int)branchModel){
  1052. //Dbg("branchModel");
  1053. m_uploadModel = false;//旧模式
  1054. }else if(m_centerModel == (int)centerModel){
  1055. //Dbg("centerModel");
  1056. //防止url无效,新模式直接停止上传 等待下一次
  1057. if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
  1058. m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
  1059. Dbg("centerModel mode ,centerUrl is null , wait for next time");
  1060. ScheduleTimer(1, 120000);
  1061. return ;
  1062. }
  1063. //新模式,查询策略
  1064. if(queryPlan()){
  1065. m_uploadModel = true;
  1066. }else{
  1067. //查询策略失败,等待下一次
  1068. Dbg("queryPlan is fail , wait for next time");
  1069. ScheduleTimer(1, 120000);
  1070. return ;
  1071. }
  1072. }else if(m_centerModel == (int)mixModel){
  1073. //Dbg("mixModel");
  1074. m_uploadModel = queryPlan();//新旧模式 查询策略进一步判断采用何种模式
  1075. //防止url无效,url依然走旧模式
  1076. if(m_uploadModel){
  1077. if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
  1078. m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
  1079. //走旧模式
  1080. Dbg("mixModel mode ,centerUrl is null ,exec old model");
  1081. m_uploadModel=false;
  1082. }
  1083. }
  1084. }else{
  1085. Dbg("m_centerModel is invalid");
  1086. ScheduleTimer(1, 120000);
  1087. return;
  1088. }
  1089. if(m_uploadModel){
  1090. //新模式扫描
  1091. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_SCAN));
  1092. }else{
  1093. //旧模式扫描
  1094. PostEventLIFO(new FSMEvent(USER_EVT_JMP_OLD_SCAN));
  1095. //旧模式扫描
  1096. /**
  1097. if (find_first_upload_file() == NULL) {
  1098. upload_fresh(&m_updir_list);
  1099. }
  1100. if (find_first_upload_file() == NULL) {
  1101. ScheduleTimer(1, 120000);
  1102. } else {
  1103. //把新增加的上传日期加入集合里面
  1104. //insertUploadDate();
  1105. PostEventLIFO(new FSMEvent(USER_EVT_JMP_CONNECT));
  1106. }
  1107. */
  1108. }
  1109. }
  1110. void UploadFSM::s2_on_exit()
  1111. {
  1112. CancelTimer(1);
  1113. }
  1114. unsigned int UploadFSM::s2_on_event(FSMEvent* event)
  1115. {
  1116. if (event->iEvt == EVT_TIMER) {
  1117. /**
  1118. if (find_first_upload_file() == NULL) {
  1119. upload_fresh(&m_updir_list);
  1120. }
  1121. if (find_first_upload_file() == NULL) {
  1122. ScheduleTimer(1, 120000);
  1123. } else {
  1124. //把新增加的上传日期加入集合里面
  1125. //交易受限功能代码废弃
  1126. //insertUploadDate();
  1127. PostEventLIFO(new FSMEvent(USER_EVT_JMP_CONNECT));
  1128. }
  1129. */
  1130. m_uploadModel = false;//默认是分行上传模式
  1131. //清理上次扫描文件列表,扫描计划,分行ip列表
  1132. if(m_uploadList!=NULL){
  1133. list<UploadFileInfo*>::iterator iter ;
  1134. for(iter=m_uploadList->begin();iter!=m_uploadList->end();++iter){
  1135. delete *iter;
  1136. }
  1137. m_uploadList->clear();
  1138. }
  1139. if(m_uploadPlanList!=NULL){
  1140. list<UploadPlan*>::iterator iter ;
  1141. for(iter=m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  1142. delete *iter;
  1143. }
  1144. m_uploadPlanList->clear();
  1145. }
  1146. m_branchIpList.clear();
  1147. while(true){
  1148. file_t* f = find_first_upload_file();
  1149. if (f == NULL) {
  1150. break;//链表为空
  1151. }else{
  1152. updir_del_file(f);//销毁对象
  1153. }
  1154. }
  1155. //上传模式确定
  1156. if(m_centerModel==(int)branchModel){
  1157. //旧模式
  1158. Dbg("branchModel");
  1159. m_uploadModel = false;
  1160. }else if(m_centerModel == (int)centerModel){
  1161. Dbg("centerModel");
  1162. //防止url无效,新模式直接停止上传,等待下一次
  1163. if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
  1164. m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
  1165. Dbg("centerModel mode ,centerUrl is null , wait for next time");
  1166. ScheduleTimer(1, 240000);
  1167. return 0;
  1168. }
  1169. //新模式,查询策略
  1170. if(queryPlan()){
  1171. m_uploadModel = true;
  1172. }else{
  1173. //查询策略失败,等待下一次
  1174. Dbg("queryPlan is fail , wait for next time");
  1175. ScheduleTimer(1, 240000);
  1176. return 0;
  1177. }
  1178. }else if(m_centerModel == (int)mixModel){
  1179. Dbg("mixModel");
  1180. //新旧模式 查询策略进一步判断采用何种模式
  1181. m_uploadModel = queryPlan();
  1182. //防止url无效,url依然走旧模式
  1183. if(m_uploadModel){
  1184. if(m_centerUrl.addUploadFailUrl.empty()||m_centerUrl.queryPlanUrl.empty()||
  1185. m_centerUrl.queryTempFileUrl.empty()||m_centerUrl.updateStateUrl.empty()){
  1186. //走旧模式
  1187. Dbg("mixModel mode ,centerUrl is null ,exec old model");
  1188. m_uploadModel=false;
  1189. }
  1190. }
  1191. }else{
  1192. Dbg("m_centerModel is invalid");
  1193. ScheduleTimer(1, 240000);
  1194. return 0;
  1195. }
  1196. if(m_uploadModel){
  1197. //新模式扫描
  1198. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_SCAN));
  1199. }else{
  1200. //旧模式扫描
  1201. PostEventLIFO(new FSMEvent(USER_EVT_JMP_OLD_SCAN));
  1202. }
  1203. }else if (event->iEvt == USER_EVT_JMP_OLD_SCAN) {
  1204. Dbg("enter old model upload");
  1205. //旧模式
  1206. if (find_first_upload_file() == NULL) {
  1207. upload_fresh(&m_updir_list);
  1208. }
  1209. if (find_first_upload_file() == NULL) {
  1210. Dbg("find_first_upload_file is 0,wait for 4 min retry scan");
  1211. ScheduleTimer(1, 240000);
  1212. } else {
  1213. PostEventLIFO(new FSMEvent(USER_EVT_JMP_CONNECT));
  1214. }
  1215. }else if (event->iEvt == USER_EVT_JMP_NEW_SCAN) {
  1216. Dbg("enter new model upload");
  1217. //新模式
  1218. if (m_uploadList->size() == 0) {
  1219. //重新扫描文件
  1220. scanFile();
  1221. }
  1222. if (m_uploadList->size() == 0) {
  1223. Dbg("m_uploadList is 0,wait for 8 min retry scan");
  1224. ScheduleTimer(1, 480000);
  1225. } else {
  1226. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_UPLOAD));//跳到新的上传状态
  1227. }
  1228. }
  1229. return 0;
  1230. }
  1231. void UploadFSM::s3_on_entry()
  1232. {
  1233. if (!m_pConnection) {
  1234. m_pConnection = new UploadConnection(m_pEntity, this);
  1235. //if (!m_pConnection->Connect(m_server1, m_server1_port, 3)) {
  1236. // m_pConnection->Close();
  1237. // m_pConnection->DecRefCount();
  1238. // m_pConnection = NULL;
  1239. // if((m_server2!=NULL)&&(m_server2_port!=0)&&((m_server2 != m_server1) || (m_server2_port != m_server1_port)))
  1240. // {
  1241. // m_pConnection = new UploadConnection(m_pEntity, this);
  1242. // if (!m_pConnection->Connect(m_server2, m_server2_port, 3)) {
  1243. // m_pConnection->Close();
  1244. // m_pConnection->DecRefCount();
  1245. // m_pConnection = NULL;
  1246. // }
  1247. // }
  1248. //}
  1249. if(m_pConnection->ConnectFromCentralSetting() && m_pConnection->IsConnectionOK()){
  1250. //创建成功
  1251. }else{
  1252. m_pConnection->Close();
  1253. m_pConnection->DecRefCount();
  1254. m_pConnection = NULL;
  1255. }
  1256. }
  1257. if (!m_pConnection)
  1258. {
  1259. ScheduleTimer(2, 30000); // try 30 seconds later
  1260. }
  1261. else
  1262. {
  1263. PostEventLIFO(new FSMEvent(USER_EVT_JMP_UPLOAD));
  1264. }
  1265. }
  1266. void UploadFSM::s3_on_exit()
  1267. {
  1268. CancelTimer(2);
  1269. }
  1270. unsigned int UploadFSM::s3_on_event(FSMEvent* event)
  1271. {
  1272. if (event->iEvt == EVT_TIMER) {
  1273. m_pConnection = new UploadConnection(m_pEntity, this);
  1274. /*if (!m_pConnection->Connect(m_server1, m_server1_port, 3))
  1275. {
  1276. m_pConnection->Close();
  1277. m_pConnection->DecRefCount();
  1278. m_pConnection = NULL;
  1279. if((m_server2!=NULL)&&(m_server2_port!=0)&&((m_server2 != m_server1) || (m_server2_port != m_server1_port)))
  1280. {
  1281. m_pConnection = new UploadConnection(m_pEntity, this);
  1282. if (!m_pConnection->Connect(m_server2, m_server2_port, 3))
  1283. {
  1284. m_pConnection->Close();
  1285. m_pConnection->DecRefCount();
  1286. m_pConnection = NULL;
  1287. }
  1288. }
  1289. }*/
  1290. if(m_pConnection->ConnectFromCentralSetting()&&m_pConnection->IsConnectionOK()){
  1291. //创建成功
  1292. }else{
  1293. m_pConnection->Close();
  1294. m_pConnection->DecRefCount();
  1295. m_pConnection = NULL;
  1296. }
  1297. if (!m_pConnection)
  1298. {
  1299. ScheduleTimer(2, 30000); // try 30 seconds later
  1300. }
  1301. else {
  1302. PostEventLIFO(new FSMEvent(USER_EVT_JMP_UPLOAD));
  1303. }
  1304. }
  1305. return 0;
  1306. }
  1307. void UploadFSM::s4_on_entry()
  1308. {
  1309. m_uploading_file = find_first_upload_file();//获取要处理的文件
  1310. #ifdef RVC_OS_WIN
  1311. m_uploading_handle = INVALID_HANDLE_VALUE;//文件句柄
  1312. #else
  1313. m_uploading_handle = NULL;
  1314. #endif // RVC_OS_WIN
  1315. //开始统计时间
  1316. /**交易受限功能代码废弃
  1317. //m_dBeginTime=GetTickCount();//开始时间
  1318. */
  1319. //Dbg("m_dBeginTime:%d",m_dBeginTime);
  1320. m_pConnection->SendUpReq(m_uploading_file);//发送上传请求
  1321. ScheduleTimer(4,30000);
  1322. }
  1323. void UploadFSM::s4_on_exit()
  1324. {
  1325. /**交易受限功能代码废弃
  1326. m_dBeginTime=0;
  1327. m_dEndTime=0;
  1328. m_iSpeed=0;
  1329. */
  1330. #ifdef RVC_OS_WIN
  1331. if (m_uploading_handle != INVALID_HANDLE_VALUE) {
  1332. CloseHandle(m_uploading_handle);
  1333. m_uploading_handle = INVALID_HANDLE_VALUE;
  1334. }
  1335. #else
  1336. if (m_uploading_handle != NULL) {
  1337. fclose(m_uploading_handle);
  1338. m_uploading_handle = NULL;
  1339. }
  1340. #endif // RVC_OS_WIN
  1341. m_uploading_file = NULL;
  1342. CancelTimer(4);
  1343. }
  1344. unsigned int UploadFSM::s4_on_event(FSMEvent* event)
  1345. {
  1346. CancelTimer(4);
  1347. if (event->iEvt == USER_EVT_UPLOAD_ANS)
  1348. { // .....
  1349. UploadAnsEvent *ans = (UploadAnsEvent *)event;
  1350. if (ans->m_reply.ResultCode == UploadCtlCode::Begin || ans->m_reply.ResultCode == UploadCtlCode::Continua)
  1351. {
  1352. m_uploading_block_id = ans->m_reply.BeginBlock;
  1353. #ifdef RVC_OS_WIN
  1354. m_uploading_handle = CreateFileA(m_uploading_file->path, GENERIC_READ,
  1355. FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  1356. if (m_uploading_handle == INVALID_HANDLE_VALUE)
  1357. { // open file handle failed, we ignore this file
  1358. //list_del(&m_uploading_file->entry);//从链表删除文件
  1359. //upload_file_destroy(m_uploading_file);//销毁文件
  1360. DWORD err = GetLastError();
  1361. Dbg("USER_EVT_UPLOAD_ANS CreateFileA is error file name [%s] , GetLastError = %d", m_uploading_file->name, err);
  1362. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1363. m_pConnection->Close();
  1364. m_pConnection->DecRefCount();
  1365. m_pConnection = NULL;
  1366. return 1; // goto s5
  1367. }
  1368. else
  1369. {
  1370. memcpy(m_upload_id, ans->m_reply.UploadID, sizeof(m_upload_id));
  1371. //当发送不成功,则把文件从列表删除,进行下一个文件传送
  1372. if (!m_pConnection->SendBlockReq(m_uploading_file, m_uploading_handle, m_upload_id, m_uploading_block_id)) {
  1373. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1374. m_pConnection->Close();
  1375. m_pConnection->DecRefCount();
  1376. m_pConnection = NULL;
  1377. return 1; // goto s5
  1378. }
  1379. }
  1380. #else
  1381. m_uploading_handle = fopen(m_uploading_file->path, "rb");
  1382. if (m_uploading_handle == NULL)
  1383. {
  1384. Dbg("USER_EVT_UPLOAD_ANS fopen is error file name [%s] ", m_uploading_file->name);
  1385. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1386. m_pConnection->Close();
  1387. m_pConnection->DecRefCount();
  1388. m_pConnection = NULL;
  1389. return 1; // goto s5
  1390. }
  1391. else
  1392. {
  1393. memcpy(m_upload_id, ans->m_reply.UploadID, sizeof(m_upload_id));
  1394. //当发送不成功,则把文件从列表删除,进行下一个文件传送
  1395. if (!m_pConnection->SendBlockReq(m_uploading_file, m_uploading_handle, m_upload_id, m_uploading_block_id)) {
  1396. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1397. m_pConnection->Close();
  1398. m_pConnection->DecRefCount();
  1399. m_pConnection = NULL;
  1400. return 1; // goto s5
  1401. }
  1402. }
  1403. #endif // RVC_OS_WIN
  1404. }
  1405. else if (ans->m_reply.ResultCode == UploadCtlCode::Timeout)
  1406. { //文件是否过期,不用再上传,现有配置是日志文件31天过期,受分行服务配置文件控制
  1407. post_process();//后续本地处理此文件
  1408. m_uploading_file = find_first_upload_file();//获取下一个文件
  1409. if (m_uploading_file)
  1410. {
  1411. m_pConnection->SendUpReq(m_uploading_file);//发送上传文件指令
  1412. }
  1413. else
  1414. {
  1415. m_pConnection->Close();
  1416. m_pConnection->DecRefCount();
  1417. m_pConnection = NULL;
  1418. return 1; // goto s5
  1419. }
  1420. }
  1421. else
  1422. {//(会有ErrorType错误)不做任务任何处理,仅仅把要处理的文件从列表移除
  1423. //list_del(&m_uploading_file->entry);
  1424. //upload_file_destroy(m_uploading_file);
  1425. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1426. m_pConnection->Close();
  1427. m_pConnection->DecRefCount();
  1428. m_pConnection = NULL;
  1429. return 1; // goto s5
  1430. }
  1431. }
  1432. else if (event->iEvt == USER_EVT_BLOCK_ANS)
  1433. {
  1434. BlockAnsEvent *ans = (BlockAnsEvent*)event;
  1435. if (ans->m_reply.ResultCode == UploadCtlCode::Continua)
  1436. {
  1437. /**交易受限功能代码废弃
  1438. m_dEndTime = GetTickCount();
  1439. if(m_dEndTime-m_dBeginTime!=0){
  1440. m_iSpeed = 1000*32/(m_dEndTime-m_dBeginTime);
  1441. }else{
  1442. }
  1443. m_dBeginTime = GetTickCount();
  1444. */
  1445. m_uploading_block_id++;
  1446. //当发送不成功,则把文件从列表删除,进行下一个文件传送
  1447. if(!m_pConnection->SendBlockReq(m_uploading_file, m_uploading_handle, m_upload_id, m_uploading_block_id)){
  1448. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1449. m_pConnection->Close();
  1450. m_pConnection->DecRefCount();
  1451. m_pConnection = NULL;
  1452. return 1; // goto s5
  1453. }
  1454. }
  1455. else if (ans->m_reply.ResultCode == UploadCtlCode::ErrorBlock)
  1456. { //不做任务任何处理,仅仅把要处理的文件从列表移除
  1457. Dbg("rx error block reply, resend!");
  1458. //m_uploading_block_id = ans->m_reply.
  1459. //m_pConnection->SendBlockReq(m_uploading_file, m_uploading_handle, m_upload_id, m_uploading_block_id);
  1460. //list_del(&m_uploading_file->entry);
  1461. //upload_file_destroy(m_uploading_file);
  1462. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1463. m_pConnection->Close();
  1464. m_pConnection->DecRefCount();
  1465. m_pConnection = NULL;
  1466. return 1; // goto s5
  1467. }
  1468. else if (ans->m_reply.ResultCode == UploadCtlCode::Begin)
  1469. { //重新传文件
  1470. m_uploading_block_id = 0; // upload again
  1471. if(!m_pConnection->SendBlockReq(m_uploading_file, m_uploading_handle, m_upload_id, m_uploading_block_id)){
  1472. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1473. m_pConnection->Close();
  1474. m_pConnection->DecRefCount();
  1475. m_pConnection = NULL;
  1476. return 1; // goto s5
  1477. }
  1478. }
  1479. else if (ans->m_reply.ResultCode == UploadCtlCode::ErrorType)
  1480. { // (不存在)server do not support this//不做任务任何处理,仅仅把要处理的文件从列表移除
  1481. Dbg("server do not support this type!");
  1482. //list_del(&m_uploading_file->entry);
  1483. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1484. m_pConnection->Close();
  1485. m_pConnection->DecRefCount();
  1486. m_pConnection = NULL;
  1487. //upload_file_destroy(m_uploading_file);
  1488. //m_uploading_file = NULL;
  1489. //CloseHandle(m_uploading_handle);
  1490. //m_uploading_handle = INVALID_HANDLE_VALUE;
  1491. return 1;
  1492. }
  1493. else if (ans->m_reply.ResultCode == UploadCtlCode::ErrorUploadId)
  1494. { //(概率很小)不做任务任何处理,仅仅把要处理的文件从列表移除
  1495. Dbg("server do not support this type!");
  1496. //list_del(&m_uploading_file->entry);
  1497. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1498. m_pConnection->Close();
  1499. m_pConnection->DecRefCount();
  1500. m_pConnection = NULL;
  1501. //upload_file_destroy(m_uploading_file);
  1502. //m_uploading_file = NULL;
  1503. //CloseHandle(m_uploading_handle);
  1504. //m_uploading_handle = INVALID_HANDLE_VALUE;
  1505. return 1;
  1506. }
  1507. else if (ans->m_reply.ResultCode == UploadCtlCode::Finish)
  1508. { //后续本地处理此文件
  1509. /**交易受限功能代码废弃
  1510. m_dEndTime = GetTickCount();
  1511. if(m_dEndTime-m_dBeginTime!=0){
  1512. m_iSpeed = 1000*32/(m_dEndTime-m_dBeginTime);
  1513. }else{
  1514. }
  1515. m_dBeginTime = GetTickCount();
  1516. */
  1517. post_process();
  1518. m_uploading_file = find_first_upload_file();
  1519. if (m_uploading_file)
  1520. {
  1521. m_pConnection->SendUpReq(m_uploading_file);
  1522. }
  1523. else
  1524. {
  1525. m_pConnection->Close();
  1526. m_pConnection->DecRefCount();
  1527. m_pConnection = NULL;
  1528. return 1; // goto s5
  1529. }
  1530. }
  1531. else
  1532. { //不做任务任何处理,仅仅把要处理的文件从列表移除
  1533. Dbg("server do not support this file! ResultCode:%d", ans->m_reply.ResultCode);
  1534. //list_del(&m_uploading_file->entry);
  1535. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1536. m_pConnection->Close();
  1537. m_pConnection->DecRefCount();
  1538. m_pConnection = NULL;
  1539. //upload_file_destroy(m_uploading_file);
  1540. //m_uploading_file = NULL;
  1541. //CloseHandle(m_uploading_handle);
  1542. //m_uploading_handle = INVALID_HANDLE_VALUE;
  1543. return 1; // goto s5
  1544. }
  1545. }
  1546. else if (event->iEvt == USER_EVT_DISCONNECT)
  1547. { // server disconnected
  1548. m_pConnection->Close();
  1549. m_pConnection->DecRefCount();
  1550. m_pConnection = NULL;
  1551. return 1; // goto s6
  1552. }
  1553. else if (event->iEvt == USER_EVT_JMP_DISABLE)
  1554. { // aborted any way
  1555. m_pConnection->Close();
  1556. m_pConnection->DecRefCount();
  1557. m_pConnection = NULL;
  1558. }
  1559. else if (event->iEvt == EVT_TIMER)
  1560. {
  1561. Dbg("SendUpReq timeout!!!");
  1562. }
  1563. return 0;
  1564. }
  1565. void UploadFSM::s5_on_entry()
  1566. {
  1567. ScheduleTimer(5, 1000); // sleep for a short to collect OnClose and OnDisconnect event
  1568. }
  1569. void UploadFSM::s5_on_exit()
  1570. {
  1571. CancelTimer(5);
  1572. }
  1573. unsigned int UploadFSM::s5_on_event(FSMEvent* event)
  1574. {
  1575. if (event->iEvt == USER_EVT_DISCONNECT) {
  1576. Dbg("rx disconnect evt at s5");
  1577. // goto s2
  1578. } else if (event->iEvt == EVT_TIMER) {
  1579. // goto s2
  1580. }
  1581. return 0;
  1582. }
  1583. void UploadFSM::s6_on_entry()
  1584. {
  1585. ScheduleTimer(6, 30000);
  1586. }
  1587. void UploadFSM::s6_on_exit()
  1588. {
  1589. CancelTimer(6);
  1590. }
  1591. unsigned int UploadFSM::s6_on_event(FSMEvent* event)
  1592. {
  1593. if (event->iEvt == EVT_TIMER) {
  1594. // goto s2
  1595. Dbg("disconnect sleeping 30s");
  1596. }
  1597. return 0;
  1598. }
  1599. void UploadFSM::s7_on_entry()
  1600. {
  1601. //新上传模式
  1602. m_uploadReport.sum = m_uploadList->size();
  1603. m_uploadReport.succ = 0;
  1604. m_uploadReport.fail = 0;
  1605. m_uploadReport.uploadFail = 0;
  1606. m_uploadReport.updateState = 0;
  1607. m_uploadReport.decodeFail = 0;
  1608. m_uploadReport.operateFileFail= 0;
  1609. m_uploadReport.queryTempFail =0;
  1610. m_uploadReport.isBreak =false;
  1611. //获取一个新文件,发送上传请求线程
  1612. if(m_uploadList->size()>0){
  1613. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1614. m_uploadList->pop_front();//去除首元素
  1615. Task::SendFileTask* task = new Task::SendFileTask(this);
  1616. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1617. if (rc != Error_Succeed)
  1618. {
  1619. if(m_currUploadFile!=NULL){
  1620. delete m_currUploadFile;
  1621. m_currUploadFile=NULL;
  1622. }
  1623. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 30s retry");
  1624. ScheduleTimer(7, 30000);
  1625. }
  1626. }
  1627. }
  1628. void UploadFSM::s7_on_exit()
  1629. {
  1630. if(m_currUploadFile!=NULL){
  1631. delete m_currUploadFile;
  1632. m_currUploadFile=NULL;
  1633. }
  1634. CancelTimer(7);
  1635. }
  1636. unsigned int UploadFSM::s7_on_event(FSMEvent* event)
  1637. {
  1638. if (event->iEvt == USER_EVT_UPLOAD_SUCC) {
  1639. m_uploadReport.succ++;//成功计数
  1640. //获取新的上传文件,发送上传请求线程
  1641. //判断是否已经需要退出
  1642. //无文件,跳出此状态
  1643. if(m_isOffLine){
  1644. if(m_uploadList->size()>0){
  1645. if(m_currUploadFile!=NULL){
  1646. delete m_currUploadFile;
  1647. m_currUploadFile=NULL;
  1648. }
  1649. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1650. m_uploadList->pop_front();//去除首元素
  1651. Task::SendFileTask* task = new Task::SendFileTask(this);
  1652. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1653. if (rc != Error_Succeed)
  1654. {
  1655. if(m_currUploadFile!=NULL){
  1656. delete m_currUploadFile;
  1657. m_currUploadFile=NULL;
  1658. }
  1659. m_uploadReport.isBreak =true;
  1660. reportBatchMsg();
  1661. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 240s retry scan");
  1662. ScheduleTimer(7, 240000);
  1663. }
  1664. }else{
  1665. m_uploadReport.isBreak =false;
  1666. reportBatchMsg();
  1667. Dbg("NewUpload m_uploadList is empty,wait 240s retry scan");
  1668. ScheduleTimer(7, 240000);// goto s2
  1669. }
  1670. }else{
  1671. m_uploadReport.isBreak =true;
  1672. reportBatchMsg();
  1673. Dbg("NewUpload m_isOffLine is false,jump s1");
  1674. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_DISABLE));// goto s1
  1675. }
  1676. }else if (event->iEvt == USER_EVT_UPLOAD_FAIL) {
  1677. m_uploadReport.fail++;//失败计数
  1678. //获取新的上传文件,发送上传请求线程
  1679. //判断是否已经需要退出
  1680. //无文件,跳出此状态
  1681. if(m_isOffLine){
  1682. Sleep(3000);//上传失败,等待5秒再下一个
  1683. if(m_uploadList->size()>0){
  1684. if(m_currUploadFile!=NULL){
  1685. delete m_currUploadFile;
  1686. m_currUploadFile=NULL;
  1687. }
  1688. m_currUploadFile = *(m_uploadList->begin());//首元素赋值给全局变量
  1689. m_uploadList->pop_front();//去除首元素
  1690. Task::SendFileTask* task = new Task::SendFileTask(this);
  1691. ErrorCodeEnum rc = this->GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  1692. if (rc != Error_Succeed)
  1693. {
  1694. if(m_currUploadFile!=NULL){
  1695. delete m_currUploadFile;
  1696. m_currUploadFile=NULL;
  1697. }
  1698. m_uploadReport.isBreak =true;
  1699. reportBatchMsg();
  1700. LogError(Severity_Middle, rc, 0, "Post SendFileTask task to Thread is fail,wait 240s retry scan");
  1701. ScheduleTimer(7, 240000);
  1702. }
  1703. }else{
  1704. m_uploadReport.isBreak =false;
  1705. reportBatchMsg();
  1706. Dbg("NewUpload m_uploadList is empty,wait 240s retry scan");
  1707. ScheduleTimer(7, 240000);// goto s2
  1708. }
  1709. }else{
  1710. m_uploadReport.isBreak =true;
  1711. reportBatchMsg();
  1712. Dbg("NewUpload m_isOffLine is false,jump s1");
  1713. PostEventLIFO(new FSMEvent(USER_EVT_JMP_NEW_DISABLE));// goto s1
  1714. }
  1715. }else if (event->iEvt == EVT_TIMER) {
  1716. // goto s2
  1717. Dbg("NewUpload ,jump to s2");
  1718. }
  1719. return 0;
  1720. }
  1721. /** 交易受限功能代码废弃
  1722. static ErrorCodeEnum ParseIPAddress( const char *str, CSimpleStringA &ip, int &port )
  1723. {
  1724. ErrorCodeEnum Error = Error_Unexpect;
  1725. if (str) {
  1726. char tmp1[32] = {};
  1727. char tmp2[16] = {};
  1728. sscanf(str, "%s %s", tmp1, tmp2);
  1729. if (tmp1[0] != 0 && tmp2[0] != 0)
  1730. {
  1731. ip = tmp1;
  1732. port = atoi(tmp2);
  1733. Error = Error_Succeed;
  1734. }
  1735. else
  1736. return Error;
  1737. }
  1738. return Error;
  1739. }
  1740. ErrorCodeEnum UploadFSM::LoadServerConfigFromCenterSetting()
  1741. {
  1742. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();
  1743. CSmartPointer<IConfigInfo> spConfig;
  1744. ErrorCodeEnum Error = spFunction->OpenConfig(Config_CenterSetting, spConfig);
  1745. if (Error == Error_Succeed) {
  1746. CSimpleStringA str;
  1747. Error = spConfig->ReadConfigValue("Upload", "Server", str);
  1748. if (Error == Error_Succeed)
  1749. {
  1750. Error = ParseIPAddress(str, m_server1, m_server1_port);
  1751. }
  1752. if (Error == Error_Succeed)
  1753. {
  1754. ErrorCodeEnum ErrorCode;
  1755. ErrorCode = spConfig->ReadConfigValue("Upload", "Server_Backup", str);
  1756. if (ErrorCode == Error_Succeed)
  1757. {
  1758. ErrorCode = ParseIPAddress(str, m_server2, m_server2_port);
  1759. }
  1760. if (ErrorCode!= Error_Succeed)
  1761. {
  1762. m_server2 = NULL;
  1763. m_server2_port = 0;
  1764. }
  1765. }
  1766. }
  1767. return Error;
  1768. }
  1769. */
  1770. file_t * UploadFSM::find_first_upload_file()
  1771. {
  1772. upload_dir_t *pos;
  1773. list_for_each_entry(pos, &m_updir_list, upload_dir_t, entry) {
  1774. if (!list_empty(&pos->candidate_list)) {
  1775. return list_first_entry(&pos->candidate_list, file_t, entry);
  1776. }
  1777. }
  1778. return NULL;
  1779. }
  1780. void UploadFSM::post_process()
  1781. {
  1782. int flags = m_uploading_file->owner->flags;
  1783. if (flags & UPLOAD_FLAG_AUTODELETE)
  1784. {
  1785. Dbg("delete file %s", m_uploading_file->name);
  1786. #ifdef RVC_OS_WIN
  1787. if (m_uploading_handle != INVALID_HANDLE_VALUE)
  1788. {
  1789. CloseHandle(m_uploading_handle);
  1790. m_uploading_handle = INVALID_HANDLE_VALUE;
  1791. }
  1792. DWORD dwAttr = GetFileAttributesA(m_uploading_file->path);
  1793. dwAttr &= ~FILE_ATTRIBUTE_READONLY;//去除只读属性
  1794. SetFileAttributesA(m_uploading_file->path, dwAttr);
  1795. if (DeleteFileA(m_uploading_file->path)) {
  1796. Dbg("delete file is ok");
  1797. }
  1798. else {
  1799. DWORD err = GetLastError();
  1800. Dbg("delete file is error , GetLastError = %d", err);
  1801. }
  1802. #else
  1803. if (m_uploading_handle != NULL) {
  1804. fclose(m_uploading_handle);
  1805. m_uploading_handle = NULL;
  1806. }
  1807. if (changeFileAtt(m_uploading_file->path)==0) {
  1808. if (remove(m_uploading_file->path) == 0) {
  1809. Dbg("delete file is ok");
  1810. }
  1811. else {
  1812. Dbg("delete file is error,errno=%d , file=%s", errno, m_uploading_file->path);
  1813. }
  1814. }
  1815. else {
  1816. Dbg("delete file is error,changefileAtt fail ,errno=%d , file=%s ", errno,m_uploading_file->path);
  1817. }
  1818. #endif // RVC_OS_WIN
  1819. }
  1820. else if (flags & UPLOAD_FLAG_MOVEPATH)
  1821. {
  1822. char to_path[MAX_PATH];
  1823. strcpy(to_path, m_uploading_file->owner->movepath);
  1824. strcat(to_path, SPLIT_SLASH_STR);
  1825. strcat(to_path, m_uploading_file->name);
  1826. Dbg("move file %s to %s", m_uploading_file->path, to_path);
  1827. #ifdef RVC_OS_WIN
  1828. if (m_uploading_handle != INVALID_HANDLE_VALUE) {
  1829. CloseHandle(m_uploading_handle);
  1830. m_uploading_handle = INVALID_HANDLE_VALUE;
  1831. }
  1832. DWORD dwAttr = GetFileAttributesA(m_uploading_file->path);
  1833. dwAttr &= ~FILE_ATTRIBUTE_READONLY;//一定要设置只读属性
  1834. SetFileAttributesA(m_uploading_file->path, dwAttr);
  1835. {
  1836. int i;
  1837. int tries = 10;
  1838. for (i = 0; i < tries; ++i) {
  1839. if (MoveFileExA(m_uploading_file->path, to_path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) {
  1840. Dbg("move ok! tries:%d", i);
  1841. break;
  1842. }
  1843. else {
  1844. Dbg("move %s -> %s failed! GetLastError:%d", m_uploading_file->path, to_path, GetLastError());
  1845. Sleep(1000);
  1846. }
  1847. }
  1848. }
  1849. #else
  1850. if (m_uploading_handle != NULL) {
  1851. fclose(m_uploading_handle);
  1852. m_uploading_handle = NULL;
  1853. }
  1854. if (changeFileAtt(m_uploading_file->path) == 0)
  1855. {
  1856. int i;
  1857. int tries = 10;
  1858. for (i = 0; i < tries; ++i) {
  1859. if (rename(m_uploading_file->path, to_path) == 0) {
  1860. Dbg("move ok! tries:%d", i);
  1861. break;
  1862. }
  1863. else {
  1864. Dbg("move %s -> %s failed! errno=%d", m_uploading_file->path, to_path,errno);
  1865. std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  1866. }
  1867. }
  1868. }
  1869. else
  1870. {
  1871. Dbg("move %s -> %s failed! , changefileAtt fail,errno=%d", m_uploading_file->path, to_path,errno);
  1872. }
  1873. #endif // RVC_OS_WIN
  1874. }
  1875. if (m_uploading_file)
  1876. {
  1877. //list_del(&m_uploading_file->entry);
  1878. //upload_file_destroy(m_uploading_file);
  1879. updir_del_file(m_uploading_file);//把文件从文件夹列表删除
  1880. m_uploading_file = NULL;
  1881. }
  1882. #ifdef RVC_OS_WIN
  1883. if (m_uploading_handle != INVALID_HANDLE_VALUE)
  1884. {
  1885. CloseHandle(m_uploading_handle);
  1886. m_uploading_handle = INVALID_HANDLE_VALUE;
  1887. }
  1888. #else
  1889. if (m_uploading_handle != NULL)
  1890. {
  1891. fclose(m_uploading_handle);
  1892. m_uploading_handle = NULL;
  1893. }
  1894. #endif // RVC_OS_WIN
  1895. }
  1896. //通过
  1897. bool UploadFSM::queryPlan()
  1898. {
  1899. //Dbg("queryPlan");
  1900. IHttpFunc* client;
  1901. client = create_http(HttpsLogCallBack);
  1902. CSystemStaticInfo si;
  1903. ErrorCodeEnum error = this->GetEntityBase()->GetFunction()->GetSystemStaticInfo(si);
  1904. if(error!=Error_Succeed){
  1905. return false;//获取失败,走旧模式
  1906. }
  1907. UploadQueryPlanReq planReq;
  1908. UploadQueryPlanRet planRet;
  1909. Json::Value rootReq;
  1910. Json::FastWriter writer;
  1911. rootReq["terminal_no"] = si.strTerminalID.GetData();
  1912. rootReq["os_type"] = "UOS";
  1913. string jsonReq = writer.write(rootReq);
  1914. planReq.m_reqStr = jsonReq;
  1915. //planReq.m_printDbg = true;
  1916. planReq.m_url = m_centerUrl.queryPlanUrl.c_str();
  1917. if(!client->Post(planReq, planRet)){
  1918. //Dbg("queryPlan http req fail,url is %s",m_centerUrl.queryPlanUrl.c_str());
  1919. 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());
  1920. client->Destory();
  1921. return false;//http错误,走旧模式
  1922. }
  1923. client->Destory();
  1924. //Dbg("planRet=%s",planRet.m_retStr.c_str());
  1925. //解析回应报文
  1926. Json::Reader reader;
  1927. Json::Value rootRet;
  1928. if (!reader.parse(planRet.m_retStr, rootRet, false))
  1929. {
  1930. Dbg("queryPlan parse resp is fail");
  1931. return false;//解析失败,走旧模式
  1932. }
  1933. bool isSucc = rootRet["success"].asBool();
  1934. if(isSucc){
  1935. if(rootRet.isMember("data")){
  1936. if(rootRet["data"]["mode"].asBool()){
  1937. //新模式
  1938. string branchNO = rootRet["data"]["branch_no"].asString();
  1939. //分行服务器列表:可能为空
  1940. if(rootRet["data"]["upload_address"].isMember("upload_url")){
  1941. for(int i =0;i<rootRet["data"]["upload_address"]["upload_url"].size();i++){
  1942. string bUploadUrl = rootRet["data"]["upload_address"]["upload_url"][i].asString();
  1943. m_branchIpList[i+1]=bUploadUrl;
  1944. //Dbg("queryPlan return upload_url=%s",bUploadUrl.c_str());
  1945. if(!bUploadUrl.empty()){
  1946. // Dbg("queryPlan return upload_url=%s",bUploadUrl.c_str());
  1947. }else{
  1948. Dbg("queryPlan return upload_url=");
  1949. }
  1950. }
  1951. }else{
  1952. Dbg("[data][upload_address][upload_url] is null");
  1953. }
  1954. string env = "";//上传服务器地址属于行内还是行外
  1955. if(rootRet["data"]["upload_address"].isMember("env")){
  1956. env = rootRet["data"]["upload_address"]["env"].asString();
  1957. if(strcmp(env.c_str(),"DMZ")==0||strcmp(env.c_str(),"BIZ")==0){
  1958. }else{
  1959. //Dbg("[data][upload_address][env] is invaild [%s]",env.c_str());
  1960. 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());
  1961. return false;//上传服务ip环境不正确,走旧模式
  1962. }
  1963. }else{
  1964. //Dbg("[data][upload_address][env] is null");
  1965. 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());
  1966. return false;//上传服务ip环境为空,走旧模式
  1967. }
  1968. //扫描策略:可能为空
  1969. for (int i =0;i <rootRet["data"]["plan_list"].size();i++){
  1970. UploadPlan* p = new UploadPlan();
  1971. p->plan_id = rootRet["data"]["plan_list"][i]["plan_id"].asString();
  1972. p->branch_no = branchNO;//分行号
  1973. p->plan_type = rootRet["data"]["plan_list"][i]["plan_type"].asString();
  1974. p->file_type = rootRet["data"]["plan_list"][i]["file_type"].asString();
  1975. p->path_type = rootRet["data"]["plan_list"][i]["path_type"].asString();
  1976. #ifdef RVC_OS_WIN
  1977. p->path_name = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1978. #else
  1979. //转义路径里面windows反斜杠'\'为'/'
  1980. //p->path_name = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1981. string pathName = rootRet["data"]["plan_list"][i]["path_name"].asString();
  1982. std::replace(pathName.begin(), pathName.end(), '\\', SPLIT_SLASH);
  1983. p->path_name = pathName.c_str();
  1984. #endif
  1985. p->file_name = rootRet["data"]["plan_list"][i]["file_name"].asString();
  1986. p->file_regex = rootRet["data"]["plan_list"][i]["file_regex"].asString();
  1987. p->before_deal_type = rootRet["data"]["plan_list"][i]["before_deal_type"].asString();
  1988. p->after_deal_type = rootRet["data"]["plan_list"][i]["after_deal_type"].asString();
  1989. #ifdef RVC_OS_WIN
  1990. p->after_deal_text = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1991. #else
  1992. //转义路径里面windows反斜杠'\'为'/'
  1993. //p->after_deal_text = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1994. string afterDealText = rootRet["data"]["plan_list"][i]["after_deal_text"].asString();
  1995. std::replace(afterDealText.begin(), afterDealText.end(), '\\', SPLIT_SLASH);
  1996. p->after_deal_text = afterDealText.c_str();
  1997. #endif
  1998. p->file_limit = rootRet["data"]["plan_list"][i]["file_limit"].asInt();
  1999. p->file_length_limit = rootRet["data"]["plan_list"][i]["file_length_limit"].asInt();//增加扫描文件最大长度限制
  2000. if(p->file_length_limit==0){
  2001. //默认扫描文件最大长度设置为200m
  2002. p->file_length_limit = 200;
  2003. }
  2004. p->max_silent = rootRet["data"]["plan_list"][i]["max_silent"].asInt();
  2005. p->upload_address_env = env;
  2006. m_uploadPlanList->push_back(p);
  2007. }
  2008. //行内需要判断分行服务url地址(废弃用终端场所判断,统一由后台服务返回文件上传地址)
  2009. //if(si.strSite.Compare("CMB.LIB",true)==0||si.strSite.Compare("CMB.SSB",true)==0){
  2010. // if(m_branchIpList.size()==0){
  2011. // return false;//告警分行服务ip为空,走旧模式
  2012. // }
  2013. //}
  2014. if(m_branchIpList.size()==0){
  2015. //Dbg("queryPlan return upload_url count is 0");
  2016. 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());
  2017. return false;//上传服务ip为空,走旧模式
  2018. }
  2019. if(m_uploadPlanList->size()==0){
  2020. Dbg("queryPlan return %d plan ",m_uploadPlanList->size());
  2021. return true;//等待下一次请求,走新模式
  2022. }
  2023. return true;//明确走新模式
  2024. }else{
  2025. Dbg("queryPlan return [data].[mode] is false");
  2026. return false;//明确走旧模式
  2027. }
  2028. }else{
  2029. Dbg("queryPlan return data is null");
  2030. return false;//无data字段,走旧模式
  2031. }
  2032. }else{
  2033. Dbg("queryPlan return success is false");
  2034. return false;//服务返回错误,走旧模式
  2035. }
  2036. }
  2037. //通过
  2038. void UploadFSM::scanFile()
  2039. {
  2040. list<UploadPlan*>::iterator iter;
  2041. for(iter = m_uploadPlanList->begin();iter!=m_uploadPlanList->end();++iter){
  2042. UploadPlan* up = *iter;
  2043. //构建初始的扫描根路径
  2044. string path="";
  2045. if(up->path_type=="R"){
  2046. #ifdef RVC_OS_WIN
  2047. path = m_rootPath + "\\" + up->path_name;
  2048. #else
  2049. path = m_rootPath + SPLIT_SLASH_STR + up->path_name;
  2050. #endif
  2051. }else if(up->path_type=="A"){
  2052. path=up->path_name;
  2053. }else{
  2054. Dbg("plan path_type is invalid path_type=%s",up->path_type.c_str());
  2055. continue;
  2056. }
  2057. if(m_printPlan){
  2058. Dbg("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);
  2059. }
  2060. scanDirfresh(up,path.c_str());
  2061. }
  2062. m_printPlan=false;//只打印一次,设置为不打印
  2063. //加入文件超过阈值后告警
  2064. if(m_uploadList->size()>m_uploadMaxNum){
  2065. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_MAX_ERROR, CSimpleStringA::Format("upload list num(%d) is over max num",m_uploadList->size()).GetData());
  2066. }
  2067. }
  2068. //通过
  2069. void UploadFSM::scanDirfresh(UploadPlan* plan,const char *path)
  2070. {
  2071. //Dbg("scan dir=%s",path);
  2072. array_header_t *arr_files = fileutil_get_sub_files2_a(path, plan->file_limit);
  2073. if (arr_files) {
  2074. int i;
  2075. for (i = 0; i < arr_files->nelts; ++i){
  2076. char *file_path = ARRAY_IDX(arr_files, i, char*);
  2077. //Dbg("find file src path=%s",file_path);
  2078. //得到文件名
  2079. string fileName = _GetFileName(file_path);
  2080. //Dbg("fileName=%s",fileName.c_str());
  2081. //文件名通配符过滤
  2082. CSimpleStringA strFileFilter = _GetFileName(plan->file_name.c_str());
  2083. //Dbg("strFileFilter=[%s]",strFileFilter.GetData());
  2084. if(!IsFileMatch(strFileFilter.GetData(),fileName.c_str())){
  2085. continue;//继续下一个文件
  2086. }
  2087. //正则表达式过滤
  2088. if(!plan->file_regex.empty()){
  2089. //Dbg("file_regex=[%s]",plan->file_regex.c_str());
  2090. regex e(plan->file_regex.c_str());
  2091. if(!regex_match(fileName.c_str(),e,regex_constants::match_default)){
  2092. continue;//继续下一个文件
  2093. }
  2094. }
  2095. #ifdef RVC_OS_WIN
  2096. //最后修改时间间隔过滤
  2097. WIN32_FILE_ATTRIBUTE_DATA attr;
  2098. if (!GetFileAttributesExA(file_path, GetFileExInfoStandard, &attr)) {
  2099. Dbg("get local file attrr fail! file_path=%s",file_path);
  2100. continue;//继续下一个文件
  2101. }
  2102. //判断文件是否超过最大扫描文件长度
  2103. unsigned long limit = plan->file_length_limit*1024*1024;
  2104. if(attr.nFileSizeLow>limit){
  2105. 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);
  2106. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_FILE_OVER_LIMIT, warnStr.GetData());
  2107. continue;//继续下一个文件
  2108. }
  2109. FILETIME fttmp;
  2110. SYSTEMTIME filest;
  2111. SYSTEMTIME st;
  2112. if(!FileTimeToLocalFileTime(&attr.ftLastWriteTime,&fttmp)){
  2113. continue;//继续下一个文件
  2114. }
  2115. if(!FileTimeToSystemTime(&fttmp,&filest)){
  2116. continue;//继续下一个文件
  2117. }
  2118. GetLocalTime(&st);
  2119. 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);
  2120. if(nsecondsInterval<plan->max_silent){
  2121. //Dbg("the time error! file_path=%s",file_path);
  2122. continue;//继续下一个文件,时间不够
  2123. }else{
  2124. //时间已够,判断文件是否能独占锁
  2125. if(!test_zero_ref(file_path)){
  2126. continue;//继续下一个文件
  2127. }
  2128. }
  2129. //得到文件长度
  2130. unsigned long filelen = attr.nFileSizeLow;
  2131. #else
  2132. struct stat attr_of_src;
  2133. if (lstat(file_path, &attr_of_src) != 0) {
  2134. Dbg("get local file attrr fail! file_path=%s", file_path);
  2135. continue;//继续下一个文件
  2136. }
  2137. //判断文件是否超过最大扫描文件长度
  2138. unsigned long limit = plan->file_length_limit * 1024 * 1024;
  2139. if (attr_of_src.st_size > limit) {
  2140. 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);
  2141. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_QUERY_FILE_OVER_LIMIT, warnStr.GetData());
  2142. continue;//继续下一个文件
  2143. }
  2144. time_t nowTime = time((time_t*)NULL);//当前时间
  2145. if (nowTime > attr_of_src.st_mtime)
  2146. {
  2147. long diff = nowTime - attr_of_src.st_mtime;
  2148. if (diff < plan->max_silent)
  2149. {
  2150. //Dbg("the time error! file_path=%s",file_path);
  2151. continue;//继续下一个文件,时间不够
  2152. }else{
  2153. //时间已够,判断文件是否能独占锁
  2154. if (!test_zero_ref(file_path)) {
  2155. continue;//继续下一个文件
  2156. }
  2157. }
  2158. }else {
  2159. //Dbg("the time error! file_path=%s",file_path);
  2160. continue;//继续下一个文件,时间不够
  2161. }
  2162. //得到文件长度
  2163. unsigned long filelen = attr_of_src.st_size;
  2164. #endif
  2165. //添加扫描文件
  2166. UploadFileInfo* upFile = new UploadFileInfo();
  2167. upFile->fileName = fileName;
  2168. upFile->filePath = file_path;
  2169. if(upFile->filePath.length()>900){
  2170. //路径太长,ECS存储有问题,截取路径,并加入模拟路径前缀:window S:\\ , linux /S/
  2171. #ifdef RVC_OS_WIN
  2172. upFile->fileUploadPath.append("S:\\");
  2173. #else
  2174. upFile->fileUploadPath.append("/S/");
  2175. #endif
  2176. upFile->fileUploadPath.append(fileName.c_str());
  2177. //upFile->fileUploadRelativePath = "S:\\";
  2178. }else{
  2179. //直接赋值
  2180. upFile->fileUploadPath = file_path;
  2181. //upFile->fileUploadRelativePath = upFile->fileUploadPath.substr(0,upFile->fileUploadPath.length()-fileName.length());//截取文件名称的路径
  2182. }
  2183. upFile->BranchFilePath = file_path;
  2184. upFile->fileLen = filelen;
  2185. #ifdef RVC_OS_WIN
  2186. upFile->editTime = CSimpleStringA::Format("%d-%d-%d %d:%d:%d",filest.wYear, filest.wMonth, filest.wDay, filest.wHour, filest.wMinute, filest.wSecond);
  2187. #else
  2188. tm fileTimeTm = { 0 };
  2189. localtime_r(&attr_of_src.st_mtime, &fileTimeTm);
  2190. 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);
  2191. #endif
  2192. upFile->plan_id = plan->plan_id;
  2193. upFile->branch_no = plan->branch_no;
  2194. upFile->plan_type = plan->plan_type;
  2195. upFile->file_type = plan->file_type;
  2196. upFile->path_type = plan->path_type;
  2197. upFile->path_name = plan->path_name;//因传回路径可能是windows路径斜杠,转义为linux斜杠
  2198. upFile->file_name = plan->file_name;
  2199. upFile->file_regex = plan->file_regex;
  2200. upFile->before_deal_type = plan->before_deal_type;
  2201. upFile->after_deal_type = plan->after_deal_type;
  2202. upFile->after_deal_text = plan->after_deal_text;
  2203. upFile->file_limit = plan->file_limit;
  2204. upFile->file_length_limit = plan->file_length_limit;
  2205. upFile->max_silent = plan->max_silent;
  2206. upFile->upload_address_env = plan->upload_address_env;
  2207. m_uploadList->push_back(upFile);
  2208. //Dbg("file %s lenth(%d) added!",file_path,filelen);
  2209. }
  2210. toolkit_array_free2(arr_files);
  2211. }
  2212. array_header_t *arr_dir = fileutil_get_sub_dirs_a(path);
  2213. if (arr_dir) {
  2214. int i;
  2215. for (i = 0; i < arr_dir->nelts; ++i) {
  2216. char *dir_path = ARRAY_IDX(arr_dir, i, char*);
  2217. scanDirfresh(plan, dir_path);
  2218. }
  2219. }
  2220. }
  2221. void UploadFSM::HttpsLogCallBack(const char* logtxt)
  2222. {
  2223. if(logtxt!=NULL){
  2224. Dbg("http dbg: %s",logtxt);
  2225. }
  2226. }
  2227. bool UploadFSM::IsFileMatch(const char *pszFilter, const char *pszFileName)
  2228. {
  2229. const char *p1 = pszFilter;
  2230. const char *p2 = pszFileName;
  2231. if (p1 == NULL)
  2232. return true;
  2233. if (p2 == NULL)
  2234. return false;
  2235. if (*p1 ==NULL && *p2 ==NULL)
  2236. return true;
  2237. else if (*p1 == NULL)
  2238. return false;
  2239. else if (*p2 == NULL)
  2240. {
  2241. // 查找*p1是否全是*
  2242. while (*p1 == '*')
  2243. p1++;
  2244. if (*p1 == NULL)
  2245. return true;
  2246. else
  2247. return false;
  2248. }
  2249. if (*p1 != '*')
  2250. {
  2251. if (tolower(*p1) != tolower(*p2))
  2252. return false;
  2253. else
  2254. return IsFileMatch(p1+1, p2+1);
  2255. }
  2256. else
  2257. {
  2258. while(*++p1 == '*');
  2259. if (*p1 == NULL)
  2260. return true;
  2261. while (*p2)
  2262. {
  2263. while(tolower(*p1) != tolower(*p2) && *++p2);
  2264. if (*p2 == NULL)
  2265. return false;
  2266. if(IsFileMatch(p1+1, p2+1))
  2267. return true;
  2268. p2++;
  2269. }
  2270. return false;
  2271. }
  2272. }
  2273. ErrorCodeEnum UploadFSM::SM3FileToStr(CSimpleStringA strFilePath, CSimpleStringA &strSM3,bool isSub)
  2274. {
  2275. if(strFilePath.IsNullOrEmpty()){
  2276. return Error_Null;
  2277. }
  2278. int nlen = strlen(strFilePath.GetData());
  2279. char* pchar = new char[nlen+1];
  2280. strcpy(pchar,strFilePath.GetData());
  2281. BYTE md5[32]={0};
  2282. try
  2283. {
  2284. if(SM3File(pchar,md5)){
  2285. delete pchar;
  2286. //获取16进制的字符串
  2287. if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
  2288. Dbg("sm3国密转16进制字符串失败,file=%s",strFilePath.GetData());
  2289. return Error_Unexpect;
  2290. }
  2291. return Error_Succeed;
  2292. }else{
  2293. delete pchar;
  2294. Dbg("sm3国密加密失败,file=%s",strFilePath.GetData());
  2295. return Error_Unexpect;
  2296. }
  2297. }
  2298. catch (...)
  2299. {
  2300. delete pchar;
  2301. Dbg("sm3国密加密异常失败,file=%s",strFilePath.GetData());
  2302. return Error_Exception;
  2303. }
  2304. }
  2305. ErrorCodeEnum UploadFSM::SM3_Str(CSimpleStringA &strSM3,BYTE * SM3Byte,bool isSub)
  2306. {
  2307. if(SM3Byte == NULL){
  2308. return Error_Exception;
  2309. }
  2310. int SM3_len=64;
  2311. if(isSub){
  2312. SM3_len=32;
  2313. }
  2314. int i;
  2315. char* file_SM3 = (char*)malloc((SM3_len + 1) * sizeof(char));
  2316. if(file_SM3 == NULL)
  2317. {
  2318. fprintf(stderr, "SM3 malloc failed.\n");
  2319. return Error_Exception;
  2320. }
  2321. memset(file_SM3, 0, (SM3_len + 1));
  2322. if(SM3_len == 32)
  2323. {
  2324. for(i=0; i<16; i++)
  2325. { //SM3截取中间16位字节,8-24位字节数,小写
  2326. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i+8]);
  2327. }
  2328. }
  2329. else if(SM3_len == 64)
  2330. {
  2331. for(i=0; i<32; i++)
  2332. {
  2333. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i]);
  2334. }
  2335. }
  2336. strSM3=file_SM3;
  2337. free(file_SM3);
  2338. return Error_Succeed;
  2339. }
  2340. bool UploadFSM::getFileContent(FILE* pFile,unsigned char* content,int beginPos, int contentLen)
  2341. {
  2342. if(pFile==NULL||content==NULL){
  2343. return false;
  2344. }
  2345. if(fseek(pFile,beginPos,SEEK_SET)!=0){
  2346. return false;
  2347. }
  2348. unsigned char* pRead = content;//移动的指针
  2349. int pRemaind = contentLen; //剩余字节数
  2350. int numBytes = 0;
  2351. while(!feof(pFile)&&!ferror(pFile)){
  2352. if(pRemaind<=0){
  2353. break;
  2354. }
  2355. numBytes=(int)fread(pRead,1,pRemaind,pFile);
  2356. //Dbg("读取字节numBytes=%d",numBytes);
  2357. if(numBytes>0){
  2358. pRemaind -=numBytes;
  2359. pRead +=numBytes;
  2360. }
  2361. }
  2362. if(pRemaind==0){
  2363. return true;
  2364. }else{
  2365. Dbg("getFileContent fail,pRemaind =%d",pRemaind);
  2366. return false;
  2367. }
  2368. }
  2369. bool UploadFSM::test_zero_ref(const char *path)
  2370. {
  2371. #ifdef RVC_OS_WIN
  2372. HANDLE hFile = CreateFileA(path,
  2373. GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); // try open
  2374. if (hFile != INVALID_HANDLE_VALUE) {
  2375. CloseHandle(hFile);
  2376. return TRUE;
  2377. } else {
  2378. //添加获取句柄失败情况
  2379. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_SCANFILE_LOCK_ERROR, CSimpleStringA::Format("test_zero_ref is fail:%s",path).GetData());
  2380. DWORD dwRet = GetLastError();
  2381. return FALSE;
  2382. }
  2383. #else
  2384. //后期改为linux真正的文件锁,现在来看,暂时用不着
  2385. FILE* fp = fopen(path, "rb");
  2386. if (fp != NULL) {
  2387. fclose(fp);
  2388. return true;
  2389. }
  2390. else
  2391. {
  2392. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_SCANFILE_LOCK_ERROR, CSimpleStringA::Format("check_zero_ref is fail:%s", path).GetData());
  2393. return false;
  2394. }
  2395. #endif // RVC_OS_WIN
  2396. }
  2397. bool UploadFSM::GetFileLength(const char* filePath,long &fileLen)
  2398. {
  2399. FILE* file = fopen(filePath, "rb");
  2400. if (file!=NULL)
  2401. {
  2402. #ifdef RVC_OS_WIN
  2403. fileLen = filelength(fileno(file));
  2404. fclose(file);
  2405. return true;
  2406. #else
  2407. //取得当前文件流的读取位置
  2408. int cur_pos = ftell(file);
  2409. //将文件流的读取位置设为文件末尾
  2410. if (fseek(file, SEEK_SET, SEEK_END)==0) {
  2411. //获取文件末尾的读取位置,即文件大小
  2412. fileLen = ftell(file);
  2413. //将文件流的读取位置还原为原先的值
  2414. fseek(file, cur_pos, SEEK_SET);
  2415. fclose(file);
  2416. return true;
  2417. }
  2418. else {
  2419. Dbg("fseek file=%s is fail, err=%d", filePath,errno);
  2420. fclose(file);
  2421. return false;
  2422. }
  2423. #endif
  2424. } else{
  2425. fileLen = 0;
  2426. return false;
  2427. }
  2428. }
  2429. void UploadFSM::reportBatchMsg()
  2430. {
  2431. CSimpleStringA strReport;
  2432. if(m_uploadReport.fail==0){
  2433. 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)",
  2434. m_uploadReport.isBreak, m_uploadReport.sum, m_uploadReport.succ, m_uploadReport.fail, m_uploadReport.uploadFail, m_uploadReport.updateState,
  2435. m_uploadReport.operateFileFail, m_uploadReport.decodeFail, m_uploadReport.queryTempFail);
  2436. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
  2437. }else{
  2438. 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)",
  2439. m_uploadReport.isBreak, m_uploadReport.sum, m_uploadReport.succ, m_uploadReport.fail, m_uploadReport.uploadFail, m_uploadReport.updateState,
  2440. m_uploadReport.operateFileFail, m_uploadReport.decodeFail, m_uploadReport.queryTempFail);
  2441. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPLOAD_FILE_REPORT, strReport.GetData());
  2442. }
  2443. }
  2444. /** 交易受限功能代码废弃
  2445. int UploadFSM::getCheckDirFile(int silentTime)
  2446. {
  2447. //把要检查的目录在要上传的目录里面查询,并搜索文件
  2448. list<CSimpleStringA>::iterator iter;
  2449. int sum =0;
  2450. int count=0;
  2451. for(iter=m_check_dir->begin();iter!=m_check_dir->end();++iter){
  2452. CSimpleStringA checkstr= *iter;
  2453. upload_dir_t *pos;
  2454. list_for_each_entry(pos, &m_updir_list, upload_dir_t, entry)
  2455. {
  2456. if(strcmp(pos->name,checkstr.GetData())==0){
  2457. int fileLen=0;//文件长度,长度是k
  2458. count = check_dir_fresh(pos->path,pos->child_count_limitation,silentTime,fileLen);
  2459. Dbg("交易文件夹:%s 还有未上传的文件个数 %d,文件总大小 %d k",pos->name,count,fileLen);
  2460. sum +=count;
  2461. }else{
  2462. continue;;
  2463. }
  2464. }
  2465. }
  2466. return sum;
  2467. }
  2468. void UploadFSM::getUploadProgress(UploadProgress &progress)
  2469. {
  2470. int fileSumlen=0;
  2471. if(m_iState==s0){
  2472. progress.uploadState=0;
  2473. progress.elapseTime="--:--:--";
  2474. progress.uploadNumber=getUploadFileNum(fileSumlen);
  2475. }else if(m_iState==s1){
  2476. progress.uploadState=1;
  2477. progress.elapseTime="--:--:--";
  2478. progress.uploadNumber=getUploadFileNum(fileSumlen);
  2479. }else if(m_iState==s2){
  2480. progress.uploadState=2;
  2481. progress.elapseTime="--:--:--";
  2482. progress.uploadNumber=getUploadFileNum(fileSumlen);
  2483. }else if(m_iState==s3){
  2484. progress.uploadState=3;
  2485. progress.elapseTime="--:--:--";
  2486. progress.uploadNumber=getUploadFileNum(fileSumlen);
  2487. }else if(m_iState==s4){
  2488. progress.uploadState=4;
  2489. progress.uploadNumber=getUploadFileNum(fileSumlen);
  2490. //Dbg("总文件长度:%d",fileSumlen);
  2491. if(m_iSpeed!=0){
  2492. int loop = fileSumlen/m_iSpeed ;
  2493. //Dbg("loop:%d",loop);
  2494. CSimpleStringA hour=CSimpleStringA::Format("%d",loop/3600);
  2495. //Dbg("hour:%s",hour);
  2496. loop=loop%3600;
  2497. CSimpleStringA ss = CSimpleStringA::Format("%02d",loop/60);
  2498. //Dbg("ss:%s",ss);
  2499. loop = loop%60;
  2500. CSimpleStringA mm = CSimpleStringA::Format("%02d",loop);
  2501. //Dbg("mm:%s",mm);
  2502. CSimpleStringA strloop = hour+":"+ss+":"+mm;
  2503. progress.elapseTime=strloop;//动态获取估计时间
  2504. Dbg("总预估时间:%s",strloop.GetData());
  2505. }else{
  2506. progress.elapseTime="--:--:--";
  2507. }
  2508. }else if(m_iState==s5){
  2509. progress.uploadState=5;
  2510. progress.elapseTime="--:--:--";
  2511. progress.uploadNumber=getUploadFileNum(fileSumlen);
  2512. }else if(m_iState==s6){
  2513. progress.uploadState=6;
  2514. progress.elapseTime="--:--:--";
  2515. progress.uploadNumber=getUploadFileNum(fileSumlen);
  2516. }else{
  2517. progress.uploadState=-1;
  2518. progress.elapseTime="--:--:--";
  2519. progress.uploadNumber=getUploadFileNum(fileSumlen);
  2520. }
  2521. }
  2522. int UploadFSM::getUploadFileNum(int &fileSumlen)
  2523. {
  2524. int sum=0;
  2525. upload_dir_t *pos;
  2526. int count=0;
  2527. list_for_each_entry(pos, &m_updir_list, upload_dir_t, entry)
  2528. {
  2529. int fileLen=0;//文件长度,长度是k
  2530. count = check_dir_fresh(pos->path,pos->child_count_limitation,pos->silent_time,fileLen);
  2531. if(count!=0){
  2532. Dbg("文件夹:%s 未上传的文件个数 %d,文件大小 %d k",pos->name,count,fileLen);
  2533. }
  2534. sum += count;
  2535. fileSumlen += fileLen;
  2536. }
  2537. Dbg("上传进度查询:未上传的文件总个数 %d,文件总大小 %d k",sum,fileSumlen);
  2538. return sum;
  2539. }
  2540. bool UploadFSM::clearUploadDate()
  2541. {
  2542. bool ret = false;
  2543. EnterCriticalSection(&m_cs);
  2544. m_uploadDateList->clear();
  2545. ErrorCodeEnum Error = SaveUploadDate();
  2546. if(Error==Error_Succeed){
  2547. ret = true;
  2548. }else{
  2549. ret = false;
  2550. }
  2551. LeaveCriticalSection(&m_cs);
  2552. return ret;
  2553. }
  2554. ErrorCodeEnum UploadFSM::SaveUploadDate()
  2555. {
  2556. CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();;
  2557. CSmartPointer<IConfigInfo> spConfig;
  2558. ErrorCodeEnum Error = spFunction->OpenConfig(Config_Run, spConfig);
  2559. if (Error == Error_Succeed) {
  2560. list<CSimpleStringA>::iterator iter;
  2561. CSimpleStringA strDate="";
  2562. for(iter=m_uploadDateList->begin();iter!=m_uploadDateList->end();++iter){
  2563. CSimpleStringA date = (CSimpleStringA)*iter;
  2564. strDate.Append(date);
  2565. strDate.Append(",");
  2566. }
  2567. CSimpleStringA writeStr ="";
  2568. if(strDate.GetLength()>0){
  2569. writeStr = strDate.SubString(0,strDate.GetLength()-1);
  2570. Dbg("prepare write uploadDate/dateList : %s",writeStr.GetData());
  2571. Error = spConfig->WriteConfigValue("uploadDate", "dateList", writeStr.GetData());
  2572. }else{
  2573. Dbg("prepare write uploadDate/dateList : ");
  2574. Error = spConfig->WriteConfigValue("uploadDate", "dateList", writeStr.GetData());
  2575. }
  2576. if(Error==Error_Succeed){
  2577. Dbg("write uploadDate/dateList success: %s",writeStr.GetData());
  2578. }else{
  2579. Dbg("write uploadDate/dateList fail: %s error:%d",writeStr.GetData(),Error);
  2580. }
  2581. }else{
  2582. Dbg("SaveUploadDate is fail , open runcfg/upload.ini fail!");
  2583. }
  2584. return Error;
  2585. }
  2586. ErrorCodeEnum UploadFSM::getUploadDate( CAutoArray<CSimpleStringA> &strList )
  2587. {
  2588. ErrorCodeEnum Error = Error_Succeed;
  2589. EnterCriticalSection(&m_cs);
  2590. //CSmartPointer<IEntityFunction> spFunction = m_pEntity->GetFunction();;
  2591. //CSmartPointer<IConfigInfo> spConfig;
  2592. //Error = spFunction->OpenConfig(Config_Run, spConfig);
  2593. //if (Error == Error_Succeed) {
  2594. // CSimpleStringA dateList ="";
  2595. // Error = spConfig->ReadConfigValue("uploadDate", "dateList", dateList);
  2596. // if(Error == Error_Succeed){
  2597. // strList = dateList.Split(',');
  2598. // }else{
  2599. // Dbg("getUploadDate read upload.ini param uploadDate/dateList fail!");
  2600. // }
  2601. //}else{
  2602. // Dbg("getUploadDate open runcfg upload.ini fail, please check out upload.ini!");
  2603. //}
  2604. //因运行时文件可能会有错误的日期,故从内存中读取
  2605. strList.Init(m_uploadDateList->size());
  2606. list<CSimpleStringA>::iterator iter;
  2607. CSimpleStringA strDate="";
  2608. int i=0;
  2609. for(iter=m_uploadDateList->begin();iter!=m_uploadDateList->end();++iter){
  2610. CSimpleStringA strDate = *iter;
  2611. strList[i]=strDate;
  2612. Dbg("getUploadDate strDate[%d]:%s",i,strDate.GetData());
  2613. i++;
  2614. }
  2615. LeaveCriticalSection(&m_cs);
  2616. return Error;
  2617. }
  2618. ErrorCodeEnum UploadFSM::insertUploadDate()
  2619. {
  2620. ErrorCodeEnum Error = Error_Succeed;
  2621. EnterCriticalSection(&m_cs);
  2622. list<CSimpleStringA>::iterator iter;
  2623. for(iter=m_check_dir->begin();iter!=m_check_dir->end();++iter){
  2624. CSimpleStringA checkstr= *iter;
  2625. upload_dir_t *pos;
  2626. list_for_each_entry(pos, &m_updir_list, upload_dir_t, entry)
  2627. {
  2628. if(strcmp(pos->name,checkstr.GetData())==0){
  2629. if (!list_empty(&pos->candidate_list)) {
  2630. file_t *fpos;
  2631. list_for_each_entry(fpos,&pos->candidate_list,file_t,entry){
  2632. #ifdef RVC_OS_WIN
  2633. WIN32_FILE_ATTRIBUTE_DATA attr;
  2634. FILETIME fttmp;
  2635. SYSTEMTIME filest;
  2636. if (GetFileAttributesExA(fpos->path, GetFileExInfoStandard, &attr))
  2637. {
  2638. FileTimeToLocalFileTime(&attr.ftLastWriteTime, &fttmp);
  2639. FileTimeToSystemTime(&fttmp, &filest);
  2640. CSimpleStringA strDate = CSimpleStringA::Format("%4.4d-%2.2d-%2.2d", filest.wYear, filest.wMonth, filest.wDay);
  2641. if (!uploadDate_exist(strDate))
  2642. {
  2643. Dbg("insertUploadDate %s:%s", fpos->path, strDate.GetData());
  2644. m_uploadDateList->push_back(strDate);
  2645. if (SaveUploadDate() == Error_Succeed) {
  2646. Dbg("insertUploadDate is success! %s:%s", fpos->path, strDate.GetData());
  2647. }
  2648. else {
  2649. Dbg("insertUploadDate is fail%s:%s", fpos->path, strDate.GetData());
  2650. //因文件写入失败,删除当前的日期,后续还有文件上传会继续添加进来
  2651. m_uploadDateList->pop_back();
  2652. }
  2653. }
  2654. }
  2655. #else
  2656. struct stat attr_of_src;
  2657. if (lstat(fpos->path, &attr_of_src) == 0) {
  2658. struct tm flocalTime = { 0 };
  2659. localtime_r(&attr_of_src.st_mtime,&flocalTime);
  2660. CSimpleStringA strDate = CSimpleStringA::Format("%4.4d-%2.2d-%2.2d", (1900 + flocalTime.tm_year), (1 + flocalTime.tm_mon), flocalTime.tm_mday);
  2661. if (!uploadDate_exist(strDate))
  2662. {
  2663. Dbg("insertUploadDate %s:%s", fpos->path, strDate.GetData());
  2664. m_uploadDateList->push_back(strDate);
  2665. if (SaveUploadDate() == Error_Succeed) {
  2666. Dbg("insertUploadDate is success! %s:%s", fpos->path, strDate.GetData());
  2667. }
  2668. else {
  2669. Dbg("insertUploadDate is fail%s:%s", fpos->path, strDate.GetData());
  2670. //因文件写入失败,删除当前的日期,后续还有文件上传会继续添加进来
  2671. m_uploadDateList->pop_back();
  2672. }
  2673. }
  2674. }
  2675. else {
  2676. Dbg("get file attr fail,file=%s", fpos->path);
  2677. }
  2678. #endif // RVC_OS_WIN
  2679. }
  2680. }
  2681. }
  2682. }
  2683. }
  2684. LeaveCriticalSection(&m_cs);
  2685. return Error;
  2686. }
  2687. bool UploadFSM::uploadDate_exist( CSimpleStringA uploadDate )
  2688. {
  2689. bool ret = false;
  2690. list<CSimpleStringA>::iterator iter;
  2691. CSimpleStringA strDate="";
  2692. for(iter=m_uploadDateList->begin();iter!=m_uploadDateList->end();++iter){
  2693. if(*iter==uploadDate){
  2694. ret=true;
  2695. break;
  2696. }
  2697. }
  2698. return ret;
  2699. }
  2700. */