UploadFSM.cpp 90 KB

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