UpgradeTaskFSM.cpp 222 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792
  1. #include "UpgradeTaskFSM.h"
  2. #include "fileutil.h"
  3. #include "iniutil.h"
  4. #include "memutil.h"
  5. #include "RVCComm.h"
  6. #include <regex>
  7. #include "mod_UpgradeMgr.h"
  8. #include "UpgradeManager_msg_g.h"
  9. #ifdef RVC_OS_WIN
  10. #include <WinBase.h>
  11. #include <io.h>
  12. #include "XUnzip.h"
  13. #include <ShellAPI.h>
  14. #else
  15. #include <sys/utsname.h>
  16. #include "XUnZipZilb.h"
  17. #endif
  18. #include "EventCode.h"
  19. #include "UpgradeMgr_UserCode.h"
  20. #include "json/json.h"
  21. namespace Task
  22. {
  23. //计算和发送文件hash
  24. struct SendSM3Task : public ITaskSp{
  25. CUpgradeTaskFSM* m_fsm;
  26. explicit SendSM3Task(CUpgradeTaskFSM* f) : m_fsm(f) {}
  27. void Process(){
  28. LOG_FUNCTION();
  29. int tryCount=3;//总共3次机会
  30. bool SendHashOK= false;
  31. while(tryCount>0){
  32. //计算hash
  33. if(m_fsm->m_fileSM3ListHash.IsNullOrEmpty()){
  34. if(getSM3Hash()){
  35. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3Task")("get SM3 list succ, len=%d, fileNum = %d, SM3 hash=%s", m_fsm->m_fileSM3List.GetLength(), m_fsm->m_fileSM3Map.size(), m_fsm->m_fileSM3ListHash.GetData());
  36. }else{
  37. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_GET_SM3_HASH_FAIL, "get SM3 list fail");
  38. tryCount--;
  39. Sleep(60*1000);//等待60s再计算
  40. continue;
  41. }
  42. }
  43. //发送hash
  44. if(sendSM3Hash()){
  45. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3Task")("send SM3 list succ");
  46. m_fsm->isSendHash=true;
  47. SendHashOK = true;
  48. break;
  49. }else{
  50. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_SEND_SM3_HASH_FAIL, "send SM3 list fail");
  51. m_fsm->isSendHash=false;
  52. Sleep(60*1000);//等待60s再上传
  53. tryCount--;
  54. continue;
  55. }
  56. }
  57. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::SendSM3TaskEvent(SendHashOK));//返回处理结果
  58. }
  59. bool getSM3Hash(){
  60. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getSM3Hash")("begin get SM3 list");
  61. CSmallDateTime beginT = CSmallDateTime::GetNow();
  62. CSimpleStringA tempSM3ListStr = "";
  63. ErrorCodeEnum rc = m_fsm->GetSM3List(tempSM3ListStr);
  64. CSmallDateTime endT = CSmallDateTime::GetNow();
  65. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("getSM3Hash")("get SM3 list 耗时%d秒",(DWORD)(endT-beginT));
  66. if (rc != Error_Succeed)
  67. {
  68. LogError(Severity_Middle, rc, 0, "get SM3 list fail");
  69. return false;
  70. }
  71. else
  72. {
  73. //tempSM3ListStr 这个值有可能因为配置的文件夹下面没有文件,故为空
  74. if(tempSM3ListStr.IsNullOrEmpty()){
  75. m_fsm->m_fileSM3ListHash = "TerminalTempHash";
  76. return true;
  77. }else{
  78. CSimpleStringA tempSM3HashStr = "";
  79. if(Error_Succeed==m_fsm->SM3DataToStr(tempSM3ListStr,tempSM3HashStr,false)){
  80. m_fsm->m_fileSM3ListHash = tempSM3HashStr;
  81. return true;
  82. }else{
  83. LogError(Severity_Middle, rc, 0, "get SM3 list hash fail");
  84. return false;
  85. }
  86. }
  87. }
  88. }
  89. bool sendSM3Hash(){
  90. //LOG_FUNCTION();
  91. IHttpFunc* client;
  92. client = create_http(m_fsm->HttpsLogCallBack);
  93. //发送hash
  94. bool bRet = SendSM3TaskImpl(client);
  95. client->Destory();
  96. return bRet;
  97. }
  98. bool SendSM3TaskImpl(IHttpFunc* client){
  99. HttpStruct::SendSM3TaskReq qTempReq;
  100. HttpStruct::SendSM3TaskRet qTempRet;
  101. CSystemStaticInfo info;
  102. ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  103. if (rc != Error_Succeed)
  104. {
  105. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendSM3TaskImpl")("SendSM3Task get CSystemStaticInfo fail");
  106. return false;
  107. }
  108. Json::Value rootReq;
  109. Json::FastWriter writer;
  110. rootReq["terminal_no"] = info.strTerminalID.GetData();
  111. rootReq["software_version"] = m_fsm->m_currentVersion.ToString().GetData();
  112. rootReq["file_hash_list"] = m_fsm->m_fileSM3List.GetData();//hash集合
  113. rootReq["list_hash"] = m_fsm->m_fileSM3ListHash.GetData();//64位
  114. string jsonReq = writer.write(rootReq);
  115. qTempReq.m_reqStr = jsonReq;//请求参数
  116. qTempReq.m_url=m_fsm->m_centerUrl.sendSM3TaskUrl;//访问地址
  117. qTempReq.m_timeOut = 60;//设置传送超时时间为60s
  118. //打印发送请求
  119. if(m_fsm->m_PrintHttpLog){
  120. qTempReq.m_printDbg = true;
  121. }
  122. if(!client->Post(qTempReq, qTempRet)){
  123. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_SEND_SM3_HASH_FAIL,CSimpleStringA::Format("SendSM3Task http req fail,url=%s, err=%s",qTempReq.m_url.c_str(),qTempRet.m_errMsg.c_str()).GetData());
  124. return false;//失败
  125. }
  126. //打印回应报文
  127. if(m_fsm->m_PrintHttpLog){
  128. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendSM3TaskImpl")("qTempRet=%s",qTempRet.m_retStr.c_str());
  129. }
  130. Json::Reader reader;
  131. Json::Value rootRet;
  132. if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  133. {
  134. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_SEND_SM3_HASH_FAIL,CSimpleStringA::Format("SendSM3Task parse resp is fail,url=%s",qTempReq.m_url.c_str()).GetData());
  135. return false;//失败
  136. }
  137. bool isSucc = rootRet["success"].asBool();
  138. if(isSucc){
  139. if(rootRet.isMember("data")){
  140. if(rootRet["data"].asBool()){
  141. return true;//写入成功
  142. }else{
  143. return false;//写入失败
  144. }
  145. }else{
  146. return false;//写入失败
  147. }
  148. }else{
  149. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SendSM3TaskImpl")("SendSM3Task [success] is false");
  150. return false;//写入失败
  151. }
  152. }
  153. };
  154. //更新任务状态
  155. struct UpdateTaskStatus : public ITaskSp{
  156. CUpgradeTaskFSM* m_fsm;
  157. explicit UpdateTaskStatus(CUpgradeTaskFSM* f) : m_fsm(f) {}
  158. void Process(){
  159. LOG_FUNCTION();
  160. IHttpFunc* client;
  161. client = create_http(m_fsm->HttpsLogCallBack);
  162. bool isSendSucc=false;//更新是否成功标志
  163. if(UpdateTaskStatusImpl(client)){
  164. isSendSucc = true;
  165. }else{
  166. isSendSucc = false;
  167. }
  168. client->Destory();
  169. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::UpdateTaskStatusEvent(isSendSucc));//返回处理结果
  170. }
  171. bool UpdateTaskStatusImpl(IHttpFunc* client){
  172. CSystemStaticInfo info;
  173. ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  174. if (rc != Error_Succeed)
  175. {
  176. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateTaskStatusImpl")("UpdateTaskStatus get CSystemStaticInfo fail,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
  177. return false;
  178. }
  179. HttpStruct::UpdateTaskStatusReq qTempReq;
  180. HttpStruct::UpdateTaskStatusRet qTempRet;
  181. Json::Value rootReq;
  182. Json::FastWriter writer;
  183. rootReq["terminal_no"] = info.strTerminalID.GetData();
  184. rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
  185. //状态为C时,为X时,或者T,版本不一致,则是回退,否则是成功
  186. //返回任务结果给服务器
  187. if(m_fsm->m_currentTask.cPendingState=="C"){
  188. rootReq["upgrade_status"] = "F";//失败
  189. }else if(m_fsm->m_currentTask.cPendingState=="X"){
  190. rootReq["upgrade_status"] = "X";//未知状态
  191. }else if(m_fsm->m_currentTask.cPendingState=="T"){
  192. if(m_fsm->m_currentTask.NewVersion==m_fsm->m_currentVersion.ToString()||m_fsm->m_currentTask.NewVersion==""){
  193. //升级成功
  194. rootReq["upgrade_status"] = "S";//成功
  195. }else{
  196. //升级失败,回滚版本导致
  197. rootReq["upgrade_status"] = "F";//失败
  198. }
  199. }
  200. string jsonReq = writer.write(rootReq);
  201. qTempReq.m_reqStr = jsonReq;//请求参数
  202. qTempReq.m_url=m_fsm->m_centerUrl.updateTaskUrl;//访问地址
  203. //打印发送请求
  204. if(m_fsm->m_PrintHttpLog){
  205. qTempReq.m_printDbg = true;
  206. }
  207. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateTaskStatusImpl")("UpdateTaskStatus req=%s",qTempReq.m_reqStr.c_str());
  208. if(!client->Post(qTempReq, qTempRet)){
  209. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_TASK_STATUS_FAIL,CSimpleStringA::Format("UpdateTaskStatus http req fail, upgradeTaskId=%s, url=%s, err=%s",m_fsm->m_currentTask.upgradeTaskId.GetData(),qTempReq.m_url.c_str(),qTempRet.m_errMsg.c_str()).GetData());
  210. return false;//失败
  211. }
  212. //打印回应报文
  213. if(m_fsm->m_PrintHttpLog){
  214. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateTaskStatusImpl")("qTempRet=%s",qTempRet.m_retStr.c_str());
  215. }
  216. Json::Reader reader;
  217. Json::Value rootRet;
  218. if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  219. {
  220. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_TASK_STATUS_FAIL,CSimpleStringA::Format("UpdateTaskStatus parse resp is fail, upgradeTaskId=%s, url=%s",m_fsm->m_currentTask.upgradeTaskId.GetData(),qTempReq.m_url.c_str()).GetData());
  221. return false;//失败
  222. }
  223. bool isSucc = rootRet["success"].asBool();
  224. if(isSucc){
  225. if(rootRet.isMember("data")){
  226. int isUpdate =rootRet["data"].asInt();
  227. //0:更新失败 1:更新成功 2:任务不属于此终端等异常情况,默认成功
  228. if(isUpdate==0){
  229. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateTaskStatusImpl")("UpdateTaskStatus update fail: upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
  230. return false;//更新失败
  231. }else if(isUpdate==1){
  232. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateTaskStatusImpl")("UpdateTaskStatus update succ: upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
  233. return true;//更新成功
  234. }else if(isUpdate==2){
  235. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_TASK_STATUS_INVALID,CSimpleStringA::Format("UpdateTaskStatus update invalid,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData()).GetData());
  236. return true;//任务异常,更新成功
  237. }else{
  238. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateTaskStatusImpl")("UpdateTaskStatus update fail: upgradeTaskId=%s, ret=%d",m_fsm->m_currentTask.upgradeTaskId.GetData(),isUpdate);
  239. return false;//更新失败
  240. }
  241. }else{
  242. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateTaskStatusImpl")("UpdateTaskStatus update fail: [data] is not exist ,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
  243. return false;//更新失败
  244. }
  245. }else{
  246. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpdateTaskStatusImpl")("UpdateTaskStatus update fail: [success] is false,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
  247. return false;//更新失败
  248. }
  249. }
  250. };
  251. //查询当前任务
  252. struct QueryCurrTask : public ITaskSp{
  253. CUpgradeTaskFSM* m_fsm;
  254. explicit QueryCurrTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
  255. void Process(){
  256. LOG_FUNCTION();
  257. //根据任务ID查询任务当前的策略。
  258. IHttpFunc* client;
  259. client = create_http(m_fsm->HttpsLogCallBack);
  260. bool isSendSucc=false;//查询是否成功标志
  261. bool isTask_valid=false;//任务是否有效
  262. if(QueryCurrTaskImpl(client,isTask_valid)){
  263. isSendSucc = true;
  264. }else{
  265. isSendSucc = false;
  266. }
  267. client->Destory();
  268. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryCurrTaskEvent(isSendSucc,isTask_valid));//返回处理结果
  269. }
  270. bool QueryCurrTaskImpl(IHttpFunc* client,bool &isValid){
  271. HttpStruct::QueryCurrTaskReq qTempReq;
  272. HttpStruct::QueryCurrTaskRet qTempRet;
  273. CSystemStaticInfo info;
  274. ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  275. if (rc != Error_Succeed)
  276. {
  277. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryCurrTaskImpl")("QueryNewTask get CSystemStaticInfo fail");
  278. return false;
  279. }
  280. //机器版本
  281. CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
  282. //框架版本
  283. CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
  284. // OS版本
  285. #ifdef RVC_OS_WIN
  286. OSVERSIONINFO osvi;
  287. ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
  288. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  289. GetVersionEx(&osvi);
  290. CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d",osvi.dwMajorVersion,osvi.dwMinorVersion,osvi.dwBuildNumber);
  291. #else
  292. DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
  293. struct utsname kernel_info;
  294. int ret = uname(&kernel_info);
  295. if (ret == 0) {
  296. int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
  297. }
  298. else {
  299. Dbg("get linux kernel version fail: %s", strerror(errno));
  300. }
  301. CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
  302. #endif
  303. Json::Value rootReq;
  304. Json::FastWriter writer;
  305. rootReq["terminal_no"] = info.strTerminalID.GetData();
  306. rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
  307. rootReq["machine_type"] = info.strMachineType.GetData();
  308. rootReq["software_version"] = strInstallVersion.GetData();
  309. rootReq["os_version"] = strOSVersion.GetData();
  310. rootReq["machine_version"] = strMachineVersion.GetData();
  311. string jsonReq = writer.write(rootReq);
  312. qTempReq.m_reqStr = jsonReq;//请求参数
  313. qTempReq.m_url=m_fsm->m_centerUrl.queryCurrTaskUrl;//访问地址
  314. //打印发送请求
  315. if(m_fsm->m_PrintHttpLog){
  316. qTempReq.m_printDbg = true;
  317. }
  318. if(!client->Post(qTempReq, qTempRet)){
  319. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask http req fail,url=%s, err=%s",qTempReq.m_url.c_str(),qTempRet.m_errMsg.c_str()).GetData());
  320. return false;//失败
  321. }
  322. //打印回应报文
  323. if(m_fsm->m_PrintHttpLog){
  324. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryCurrTaskImpl")("qTempRet=%s",qTempRet.m_retStr.c_str());
  325. }
  326. Json::Reader reader;
  327. Json::Value rootRet;
  328. if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  329. {
  330. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask parse resp is fail,url=%s",qTempReq.m_url.c_str()).GetData());
  331. return false;//失败
  332. }
  333. bool isSucc = rootRet["success"].asBool();
  334. if(isSucc){
  335. if(rootRet.isMember("data")){
  336. if(rootRet["data"]["task_status"].asBool()){
  337. isValid = true;//任务有效
  338. if(!ParamCheck(rootRet)){
  339. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask paramCheck is fail, retry once again ,url=%s",qTempReq.m_url.c_str()).GetData());
  340. return false;//查询失败 升级任务参数效验失败,无法进行升级
  341. }else{
  342. CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
  343. if(m_fsm->m_currentTask.pack_name!=packNameStr){
  344. //异常情况
  345. CSimpleStringA errmsg = CSimpleStringA::Format("runinfo packName[%s] is not equal server packName[%s]",m_fsm->m_currentTask.pack_name.GetData(),packNameStr.GetData());
  346. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_PACKNAME_NOT_EQUAL, errmsg.GetData());
  347. }
  348. m_fsm->m_currentTask.pack_name= packNameStr;//用最新的包名进行后面的安装和下载
  349. m_fsm->m_currentTask.file_path = rootRet["data"]["file_path"].asString().c_str();
  350. m_fsm->m_currentTask.download_url = rootRet["data"]["download_url"].asString().c_str();
  351. m_fsm->m_currentTask.pack_hash = rootRet["data"]["pack_hash"].asString().c_str();
  352. m_fsm->m_currentTask.pack_length = (long)rootRet["data"]["pack_length"].asInt();
  353. m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
  354. m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
  355. m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
  356. //解析step json
  357. if(!ParseInstallStep(rootRet)){
  358. m_fsm->ClearInstallStep();
  359. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask ParseInstallStep is fail, retry once again ,url=%s",qTempReq.m_url.c_str()).GetData());
  360. return false;//解析安装步骤失败
  361. }
  362. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryCurrTaskImpl")("current task id =%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
  363. return true;//查询成功
  364. }
  365. }else{
  366. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryCurrTaskImpl")("QueryCurrTask query task is invalid, taskid=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
  367. isValid = false;//任务无效
  368. return true;//查询成功
  369. }
  370. }else{
  371. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask return task [data] is null ,url=%s",qTempReq.m_url.c_str()).GetData());
  372. return false;//查询失败
  373. }
  374. }else{
  375. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask [success] is false ,url=%s",qTempReq.m_url.c_str()).GetData());
  376. return false;//查询失败
  377. }
  378. }
  379. bool ParamCheck(Json::Value rootRet){
  380. CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
  381. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [pack_name] is %s",packNameStr.GetData());
  382. if(packNameStr.IsNullOrEmpty()){
  383. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [pack_name] is null");
  384. return false;
  385. }
  386. CSimpleStringA filePathStr = rootRet["data"]["file_path"].asString().c_str();
  387. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [file_path] is %s",filePathStr.GetData());
  388. if(filePathStr.IsNullOrEmpty()){
  389. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [file_path] is null");
  390. return false;
  391. }
  392. CSimpleStringA downloadUrlStr = rootRet["data"]["download_url"].asString().c_str();
  393. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [download_url] is %s",downloadUrlStr.GetData());
  394. if(downloadUrlStr.IsNullOrEmpty()){
  395. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [download_url] is null");
  396. return false;
  397. }
  398. CSimpleStringA packHashStr = rootRet["data"]["pack_hash"].asString().c_str();
  399. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [pack_hash] is %s",packHashStr.GetData());
  400. if(packHashStr.IsNullOrEmpty()){
  401. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [pack_hash] is null");
  402. return false;
  403. }
  404. long packLengthLong = (long)rootRet["data"]["pack_length"].asInt();
  405. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [pack_length] is %d",packLengthLong);
  406. int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
  407. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [reboot_type] is %d",rebootTypeInt);
  408. if(rebootTypeInt!=1 && rebootTypeInt!=2 && rebootTypeInt!=0){
  409. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [reboot_type] is invalid ,reboot_type=%d",rebootTypeInt);
  410. return false;
  411. }
  412. CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
  413. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [pack_version] is %s",packVersionStr.GetData());
  414. if(!packVersionStr.IsNullOrEmpty()){
  415. int rebootType = rootRet["data"]["reboot_type"].asInt();
  416. if(rebootType == 1 || rebootType == 2){
  417. return true;
  418. }else{
  419. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryCurrTask paramCheck [pack_version] is not null ,[reboot_type] is not equal 1 or 2");
  420. return false;
  421. }
  422. }
  423. return true;
  424. }
  425. bool ParseInstallStep(Json::Value rootRet){
  426. //清理以前的遗留的安装步骤
  427. m_fsm->ClearInstallStep();
  428. string cmdstr = rootRet["data"]["cmd"].asString();
  429. if(cmdstr.empty()){
  430. return true;//为空则直接不解析
  431. }
  432. Json::Reader reader;
  433. Json::Value InstallRet;
  434. if (!reader.parse(cmdstr, InstallRet, false))
  435. {
  436. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask parse cmd fail,cmdstr=%s",cmdstr.c_str()).GetData());
  437. return false;//解析失败
  438. }
  439. //install_step
  440. for(int i=0;i<InstallRet.size();i++){
  441. if(!InstallRet[i]["seq"].isInt()){
  442. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][seq] is not int");
  443. return false;
  444. }
  445. int stepSeq = InstallRet[i]["seq"].asInt();
  446. if(!InstallRet[i]["cmdType"].isString()&&!InstallRet[i]["cmdType"].isNull()){
  447. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][cmdType] is not string");
  448. return false;
  449. }
  450. CSimpleStringA cmdType = InstallRet[i]["cmdType"].asString().c_str();
  451. if(cmdType.IsNullOrEmpty()){
  452. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][cmdType] is null");
  453. return false;
  454. }
  455. if(!InstallRet[i]["cmdFail"].isInt()){
  456. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][cmdFail] is not int");
  457. return false;
  458. }
  459. int cmdFail = InstallRet[i]["cmdFail"].asInt();
  460. if(!InstallRet[i]["srcPathType"].isString()&&!InstallRet[i]["srcPathType"].isNull()){
  461. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][srcPathType] is not string");
  462. return false;
  463. }
  464. CSimpleStringA srcPathType = InstallRet[i]["srcPathType"].asString().c_str();
  465. if(cmdType=="Copy"){
  466. //复制指令时,不为空
  467. if(srcPathType.IsNullOrEmpty()){
  468. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][srcPathType] is null");
  469. return false;
  470. }
  471. }
  472. if(!InstallRet[i]["srcPath"].isString()&&!InstallRet[i]["srcPath"].isNull()){
  473. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][srcPath] is not string");
  474. return false;
  475. }
  476. CSimpleStringA srcPath = InstallRet[i]["srcPath"].asString().c_str();
  477. if(cmdType=="Copy"){
  478. //复制指令时,不为空
  479. if(srcPath.IsNullOrEmpty()){
  480. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][srcPath] is null");
  481. return false;
  482. }
  483. }
  484. if(!InstallRet[i]["dstPathType"].isString()&&!InstallRet[i]["dstPathType"].isNull()){
  485. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][dstPathType] is not string");
  486. return false;
  487. }
  488. CSimpleStringA dstPathType = InstallRet[i]["dstPathType"].asString().c_str();
  489. if(cmdType=="Copy"||cmdType=="Delete"||cmdType=="Run"){
  490. if(dstPathType.IsNullOrEmpty()){
  491. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][dstPathType] is null");
  492. return false;
  493. }
  494. }
  495. if(!InstallRet[i]["dstPath"].isString()&&!InstallRet[i]["dstPath"].isNull()){
  496. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][dstPath] is not string");
  497. return false;
  498. }
  499. CSimpleStringA dstPath = InstallRet[i]["dstPath"].asString().c_str();
  500. if(cmdType=="Delete"||cmdType=="Run"){
  501. if(dstPath.IsNullOrEmpty()){
  502. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryCurrTask ParseInstallStep [cmd][dstPath] is null");
  503. return false;
  504. }
  505. }
  506. CUpgradeTaskFSM::CInstallStep* iStep= new CUpgradeTaskFSM::CInstallStep();
  507. iStep->stepSeq = stepSeq;
  508. iStep->cmdType = cmdType;
  509. iStep->cmdFail = cmdFail;
  510. iStep->srcPathType = srcPathType;
  511. iStep->srcPath = srcPath;
  512. iStep->dstPathType =dstPathType;
  513. iStep->dstPath =dstPath;
  514. m_fsm->m_currentTask.install_step.push(iStep);//加入队尾
  515. }
  516. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("install cmd size = %d",InstallRet.size());
  517. return true;
  518. }
  519. };
  520. //预查询新任务
  521. struct QueryNewPreTask : public ITaskSp{
  522. CUpgradeTaskFSM* m_fsm;
  523. explicit QueryNewPreTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
  524. void Process(){
  525. //LOG_FUNCTION();
  526. IHttpFunc* client;
  527. client = create_http(m_fsm->HttpsLogCallBack);
  528. //查询新任务
  529. bool isSendSucc=false;////查询是否成功标志
  530. if(QueryNewPreTaskImpl(client)){
  531. isSendSucc = true;
  532. }else{
  533. isSendSucc = false;
  534. }
  535. client->Destory();
  536. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryNewPreTaskEvent(isSendSucc));//返回处理结果
  537. }
  538. bool QueryNewPreTaskImpl(IHttpFunc* client){
  539. HttpStruct::QueryNewTaskReq qTempReq;
  540. HttpStruct::QueryNewTaskRet qTempRet;
  541. CSystemStaticInfo info;
  542. ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  543. if (rc != Error_Succeed)
  544. {
  545. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryNewPreTaskImpl")("QueryNewPreTask get CSystemStaticInfo fail");
  546. return false;
  547. }
  548. //机器版本
  549. CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
  550. //框架版本
  551. CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
  552. // OS版本
  553. #ifdef RVC_OS_WIN
  554. OSVERSIONINFO osvi;
  555. ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
  556. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  557. GetVersionEx(&osvi);
  558. CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber);
  559. #else
  560. DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
  561. struct utsname kernel_info;
  562. int ret = uname(&kernel_info);
  563. if (ret == 0) {
  564. int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
  565. }
  566. else {
  567. Dbg("get linux kernel version fail: %s", strerror(errno));
  568. }
  569. CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
  570. #endif
  571. Json::Value rootReq;
  572. Json::FastWriter writer;
  573. rootReq["terminal_no"] = info.strTerminalID.GetData();
  574. rootReq["machine_type"] = info.strMachineType.GetData();
  575. rootReq["software_version"] = strInstallVersion.GetData();
  576. rootReq["os_version"] = strOSVersion.GetData();
  577. rootReq["machine_version"] = strMachineVersion.GetData();
  578. //预查询判断加入查询何种任务。
  579. if (m_fsm->isTerminalInstall()) {
  580. rootReq["task_type"] = "I";//安装任务
  581. }
  582. else {
  583. rootReq["task_type"] = "U";//升级任务
  584. }
  585. #ifdef RVC_OS_WIN
  586. rootReq["system_type"] = "W";//表示是windows类型的机器
  587. #else
  588. rootReq["system_type"] = "L";//表示是uos类型的机器
  589. #endif
  590. string jsonReq = writer.write(rootReq);
  591. qTempReq.m_reqStr = jsonReq;//请求参数
  592. qTempReq.m_url=m_fsm->m_centerUrl.queryPreTaskUrl;//访问地址
  593. //打印发送请求
  594. if(m_fsm->m_PrintHttpLog){
  595. qTempReq.m_printDbg = true;
  596. }
  597. if(!client->Post(qTempReq, qTempRet)){
  598. if (qTempRet.m_sysCode == 6) {
  599. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5651")("终端查询任务域名解析失败");
  600. }else if(qTempRet.m_sysCode == 28){
  601. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5652")("终端查询任务连接总行服务超时");
  602. }else {
  603. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5653")("终端查询任务失败:%s", qTempRet.m_errMsg.c_str());
  604. }
  605. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_PRE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewPreTask http req fail,url=%s, err=%s",qTempReq.m_url.c_str(),qTempRet.m_errMsg.c_str()).GetData());
  606. return false;//失败
  607. }
  608. //打印回应报文
  609. if(m_fsm->m_PrintHttpLog){
  610. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryNewPreTaskImpl")("qTempRet=%s",qTempRet.m_retStr.c_str());
  611. }
  612. Json::Reader reader;
  613. Json::Value rootRet;
  614. if (!reader.parse(qTempRet.m_retStr, rootRet, false)){
  615. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_PRE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewPreTask parse resp is fail,url=%s",qTempReq.m_url.c_str()).GetData());
  616. return false;//失败
  617. }
  618. bool isSucc = rootRet["success"].asBool();
  619. if(isSucc){
  620. if(rootRet.isMember("data")){
  621. //解析任务,可能不存在任务
  622. if(rootRet["data"]["task_id"].asString()!=""){
  623. m_fsm->m_strPreTaskId = rootRet["data"]["task_id"].asString().c_str();
  624. int need_hash = rootRet["data"]["need_hash"].asInt();
  625. if(need_hash==0){
  626. m_fsm->m_bNeedHash = false;
  627. }else{
  628. m_fsm->m_bNeedHash = true;
  629. }
  630. return true;//查询成功
  631. }else{
  632. //无任务
  633. m_fsm->m_strPreTaskId = "";
  634. m_fsm->m_bNeedHash =false;
  635. return true;//查询成功
  636. }
  637. }else{
  638. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_PRE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewPreTask return [data] is null, retry once again ,url=%s",qTempReq.m_url.c_str()).GetData());
  639. return false;//查询失败
  640. }
  641. }else{
  642. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_PRE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewPreTask [success] is false, retry once again ,url=%s",qTempReq.m_url.c_str()).GetData());
  643. return false;//查询失败
  644. }
  645. }
  646. };
  647. //继续查询新任务
  648. struct QueryNewContinueTask : public ITaskSp{
  649. CUpgradeTaskFSM* m_fsm;
  650. explicit QueryNewContinueTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
  651. void Process(){
  652. LOG_FUNCTION();
  653. IHttpFunc* client;
  654. client = create_http(m_fsm->HttpsLogCallBack);
  655. //查询新任务
  656. int retParm=QueryNewContinueTaskImpl(client);
  657. client->Destory();
  658. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryNewContinueTaskEvent(retParm));//返回处理结果
  659. }
  660. // 0:重试 1:成功 2:跳出
  661. int QueryNewContinueTaskImpl(IHttpFunc* client){
  662. HttpStruct::QueryNewTaskReq qTempReq;
  663. HttpStruct::QueryNewTaskRet qTempRet;
  664. CSystemStaticInfo info;
  665. ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  666. if (rc != Error_Succeed)
  667. {
  668. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryNewContinueTaskImpl")("QueryNewContinueTask get CSystemStaticInfo fail");
  669. return 0;//查询失败,继续查询
  670. }
  671. //机器版本
  672. CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
  673. //框架版本
  674. CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
  675. // OS版本
  676. #ifdef RVC_OS_WIN
  677. OSVERSIONINFO osvi;
  678. ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
  679. osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  680. GetVersionEx(&osvi);
  681. CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber);
  682. #else
  683. DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
  684. struct utsname kernel_info;
  685. int ret = uname(&kernel_info);
  686. if (ret == 0) {
  687. int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
  688. }
  689. else {
  690. Dbg("get linux kernel version fail: %s", strerror(errno));
  691. }
  692. CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
  693. #endif
  694. Json::Value rootReq;
  695. Json::FastWriter writer;
  696. rootReq["terminal_no"] = info.strTerminalID.GetData();
  697. rootReq["task_id"] = m_fsm->m_strPreTaskId.GetData();
  698. rootReq["machine_type"] = info.strMachineType.GetData();
  699. rootReq["software_version"] = strInstallVersion.GetData();
  700. rootReq["os_version"] = strOSVersion.GetData();
  701. rootReq["machine_version"] = strMachineVersion.GetData();
  702. #ifdef RVC_OS_WIN
  703. rootReq["system_type"] = "W";//表示是windows类型的机器
  704. #else
  705. rootReq["system_type"] = "L";//表示是uos类型的机器
  706. #endif
  707. if(m_fsm->m_bNeedHash&&m_fsm->isSendHash){
  708. //是否发送hash码并且发送成功了
  709. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryNewContinueTaskImpl")("QueryNewContinueTask with hash");
  710. rootReq["list_hash"] = m_fsm->m_fileSM3ListHash.GetData();
  711. }else{
  712. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryNewContinueTaskImpl")("QueryNewContinueTask with no hash");
  713. rootReq["list_hash"] = "";
  714. }
  715. string jsonReq = writer.write(rootReq);
  716. qTempReq.m_reqStr = jsonReq;//请求参数
  717. qTempReq.m_url=m_fsm->m_centerUrl.queryContinueTaskUrl;//访问地址
  718. //打印发送请求
  719. if(m_fsm->m_PrintHttpLog){
  720. qTempReq.m_printDbg = true;
  721. }
  722. if(!client->Post(qTempReq, qTempRet)){
  723. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask http req fail,url=%s, err=%s",qTempReq.m_url.c_str(),qTempRet.m_errMsg.c_str()).GetData());
  724. return 0;//查询失败,继续查询
  725. }
  726. //打印回应报文
  727. if(m_fsm->m_PrintHttpLog){
  728. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryNewContinueTaskImpl")("qTempRet=%s",qTempRet.m_retStr.c_str());
  729. }
  730. Json::Reader reader;
  731. Json::Value rootRet;
  732. if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  733. {
  734. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask parse resp is fail,url=%s",qTempReq.m_url.c_str()).GetData());
  735. return 0;//查询失败,继续查询
  736. }
  737. bool isSucc = rootRet["success"].asBool();
  738. if(isSucc){
  739. if(rootRet.isMember("data")){
  740. //解析任务,可能不存在任务,task_id为空,则表示无此任务。
  741. if(rootRet["data"]["task_id"].asString()!=""){
  742. //task_status 0-无效 1-有效 2-对比不通过 3-hash内容为空
  743. int task_status = rootRet["data"]["task_status"].asInt();
  744. if(task_status ==1){
  745. //pack_status 0-准备中 1-已就绪
  746. int status = rootRet["data"]["pack_status"].asInt();
  747. if(status == 1){
  748. if(!ParamCheck(rootRet)){
  749. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_ERR,CSimpleStringA::Format("QueryNewContinueTask paramCheck is fail, check out server exception ,url=%s",qTempReq.m_url.c_str()).GetData());
  750. return 0;//查询失败 升级任务参数效验失败,告警码不同
  751. }else{
  752. m_fsm->m_currentTask.upgradeTaskId = rootRet["data"]["task_id"].asString().c_str();
  753. m_fsm->m_currentTask.pack_name = rootRet["data"]["pack_name"].asString().c_str();
  754. m_fsm->m_currentTask.file_path = rootRet["data"]["file_path"].asString().c_str();
  755. m_fsm->m_currentTask.download_url = rootRet["data"]["download_url"].asString().c_str();
  756. m_fsm->m_currentTask.pack_hash = rootRet["data"]["pack_hash"].asString().c_str();
  757. m_fsm->m_currentTask.pack_length = (long)rootRet["data"]["pack_length"].asInt();
  758. m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
  759. m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
  760. m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
  761. //解析step json
  762. if(!ParseInstallStep(rootRet)){
  763. m_fsm->ClearInstallStep();
  764. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_ERR,CSimpleStringA::Format("QueryNewContinueTask ParseInstallStep is fail, check out server exception ,url=%s",qTempReq.m_url.c_str()).GetData());
  765. return 0;//查询失败 解析安装步骤失败,告警码不同
  766. }
  767. m_fsm->m_currentTask.createTaskVersion = m_fsm->m_currentVersion.ToString();//新策略,查询到包后,用当前版本值赋值
  768. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryNewContinueTaskImpl")("new task id =%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
  769. return 1;//查询成功
  770. }
  771. }else{
  772. //任务未准备好
  773. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryNewContinueTaskImpl")("QueryNewContinueTask query pack is not create ,please next query,status=%d",status);
  774. m_fsm->m_currentTask.upgradeTaskId = "";
  775. return 0;//查询成功,继续查询
  776. }
  777. }else{
  778. //任务状态无效,对比不通过,hash内容为空
  779. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask query fail ,task_status=%d",task_status).GetData());
  780. return 2;//查询成功,但任务不再,跳出来
  781. }
  782. }else{
  783. //返回任务为空
  784. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask return [task id] is null").GetData());
  785. return 2;//查询成功,但任务不再,跳出来
  786. }
  787. }else{
  788. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_ERR,CSimpleStringA::Format("QueryNewContinueTask return [data] is null, check out server exception ,url=%s",qTempReq.m_url.c_str()).GetData());
  789. return 0;//查询失败,继续查询,告警码不同
  790. }
  791. }else{
  792. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask [success] is false, retry once again ,url=%s",qTempReq.m_url.c_str()).GetData());
  793. return 0;//查询失败,继续查询
  794. }
  795. }
  796. bool ParamCheck(Json::Value rootRet){
  797. CSimpleStringA upgradeTaskIdStr = rootRet["data"]["task_id"].asString().c_str();
  798. if(upgradeTaskIdStr.IsNullOrEmpty()){
  799. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryNewContinueTask paramCheck [task_id] is null");
  800. return false;
  801. }
  802. CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
  803. if(packNameStr.IsNullOrEmpty()){
  804. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryNewContinueTask paramCheck [pack_name] is null");
  805. return false;
  806. }
  807. CSimpleStringA filePathStr = rootRet["data"]["file_path"].asString().c_str();
  808. if(filePathStr.IsNullOrEmpty()){
  809. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryNewContinueTask paramCheck [file_path] is null");
  810. return false;
  811. }
  812. CSimpleStringA downloadUrlStr = rootRet["data"]["download_url"].asString().c_str();
  813. if(downloadUrlStr.IsNullOrEmpty()){
  814. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryNewContinueTask paramCheck [download_url] is null");
  815. return false;
  816. }
  817. CSimpleStringA packHashStr = rootRet["data"]["pack_hash"].asString().c_str();
  818. if(packHashStr.IsNullOrEmpty()){
  819. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryNewContinueTask paramCheck [pack_hash] is null");
  820. return false;
  821. }
  822. long packLengthStr = (long)rootRet["data"]["pack_length"].asInt();
  823. int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
  824. if(rebootTypeInt!=1 && rebootTypeInt!=2 && rebootTypeInt!=0){
  825. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryNewContinueTask paramCheck [reboot_type] is invalid ,reboot_type=%d",rebootTypeInt);
  826. return false;
  827. }
  828. CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
  829. if(!packVersionStr.IsNullOrEmpty()){
  830. int rebootType = rootRet["data"]["reboot_type"].asInt();
  831. if(rebootType == 1 || rebootType == 2){
  832. return true;
  833. }else{
  834. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParamCheck")("QueryNewContinueTask paramCheck [pack_version] is not null ,[reboot_type] is not equal 1 or 2");
  835. return false;
  836. }
  837. }
  838. return true;
  839. }
  840. bool ParseInstallStep(Json::Value rootRet){
  841. //清理以前的遗留的安装步骤
  842. m_fsm->ClearInstallStep();
  843. string cmdstr = rootRet["data"]["cmd"].asString();
  844. if(cmdstr.empty()){
  845. return true;//为空则直接不解析
  846. }
  847. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("cmdstr =%s",cmdstr.c_str());
  848. Json::Reader reader;
  849. Json::Value InstallRet;
  850. if (!reader.parse(cmdstr, InstallRet, false))
  851. {
  852. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask parse cmd fail,cmdstr=%s",cmdstr.c_str()).GetData());
  853. return false;//解析失败
  854. }
  855. for(int i=0;i<InstallRet.size();i++){
  856. if(!InstallRet[i]["seq"].isInt()){
  857. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][seq] is not int");
  858. return false;
  859. }
  860. int stepSeq = InstallRet[i]["seq"].asInt();
  861. if(!InstallRet[i]["cmdType"].isString()&&!InstallRet[i]["cmdType"].isNull()){
  862. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][cmdType] is not string");
  863. return false;
  864. }
  865. CSimpleStringA cmdType = InstallRet[i]["cmdType"].asString().c_str();
  866. if(cmdType.IsNullOrEmpty()){
  867. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][cmdType] is null");
  868. return false;
  869. }
  870. if(!InstallRet[i]["cmdFail"].isInt()){
  871. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][cmdFail] is not int");
  872. return false;
  873. }
  874. int cmdFail = InstallRet[i]["cmdFail"].asInt();
  875. if(!InstallRet[i]["srcPathType"].isString()&&!InstallRet[i]["srcPathType"].isNull()){
  876. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][srcPathType] is not string");
  877. return false;
  878. }
  879. CSimpleStringA srcPathType = InstallRet[i]["srcPathType"].asString().c_str();
  880. if(cmdType=="Copy"){
  881. //复制指令时,不为空
  882. if(srcPathType.IsNullOrEmpty()){
  883. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][srcPathType] is null");
  884. return false;
  885. }
  886. }
  887. if(!InstallRet[i]["srcPath"].isString()&&!InstallRet[i]["srcPath"].isNull()){
  888. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][srcPath] is not string");
  889. return false;
  890. }
  891. CSimpleStringA srcPath = InstallRet[i]["srcPath"].asString().c_str();
  892. if(cmdType=="Copy"){
  893. //复制指令时,不为空
  894. if(srcPath.IsNullOrEmpty()){
  895. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][srcPath] is null");
  896. return false;
  897. }
  898. }
  899. if(!InstallRet[i]["dstPathType"].isString()&&!InstallRet[i]["dstPathType"].isNull()){
  900. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][dstPathType] is not string");
  901. return false;
  902. }
  903. CSimpleStringA dstPathType = InstallRet[i]["dstPathType"].asString().c_str();
  904. if(cmdType=="Copy"||cmdType=="Delete"||cmdType=="Run"){
  905. if(dstPathType.IsNullOrEmpty()){
  906. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][dstPathType] is null");
  907. return false;
  908. }
  909. }
  910. if(!InstallRet[i]["dstPath"].isString()&&!InstallRet[i]["dstPath"].isNull()){
  911. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][dstPath] is not string");
  912. return false;
  913. }
  914. CSimpleStringA dstPath = InstallRet[i]["dstPath"].asString().c_str();
  915. if(cmdType=="Delete"||cmdType=="Run"){
  916. if(dstPath.IsNullOrEmpty()){
  917. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("QueryNewContinueTask ParseInstallStep [cmd][dstPath] is null");
  918. return false;
  919. }
  920. }
  921. CUpgradeTaskFSM::CInstallStep* iStep= new CUpgradeTaskFSM::CInstallStep();
  922. iStep->stepSeq = stepSeq;
  923. iStep->cmdType = cmdType;
  924. iStep->cmdFail = cmdFail;
  925. iStep->srcPathType = srcPathType;
  926. iStep->srcPath = srcPath;
  927. iStep->dstPathType =dstPathType;
  928. iStep->dstPath =dstPath;
  929. m_fsm->m_currentTask.install_step.push(iStep);//加入队尾
  930. }
  931. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ParseInstallStep")("install cmd size = %d",InstallRet.size());
  932. return true;
  933. }
  934. };
  935. //查询任务状态
  936. struct QueryTaskStatus : public ITaskSp{
  937. CUpgradeTaskFSM* m_fsm;
  938. explicit QueryTaskStatus(CUpgradeTaskFSM* f) : m_fsm(f) {}
  939. void Process(){
  940. //LOG_FUNCTION();
  941. IHttpFunc* client;
  942. client = create_http(m_fsm->HttpsLogCallBack);
  943. //查询新任务
  944. bool isSendSucc=false;////查询是否成功标志
  945. bool isValid=false;//任务是否有效
  946. if(QueryTaskStatusImpl(client,isValid)){
  947. isSendSucc = true;
  948. }else{
  949. isSendSucc = false;
  950. }
  951. client->Destory();
  952. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryTaskStatusEvent(isSendSucc,isValid));//返回处理结果
  953. }
  954. bool QueryTaskStatusImpl(IHttpFunc* client,bool &isValid){
  955. HttpStruct::QueryCurrTaskReq qTempReq;
  956. HttpStruct::QueryCurrTaskRet qTempRet;
  957. CSystemStaticInfo info;
  958. ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  959. if (rc != Error_Succeed)
  960. {
  961. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryTaskStatusImpl")("QueryTaskStatus get CSystemStaticInfo fail");
  962. return false;
  963. }
  964. Json::Value rootReq;
  965. Json::FastWriter writer;
  966. rootReq["terminal_no"] = info.strTerminalID.GetData();
  967. rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
  968. string jsonReq = writer.write(rootReq);
  969. qTempReq.m_reqStr = jsonReq;//请求参数
  970. qTempReq.m_url=m_fsm->m_centerUrl.queryTaskStatus;//访问地址
  971. //打印发送请求
  972. if(m_fsm->m_PrintHttpLog){
  973. qTempReq.m_printDbg = true;
  974. }
  975. if(!client->Post(qTempReq, qTempRet)){
  976. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_TASK_STATUS_FAIL,CSimpleStringA::Format("QueryTaskStatus http req fail,upgradeTaskId=%s, url=%s, err=%s",m_fsm->m_currentTask.upgradeTaskId.GetData(), qTempReq.m_url.c_str(), qTempRet.m_errMsg.c_str()).GetData());
  977. return false;//失败
  978. }
  979. //打印回应报文
  980. if(m_fsm->m_PrintHttpLog){
  981. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryTaskStatusImpl")("qTempRet=%s",qTempRet.m_retStr.c_str());
  982. }
  983. Json::Reader reader;
  984. Json::Value rootRet;
  985. if (!reader.parse(qTempRet.m_retStr, rootRet, false))
  986. {
  987. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_TASK_STATUS_FAIL,CSimpleStringA::Format("QueryTaskStatus parse resp is fail,upgradeTaskId=%s, url=%s",m_fsm->m_currentTask.upgradeTaskId.GetData(), qTempReq.m_url.c_str()).GetData());
  988. return false;//失败
  989. }
  990. bool isSucc = rootRet["success"].asBool();
  991. if(isSucc){
  992. if(rootRet.isMember("data")){
  993. isValid =rootRet["data"].asBool();
  994. return true;//查询成功
  995. }else{
  996. return false;//查询失败
  997. }
  998. }else{
  999. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("QueryTaskStatusImpl")("QueryTaskStatus [success] is false");
  1000. return false;//查询失败
  1001. }
  1002. }
  1003. };
  1004. //下载升级包
  1005. struct DownloadPackTask : public ITaskSp{
  1006. CUpgradeTaskFSM* m_fsm;
  1007. explicit DownloadPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
  1008. void Process(){
  1009. LOG_FUNCTION();
  1010. //下载升级包
  1011. if(m_fsm->m_currentTask.pack_name.IsNullOrEmpty()||m_fsm->m_currentTask.pack_hash.IsNullOrEmpty()){
  1012. string errMsg = CSimpleStringA::Format("DownloadPackTask fail,pack_name or pack_hash is null,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData()).GetData();
  1013. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.c_str());
  1014. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskFailEvent(errMsg));//下载失败,返回结果,这种情况下无法继续下载
  1015. return;
  1016. }
  1017. CSimpleStringA dPackName = m_fsm->m_currentTask.pack_name;
  1018. CSimpleStringA dPakchash = m_fsm->m_currentTask.pack_hash;
  1019. long lpacklen = m_fsm->m_currentTask.pack_length;
  1020. //判断是否已经下载完成
  1021. CSimpleStringA strPath;
  1022. ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetPath("Downloads", strPath);
  1023. if(Error_Succeed != rc){
  1024. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("DownloadPackTask get Downloads path fail,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData()).GetData());
  1025. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(false));//返回失败结果
  1026. return;
  1027. }
  1028. CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strPath.GetData(), dPackName.GetData());
  1029. if(m_fsm->IsPackDownloaded(strZipFile.GetData(),dPakchash.GetData(),lpacklen)){
  1030. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPackTask")("download pack [%s] sm3[%s] is exist ,do not download.", strZipFile.GetData(),dPakchash.GetData());
  1031. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(true));//下载完成,返回成功结果
  1032. return;
  1033. }else{
  1034. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPackTask")("download pack [%s] sm3[%s] is not exist ,prepare download.", strZipFile.GetData(),dPakchash.GetData());
  1035. }
  1036. //提前判断是否任务取消
  1037. if(m_fsm->m_bTaskCancel){
  1038. m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//取消下载任务,返回结果
  1039. return;
  1040. }
  1041. if(m_fsm->m_bDownloadIdle){
  1042. m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//下载中断,返回结果
  1043. return;
  1044. }
  1045. //接着下载未完成的升级包
  1046. IHttpFunc* client;
  1047. client = create_http(m_fsm->HttpsLogCallBack);
  1048. bool isDownloadSucc=false;//是否下载成功
  1049. CSimpleStringA errMsg ;//下载失败错误信息
  1050. int ret = DownloadPack(client,strZipFile.GetData(),dPakchash,errMsg);
  1051. if(ret==0){
  1052. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(false));//返回通讯失败结果
  1053. }else if(ret ==1){
  1054. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(true));//返回成功结果
  1055. }else if(ret ==2){
  1056. m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//下载中断,返回结果
  1057. }else if(ret ==3){
  1058. m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//取消下载任务,返回结果
  1059. }else if(ret ==4){
  1060. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskFailEvent(errMsg.GetData()));//下载失败,任务中止
  1061. }
  1062. client->Destory();
  1063. }
  1064. //返回值 0:下载通讯失败 1:下载成功 2:下载中断 3:任务取消 4:下载失败
  1065. int DownloadPack(IHttpFunc* client,const char* dPackPath,const char* dPackHash,CSimpleStringA &errMsg){
  1066. bool isDownloadSucc = false;
  1067. CSimpleStringA dPackPathTemp = CSimpleStringA::Format("%s%s",dPackPath,".tmp");//默认临时文件是.tmp后缀
  1068. long dPackTempLen = 0;
  1069. if(ExistsFileA(dPackPathTemp)){
  1070. if(!m_fsm->GetFileLength(dPackPathTemp.GetData(),dPackTempLen)){
  1071. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("%s get download temp pack fileLen is fail", dPackPathTemp.GetData()).GetData());
  1072. errMsg = "get download temp pack fileLen is fail";
  1073. return 4;//下载失败,计算临时文件长度失败
  1074. }
  1075. }
  1076. byte* content = new byte[m_fsm->m_newEachDownloadLen];
  1077. memset(content, 0, m_fsm->m_newEachDownloadLen);
  1078. bool isContinue = true;
  1079. while(isContinue){
  1080. if(m_fsm->m_bTaskCancel){
  1081. //任务取消
  1082. delete[] content;
  1083. return 3;
  1084. }
  1085. if(m_fsm->m_bDownloadIdle){
  1086. //状态中断
  1087. delete[] content;
  1088. return 2;
  1089. }
  1090. HttpStruct::DownloadPackTaskRet resp;
  1091. resp.bfinish= false;//默认是未下载完
  1092. resp.sm3 = "";//默认是空串
  1093. if(DownloadPackTaskImpl(client,dPackTempLen,content,resp)){
  1094. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPack")("download succ, %d , begin write %d",(int)resp.bfinish,dPackTempLen);
  1095. //成功通讯
  1096. if(!m_fsm->DownloadFileWrite(content,resp.content_length,dPackPathTemp)){
  1097. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("DownloadFileWrite write temp file fail,begin write=%d, write len=%d", dPackTempLen,resp.content_length).GetData());
  1098. errMsg = "DownloadFileWrite write temp file fail";
  1099. delete[] content;
  1100. return 4;//下载失败,写文件失败
  1101. }else{
  1102. m_fsm->DownloadProgress(dPackTempLen+resp.content_length,resp.origin_file_length);//广播下载进度
  1103. }
  1104. if(resp.bfinish){
  1105. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPack")("最后一次下载");
  1106. //最后一次
  1107. CSimpleStringA strMD5Val;
  1108. ErrorCodeEnum rc = m_fsm->SM3FileToStr(dPackPathTemp, strMD5Val,false);
  1109. if (Error_Succeed != rc)
  1110. {
  1111. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("%s get download temp pack sm3 fail ,error:%d", dPackPathTemp.GetData(), (int)rc).GetData());
  1112. errMsg = "get download temp pack sm3 fail";
  1113. delete[] content;
  1114. return 4;//下载失败,算hash失败
  1115. }
  1116. //不区分大小写比较文件hash
  1117. #ifdef RVC_OS_WIN
  1118. if(stricmp(strMD5Val.GetData(),resp.sm3.c_str())==0){
  1119. #else
  1120. if(strcmp(strMD5Val.GetData(),resp.sm3.c_str())==0){
  1121. #endif
  1122. //移动文件到正式目录
  1123. if(ExistsFileA(dPackPath)){
  1124. if(remove(dPackPath)==0){
  1125. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPack")("delete download old pack succ ", dPackPath);
  1126. if(rename(dPackPathTemp.GetData(),dPackPath)!=0){
  1127. #ifdef RVC_OS_WIN
  1128. errMsg = CSimpleStringA::Format("exist old file,remove temp file fail, error=%d",(int)GetLastError()).GetData();
  1129. #else
  1130. errMsg = CSimpleStringA::Format("exist old file,remove temp file fail, error=%d", errno).GetData();
  1131. #endif
  1132. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
  1133. delete[] content;
  1134. return 4;//下载失败,移动文件失败
  1135. }else{
  1136. delete[] content;
  1137. return 1;//成功返回
  1138. }
  1139. }else{
  1140. #ifdef RVC_OS_WIN
  1141. errMsg = CSimpleStringA::Format("delete download old pack fail ,error:%d",(int)GetLastError()).GetData();
  1142. #else
  1143. errMsg = CSimpleStringA::Format("delete download old pack fail ,error:%d", errno).GetData();
  1144. #endif
  1145. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
  1146. delete[] content;
  1147. return 4;//下载失败,删除旧文件失败
  1148. }
  1149. }else{
  1150. if(rename(dPackPathTemp.GetData(),dPackPath)!=0){
  1151. #ifdef RVC_OS_WIN
  1152. errMsg = CSimpleStringA::Format("not exist old file,remove temp file fail, error=%d",(int)GetLastError()).GetData();
  1153. #else
  1154. errMsg = CSimpleStringA::Format("not exist old file,remove temp file fail, error=%d", errno).GetData();
  1155. #endif
  1156. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
  1157. delete[] content;
  1158. return 4;//移动文件失败
  1159. }else{
  1160. delete[] content;
  1161. return 1;//成功返回
  1162. }
  1163. }
  1164. }else{
  1165. errMsg = CSimpleStringA::Format("download file sm3 is not equal,local file [%s],resp [%s]",strMD5Val.GetData(),resp.sm3.c_str()).GetData();
  1166. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("download file sm3 is not equal,local file [%s],resp [%s]",strMD5Val.GetData(),resp.sm3.c_str()).GetData());
  1167. //删除临时文件,重新下载
  1168. if(remove(dPackPathTemp.GetData())==0){
  1169. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPack")("delete download temp pack succ ,%s", dPackPathTemp.GetData());
  1170. }else{
  1171. #ifdef RVC_OS_WIN
  1172. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPack")("delete download temp pack fail ,%s error:%d", dPackPathTemp.GetData(), GetLastError());
  1173. #else
  1174. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPack")("delete download temp pack fail ,%s error:%d", dPackPathTemp.GetData(), errno);
  1175. #endif
  1176. }
  1177. delete[] content;
  1178. return 4;//下载失败,hash不对
  1179. }
  1180. }else{
  1181. if(resp.content_length==0){
  1182. errMsg = "DownloadFile server content_length = 0 ,bfinish = false ,DownloadFile server return param fail";
  1183. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"DownloadFile server content_length = 0 ,bfinish = false ,DownloadFile server return param fail");
  1184. delete[] content;
  1185. return 4;//传回零字节,但是又未结束,下载失败,等待一段时间下载
  1186. }
  1187. //继续下一次续传
  1188. dPackTempLen =dPackTempLen+resp.content_length;
  1189. memset(content, 0, m_fsm->m_newEachDownloadLen);
  1190. isContinue = true;
  1191. }
  1192. }else{
  1193. delete[] content;
  1194. return 0;//下载通讯失败,等待一段时间下载
  1195. }
  1196. }
  1197. }
  1198. bool DownloadPackTaskImpl(IHttpFunc* client,long downloaded_len,byte* respContent,HttpStruct::DownloadPackTaskRet &resp){
  1199. //注意传入参数和传出参数进行转码
  1200. CSystemStaticInfo info;
  1201. ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
  1202. if (rc != Error_Succeed)
  1203. {
  1204. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPackTaskImpl")("DownloadPackTask get CSystemStaticInfo fail");
  1205. return false;//失败
  1206. }
  1207. Json::Value rootReq;
  1208. Json::FastWriter writer;
  1209. rootReq["terminal_no"] = info.strTerminalID.GetData();
  1210. rootReq["pack_name"] = m_fsm->m_currentTask.pack_name.GetData();
  1211. rootReq["downloaded_length"] = downloaded_len;
  1212. rootReq["limit_length"] = m_fsm->m_newEachDownloadLen;
  1213. rootReq["file_path"] = m_fsm->m_currentTask.file_path.GetData();
  1214. string jsonReq = writer.write(rootReq);
  1215. CSimpleStringA downloadUrl = m_fsm->m_currentTask.download_url;
  1216. //转码
  1217. m_fsm->ConvertGBKToUtf8(jsonReq);
  1218. //打印发送请求
  1219. if(m_fsm->m_PrintHttpLog){
  1220. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPackTaskImpl")("jsonStr is %s",jsonReq.c_str());
  1221. }
  1222. long httpCode =0;
  1223. unordered_map<string, string> responseHeaders;
  1224. int time_out = DOWNLOAD_TIMEOUT;
  1225. fileContentArray content;
  1226. content.copyPtr = respContent;
  1227. content.maxLen = m_fsm->m_newEachDownloadLen;
  1228. int retlen = 0;
  1229. content.curLen = &retlen;
  1230. if(!client->DownloadFileBlock(downloadUrl.GetData(),jsonReq.c_str(), content,httpCode,responseHeaders,time_out)){
  1231. if (retlen > m_fsm->m_newEachDownloadLen) {
  1232. CSimpleStringA errMsg = CSimpleStringA::Format("retlen is over limit_length ,retlen= %d", retlen).GetData();
  1233. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL, CSimpleStringA::Format("DownloadPackTask http req fail, %s, url=%s", errMsg.GetData(), downloadUrl.GetData()).GetData());
  1234. }
  1235. else {
  1236. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL, CSimpleStringA::Format("DownloadPackTask http req fail,url=%s", downloadUrl.GetData()).GetData());
  1237. }
  1238. return false;//失败
  1239. }
  1240. //判断httpCode
  1241. if(httpCode!=200){
  1242. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("DownloadPackTask http req fail, url=%s, retHttpCode=%d",downloadUrl.GetData(),httpCode).GetData());
  1243. return false;//失败
  1244. }
  1245. //解析head值
  1246. unordered_map<string, string>::const_iterator iter = responseHeaders.find("Result");
  1247. if(iter==responseHeaders.end()){
  1248. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"resp head result is null");
  1249. return false;//无params 失败
  1250. }else{
  1251. string respStr = iter->second;
  1252. //转码:
  1253. m_fsm->ConvertUtf8ToGBK(respStr);
  1254. //打印回应报文
  1255. if(m_fsm->m_PrintHttpLog){
  1256. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadPackTaskImpl")("qTempRet Result=%s",respStr.c_str());
  1257. }
  1258. //解析json值
  1259. Json::Reader reader;
  1260. Json::Value rootRet;
  1261. if (!reader.parse(respStr, rootRet, false))
  1262. {
  1263. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"DownloadPackTask head params parse resp is fail");
  1264. return false;//解析失败
  1265. }
  1266. bool isSucc = rootRet["success"].asBool();
  1267. if(isSucc){
  1268. resp.content_length = (long)rootRet["content_length"].asInt();
  1269. resp.origin_file_length = (long)rootRet["origin_file_length"].asInt();
  1270. resp.bfinish = rootRet["finish"].asBool();//是否传送完毕
  1271. resp.sm3 = rootRet["sm3"].asString();//包hash码
  1272. return true;//查询成功
  1273. }else{
  1274. CSimpleStringA msg = rootRet["message"].asString().c_str();
  1275. if(msg.IsNullOrEmpty()){
  1276. msg = "";
  1277. }
  1278. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("DownloadPackTask [success] is false, err=%s",msg.GetData()).GetData());
  1279. return false;//查询失败
  1280. }
  1281. }
  1282. }
  1283. };
  1284. //停止播放广告和提示音
  1285. struct StopMediaPlayTask : public ITaskSp{
  1286. CUpgradeTaskFSM* m_fsm;
  1287. explicit StopMediaPlayTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
  1288. void Process(){
  1289. LOG_FUNCTION();
  1290. //判断是否需要停止广播和提示音
  1291. if(!m_fsm->m_currentTask.stop_media_play){
  1292. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(true));//返回处理结果
  1293. }else{
  1294. //停止广告、提示音播放
  1295. // 终端置为升级状态。1:升级状态,0:非升级状态。处于升级状态时调用播放接口不生效
  1296. ErrorCodeEnum rc = ((CUpgradeMgrEntity*)m_fsm->GetEntityBase())->NewStopMediaPlay();
  1297. if(rc==Error_Succeed){
  1298. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StopMediaPlayTask")("StopMediaPlayTask stop media play succ");
  1299. }else{
  1300. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StopMediaPlayTask")("StopMediaPlayTask stop media play fail");
  1301. //m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(false));//返回处理结果
  1302. }
  1303. // 终端置为升级状态。1:升级状态,0:非升级状态。处于升级状态时调用播放接口不生效
  1304. rc = m_fsm->GetEntityBase()->GetFunction()->SetSysVar("UpdateState", "1", false);
  1305. if(rc==Error_Succeed){
  1306. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StopMediaPlayTask")("StopMediaPlayTask set UpdateState to 1 succ");
  1307. }else{
  1308. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("StopMediaPlayTask")("StopMediaPlayTask set UpdateState to 1 fail");
  1309. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(false));//返回处理结果
  1310. return;
  1311. }
  1312. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(true));//返回处理结果
  1313. }
  1314. }
  1315. };
  1316. //解压安装包
  1317. struct UnzipPackTask : public ITaskSp{
  1318. CUpgradeTaskFSM* m_fsm;
  1319. explicit UnzipPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
  1320. void Process(){
  1321. LOG_FUNCTION();
  1322. //解压安装包
  1323. bool isUnzipSucc;//是否解压成功
  1324. if(m_fsm->UnzipPack(m_fsm->m_currentTask.pack_name.GetData())==Error_Succeed){
  1325. isUnzipSucc = true;
  1326. }else{
  1327. isUnzipSucc = false;
  1328. }
  1329. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::UnzipPackTaskEvent(isUnzipSucc));//返回处理结果
  1330. }
  1331. };
  1332. //升级包安装
  1333. struct InstallPackTask : public ITaskSp{
  1334. CUpgradeTaskFSM* m_fsm;
  1335. explicit InstallPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
  1336. void Process(){
  1337. LOG_FUNCTION();
  1338. //升级包安装
  1339. bool isInstallSucc=false;//是否安装成功
  1340. int failStatus=0;//安装失败状态:0:失败,1:成功,-1:未知
  1341. string packName = m_fsm->m_currentTask.pack_name.GetData();
  1342. CSimpleStringA errMsg ="";
  1343. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("InstallPackTask")("======begin ExecInstall======");
  1344. failStatus = m_fsm->ExecInstall(errMsg);
  1345. if(failStatus == 1){
  1346. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("InstallPackTask")("======end ExecInstall:succ======");
  1347. isInstallSucc =true;
  1348. }else{
  1349. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("InstallPackTask")("======end ExecInstall:fail======");
  1350. isInstallSucc =false;
  1351. }
  1352. //清理临时解压包
  1353. if(Error_Succeed==m_fsm->DeleteUnzipDir()){
  1354. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("InstallPackTask")("DeleteUnzipDir succ");
  1355. }else{
  1356. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("InstallPackTask")("DeleteUnzipDir fail");
  1357. }
  1358. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("InstallPackTask")("安装完成:failStatus=%d",failStatus);
  1359. m_fsm->PostEventFIFO(new CUpgradeTaskFSM::InstallPackTaskEvent(isInstallSucc,errMsg,failStatus));//返回处理结果
  1360. }
  1361. };
  1362. }
  1363. //完成
  1364. // 创建新版本目录,拷贝当前版本bin、cfg、dep、mod、imdep、res、install.ini,并修改Shell.ini相关配置
  1365. ErrorCodeEnum CUpgradeTaskFSM::CreateNewVersion(CVersion NewSoftwareVersion,CSimpleStringA &strErrInfo)
  1366. {
  1367. // 创建安装包日志文件
  1368. CSimpleStringA rootVerPath;
  1369. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
  1370. if(rc!=Error_Succeed){
  1371. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("Create new version fail , get RootVer path is fail");
  1372. strErrInfo = CSimpleStringA::Format("Create new version fail , get RootVer path is fail");
  1373. return Error_Bug;
  1374. }
  1375. CSimpleStringA strCurVerPath;
  1376. rc = m_pEntity->GetFunction()->GetPath("Base",strCurVerPath);//获取当前version路径
  1377. if(rc!=Error_Succeed){
  1378. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("Create new version fail , get Base path is fail");
  1379. strErrInfo = CSimpleStringA::Format("Create new version fail , get Base path is fail");
  1380. return Error_Bug;
  1381. }
  1382. CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), NewSoftwareVersion.ToString().GetData());
  1383. //auto &v = cfg->install_ini->install_version;//获取当前版本
  1384. //CVersion v;//获取当前版本
  1385. CVersion curVersion(m_currentVersion.GetMajor(), m_currentVersion.GetMinor(), m_currentVersion.GetRevision(), m_currentVersion.GetBuild());
  1386. if (curVersion == NewSoftwareVersion)
  1387. {
  1388. LogError(Severity_Low, Error_Bug, 0, CSimpleStringA::Format("new ver [%s] equals current ver [%s]", NewSoftwareVersion.ToString().GetData(), curVersion.ToString().GetData()).GetData());
  1389. strErrInfo = CSimpleStringA::Format("new ver [%s] equals current ver [%s]", NewSoftwareVersion.ToString().GetData(), curVersion.ToString().GetData());
  1390. return Error_Bug;
  1391. }
  1392. if (ExistsDirA(strNewVerPath.GetData()))
  1393. {
  1394. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("new version dir [%s] already exist, delete it", strNewVerPath.GetData());
  1395. if(!RemoveDirRecursiveA(strNewVerPath.GetData())){
  1396. #ifdef RVC_OS_WIN
  1397. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("Create new version fail, delete already exist new version is fail:%d",GetLastError());
  1398. strErrInfo = CSimpleStringA::Format("Create new version fail, delete already exist new version is fail:%d",(int)GetLastError());
  1399. #else
  1400. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("Create new version fail, delete already exist new version is fail:%d", errno);
  1401. strErrInfo = CSimpleStringA::Format("Create new version fail, delete already exist new version is fail:%d", errno);
  1402. #endif
  1403. return Error_Bug;
  1404. }
  1405. }
  1406. if (!CreateDirA(strNewVerPath.GetData(), TRUE))
  1407. {
  1408. #ifdef RVC_OS_WIN
  1409. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("Create new version dir fail: %d", GetLastError());
  1410. strErrInfo = CSimpleStringA::Format("create new version dir fail: %d", (int)GetLastError());
  1411. #else
  1412. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("Create new version dir fail: %d", errno);
  1413. strErrInfo = CSimpleStringA::Format("create new version dir fail: %d", errno);
  1414. #endif
  1415. return Error_Unexpect;
  1416. }
  1417. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("create new version dir succ, dir = %s",strNewVerPath.GetData());
  1418. //增加错误信息字段,回传给上层应用
  1419. CSimpleStringA strErrMsg ="";
  1420. CSimpleStringA strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "bin", strCurVerPath.GetData());
  1421. CSimpleStringA strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "bin", strNewVerPath.GetData());
  1422. if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
  1423. {
  1424. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy bin dir fail");
  1425. strErrInfo = CSimpleStringA::Format("copy bin dir fail: %s", strErrMsg.GetData());
  1426. return Error_Unexpect;
  1427. }
  1428. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy bin dir succ");
  1429. strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "cfg", strCurVerPath.GetData());
  1430. strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "cfg", strNewVerPath.GetData());
  1431. if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
  1432. {
  1433. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy cfg dir fail");
  1434. strErrInfo = CSimpleStringA::Format("copy cfg dir fail: %s", strErrMsg.GetData());
  1435. return Error_Unexpect;
  1436. }
  1437. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy cfg dir succ");
  1438. strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strCurVerPath.GetData());
  1439. strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strNewVerPath.GetData());
  1440. if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
  1441. {
  1442. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy dep dir fail");
  1443. strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
  1444. return Error_Unexpect;
  1445. }
  1446. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy dep dir succ");
  1447. strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "mod", strCurVerPath.GetData());
  1448. strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "mod", strNewVerPath.GetData());
  1449. if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
  1450. {
  1451. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy mod dir fail");
  1452. strErrInfo = CSimpleStringA::Format("copy mod dir fail: %s", strErrMsg.GetData());
  1453. return Error_Unexpect;
  1454. }
  1455. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy mod dir succ");
  1456. strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "res", strCurVerPath.GetData());
  1457. strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "res", strNewVerPath.GetData());
  1458. // 检测res目录是否存在
  1459. if (ExistsDirA(strSource))
  1460. {
  1461. if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
  1462. {
  1463. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy res dir fail");
  1464. strErrInfo = CSimpleStringA::Format("copy res dir fail: %s", strErrMsg.GetData());
  1465. return Error_Unexpect;
  1466. }
  1467. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy res dir succ");
  1468. }
  1469. else
  1470. {
  1471. if (!CreateDirA(strDest, TRUE))
  1472. {
  1473. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("create res dir fail");
  1474. strErrInfo = "create res dir fail";
  1475. return Error_Unexpect;
  1476. }
  1477. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("create res dir succ");
  1478. }
  1479. strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "imdep", strCurVerPath.GetData());
  1480. strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "imdep", strNewVerPath.GetData());
  1481. // 检测imdep目录是否存在
  1482. if (ExistsDirA(strSource))
  1483. {
  1484. if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
  1485. {
  1486. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy imdep dir fail");
  1487. strErrInfo = CSimpleStringA::Format("copy imdep dir fail: %s", strErrMsg.GetData());
  1488. return Error_Unexpect;
  1489. }
  1490. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("copy imdep dir succ");
  1491. }
  1492. else
  1493. {
  1494. if (!CreateDirA(strDest, TRUE))
  1495. {
  1496. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("create imdep dir fail");
  1497. strErrInfo = "create imdep dir fail";
  1498. return Error_Unexpect;
  1499. }
  1500. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CreateNewVersion")("create imdep dir succ");
  1501. }
  1502. return Error_Succeed;
  1503. }
  1504. ErrorCodeEnum CUpgradeTaskFSM::ClearUpgradeFailVersion(CVersion NewSoftwareVersion)
  1505. {
  1506. CSimpleStringA rootVerPath;
  1507. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
  1508. if(rc!=Error_Succeed){
  1509. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ClearUpgradeFailVersion")("ClearUpgradeFailVersion fail , get RootVer path is fail");
  1510. return Error_Bug;
  1511. }
  1512. CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), NewSoftwareVersion.ToString().GetData());
  1513. if (ExistsDirA(strNewVerPath.GetData()))
  1514. {
  1515. if(!RemoveDirRecursiveA(strNewVerPath.GetData())){
  1516. #ifdef RVC_OS_WIN
  1517. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ClearUpgradeFailVersion")("ClearUpgradeFailVersion fail, delete temp Version [%s] is fail:%d",strNewVerPath.GetData(),(int)GetLastError());
  1518. #else
  1519. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ClearUpgradeFailVersion")("ClearUpgradeFailVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), errno);
  1520. #endif
  1521. return Error_Bug;
  1522. }else{
  1523. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ClearUpgradeFailVersion")("ClearUpgradeFailVersion succ, delete temp Version [%s] ", strNewVerPath.GetData());
  1524. return Error_Succeed;
  1525. }
  1526. }else{
  1527. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ClearUpgradeFailVersion")("ClearUpgradeFailVersion succ, delete temp Version [%s] is not exsit ", strNewVerPath.GetData());
  1528. return Error_Succeed;
  1529. }
  1530. }
  1531. // result.log 文件内容: result=0&msg=install ok
  1532. bool CUpgradeTaskFSM::GetSysUpgradeResult(const char *pszResultLog, CSimpleStringA &eErrorCode, CSimpleStringA &strErrMsg)
  1533. {
  1534. // 设置初始值
  1535. //eErrorCode = Error_Succeed;
  1536. strErrMsg = "";
  1537. if (!ExistsFileA(pszResultLog))
  1538. {
  1539. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSysUpgradeResult")("GetSysUpgradeResult result log [%s] not exist", pszResultLog);
  1540. strErrMsg = "result.log not exist";
  1541. eErrorCode = "0";
  1542. return true;//???有些外部程序不一定会产生日志文件,故默认不产生文件,认为是成功
  1543. }
  1544. FILE *pResultLog = fopen(pszResultLog, "r");
  1545. if (pResultLog == NULL)
  1546. {
  1547. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSysUpgradeResult")("GetSysUpgradeResult open result log [%s] fail", pszResultLog);
  1548. strErrMsg = "open result.log fail";
  1549. return false;
  1550. }
  1551. char szTmp[4096] = {};
  1552. int nRead = fread_s(szTmp, sizeof(szTmp), 1, sizeof(szTmp), pResultLog);
  1553. CSimpleStringA strResult = szTmp;
  1554. fclose(pResultLog);
  1555. pResultLog = NULL;
  1556. auto arr = strResult.Split('&');
  1557. if(arr.GetCount()!=2){
  1558. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSysUpgradeResult")("GetSysUpgradeResult read result log format fail,[%s]", strResult.GetData());
  1559. strErrMsg = "read result.log format fail,eg result=0&msg=install ok";
  1560. return false;
  1561. }
  1562. for (int i = 0; i < arr.GetCount(); i++)
  1563. {
  1564. auto arr2 = arr[i].Split('=');
  1565. if (arr2.GetCount() == 2)
  1566. {
  1567. #ifdef RVC_OS_WIN
  1568. if (stricmp(arr2[0], "result") == 0)
  1569. eErrorCode = arr2[1];
  1570. else if (stricmp(arr2[0], "msg") == 0)
  1571. strErrMsg = arr2[1];
  1572. #else
  1573. if (strcmp(arr2[0], "result") == 0)
  1574. eErrorCode = arr2[1];
  1575. else if (strcmp(arr2[0], "msg") == 0)
  1576. strErrMsg = arr2[1];
  1577. #endif
  1578. }
  1579. }
  1580. return true;
  1581. }
  1582. int CUpgradeTaskFSM::ExecInstall(CSimpleStringA &strErrMsg)
  1583. {
  1584. //判断是否需要生成新版本
  1585. if(!m_currentTask.pack_version.IsNullOrEmpty()){
  1586. CSimpleStringA strUpgradeVersion = m_currentTask.pack_version;
  1587. CVersion latterVersion;//要更新到的版本号
  1588. CVersion curVer = m_currentVersion;//当前版本号
  1589. // 指定版本
  1590. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  1591. int n = sscanf(strUpgradeVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  1592. if (n != 4)
  1593. {
  1594. strErrMsg = CSimpleStringA::Format("指定升级版本号无效(%s)", strUpgradeVersion.GetData());
  1595. LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("specified software version is invalid: [%s]", strUpgradeVersion.GetData()).GetData());
  1596. return 0;
  1597. }else{
  1598. latterVersion = CVersion(dwMajor, dwMinor, dwRevision, dwBuild);
  1599. }
  1600. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecInstall")("latterVersion :%s",latterVersion.ToString().GetData());
  1601. if(curVer.ToString()==strUpgradeVersion){
  1602. //版本号相同,
  1603. strErrMsg = CSimpleStringA::Format("指定升级版本号与当前版本相同,无效(配置:%s, 当前:%s)", strUpgradeVersion.GetData(),curVer.ToString().GetData());
  1604. return 0;
  1605. //}else if(m_currentVersion.ToString().Compare(strUpgradeVersion)==1){
  1606. //字符串比较版本号大小改为整形数字对比
  1607. }else if(dwMajor < curVer.GetMajor()
  1608. || (dwMajor == curVer.GetMajor() && dwMinor < curVer.GetMinor())
  1609. || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision < curVer.GetRevision())
  1610. || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision == curVer.GetRevision() && dwBuild < curVer.GetBuild())){
  1611. //升级版本小于当前版本
  1612. strErrMsg = CSimpleStringA::Format("指定升级版本号无效(配置:%s,解析:%s,当前:%s)", strUpgradeVersion.GetData(),latterVersion.ToString().GetData(),curVer.ToString().GetData());
  1613. return 0;
  1614. }
  1615. //判断是否需要创建新版本
  1616. CSimpleStringA strErrInfo = "";
  1617. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecInstall")("begin CreateNewVersion,version[%s],pack[%s]",strUpgradeVersion.GetData(),m_currentTask.pack_name.GetData());
  1618. ErrorCodeEnum rc = CreateNewVersion(latterVersion,strErrInfo);
  1619. if (rc != Error_Succeed)
  1620. {
  1621. strErrMsg = CSimpleStringA::Format("CreateNewVersion fail:%s",strErrInfo.GetData());
  1622. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecInstall")("CreateNewVersion,version[%s] fail:%s",strUpgradeVersion.GetData(),strErrInfo.GetData());
  1623. //清理临时版本文件夹
  1624. ClearUpgradeFailVersion(latterVersion);
  1625. return 0;
  1626. }else{
  1627. m_currentTask.NewVersion = strUpgradeVersion;//赋值升级版本号给内存变量
  1628. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecInstall")("CreateNewVersion,version[%s] succ",strUpgradeVersion.GetData());
  1629. }
  1630. }
  1631. //循环执行安装命令
  1632. int iRet=1;//默认是成功
  1633. if(!m_currentTask.install_step.empty()){
  1634. int iCount = m_currentTask.install_step.size();
  1635. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecInstall")("install cmd size = %d",iCount);
  1636. for (int j = 0; j < iCount; j++){
  1637. CInstallStep* tmp = m_currentTask.install_step.front();
  1638. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecInstall")("=====begin cmd=[%s]=====",tmp->cmdType.GetData());
  1639. //开始处理具体命令
  1640. if(tmp->cmdType=="Delete"){
  1641. bool ret = ExecDeleteCmd(strErrMsg,tmp);
  1642. if(!ret){
  1643. //报错才判断
  1644. if(tmp->cmdFail == 0 ){
  1645. iRet = 0;
  1646. break;//出错直接退出
  1647. }else if(tmp->cmdFail == 1 ){
  1648. //继续
  1649. }else{
  1650. iRet = 0;
  1651. break;//其他值也退出
  1652. }
  1653. }
  1654. }else if(tmp->cmdType=="Copy"){
  1655. bool ret = ExecCpoyCmd(strErrMsg,tmp);
  1656. if(!ret){
  1657. //报错才判断
  1658. if(tmp->cmdFail == 0){
  1659. iRet = 0;
  1660. break;//出错直接退出
  1661. }else if(tmp->cmdFail == 1){
  1662. //继续
  1663. }else{
  1664. iRet = 0;
  1665. break;//其他值也退出
  1666. }
  1667. }
  1668. }else if(tmp->cmdType=="Run"){
  1669. int retInt = ExecRunCmd(strErrMsg,tmp);
  1670. if(retInt==0||retInt==-1){
  1671. //报错才判断
  1672. if(tmp->cmdFail == 0 ){
  1673. iRet = retInt;//会有0,-1值
  1674. break;//出错直接退出,并返回体系外结果
  1675. }else if(tmp->cmdFail == 1 ){
  1676. //继续
  1677. }else{
  1678. iRet = 0;
  1679. break;//其他值也退出
  1680. }
  1681. }
  1682. }else{
  1683. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecInstall")("cmd=[%s] is invalid",tmp->cmdType.GetData());
  1684. iRet = 0;
  1685. break;//命令无效直接退出
  1686. }
  1687. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecInstall")("=====end cmd=[%s]=====",tmp->cmdType.GetData());
  1688. m_currentTask.install_step.pop();//去除元素
  1689. delete tmp;//删除内存
  1690. }
  1691. }
  1692. return iRet;//返回处理结果
  1693. }
  1694. int CUpgradeTaskFSM::ExecRunCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
  1695. {
  1696. CSimpleStringA destPath ;//目的路径
  1697. if(ins->dstPathType=="0"){
  1698. CSimpleStringA rootPath;
  1699. if(GetRootTypePath(1,rootPath)){
  1700. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
  1701. }else{
  1702. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 1 is fail");
  1703. return false;
  1704. }
  1705. }else if(ins->dstPathType=="1"){
  1706. destPath = ins->dstPath;//绝对路径
  1707. }else if(ins->dstPathType=="2"){
  1708. CSimpleStringA rootPath;
  1709. if(GetRootTypePath(2,rootPath)){
  1710. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
  1711. }else{
  1712. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 2 is fail");
  1713. return false;
  1714. }
  1715. }else if(ins->dstPathType=="3"){
  1716. CSimpleStringA rootPath;
  1717. if(GetRootTypePath(3,rootPath)){
  1718. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
  1719. }else{
  1720. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 3 is fail");
  1721. return false;
  1722. }
  1723. }else if(ins->dstPathType=="4"){
  1724. CSimpleStringA rootPath;
  1725. if(GetRootTypePath(4,rootPath)){
  1726. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级包相对路径
  1727. }else{
  1728. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 4 is fail");
  1729. return false;
  1730. }
  1731. }else{
  1732. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd destPathType is invalid %s",ins->dstPathType.GetData());
  1733. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPathType is invalid %s",ins->dstPathType.GetData());
  1734. return false;//不支持的路径类型
  1735. }
  1736. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd destPath is %s",destPath.GetData());
  1737. // ToRun=install.bat
  1738. if (ExistsFileA(destPath.GetData()))
  1739. {
  1740. #ifdef RVC_OS_WIN
  1741. // window模式下 如果是Wow64模式,需屏蔽System32重定向
  1742. PVOID pRedirectOldValue(NULL);
  1743. bool bIsWow64 = IsWow64Process();
  1744. if (bIsWow64)
  1745. {
  1746. if (!Wow64DisableWow64FsRedirection(&pRedirectOldValue)){
  1747. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("Wow64DisableWow64FsRedirection fail: %d", GetLastError());
  1748. }else{
  1749. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("Wow64DisableWow64FsRedirection succ");
  1750. }
  1751. }
  1752. #endif
  1753. //system(strSourcePath);
  1754. string sysPathStr = destPath.GetData();
  1755. CSimpleStringA err ="";
  1756. int ret = system_on(sysPathStr,true,err);
  1757. #ifdef RVC_OS_WIN
  1758. // 如果是Wow64模式,恢复System32重定向
  1759. if (bIsWow64)
  1760. {
  1761. if (!Wow64RevertWow64FsRedirection(pRedirectOldValue)){
  1762. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("Wow64RevertWow64FsRedirection fail: %d", GetLastError());
  1763. }else{
  1764. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("Wow64RevertWow64FsRedirection succ");
  1765. }
  1766. }
  1767. #endif
  1768. if(ret!=0){
  1769. //程序执行异常,结果未知
  1770. #ifdef RVC_OS_WIN
  1771. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd is fail, system_on exec unknown ,err=%s",err.GetData());
  1772. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ,err=%s",err.GetData());
  1773. #else
  1774. DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd is fail, system_on exec unknown , ret=%d, err=%s",ret, strerror(errno));
  1775. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ret=%d, err=%s", ret, strerror(errno));
  1776. #endif
  1777. return -1;//未知结果返回
  1778. }else{
  1779. //进一步看返回结果文件判断是否成功
  1780. CSimpleStringA strUnzipPath = GetFileDirectory(destPath.GetData());
  1781. #ifdef RVC_OS_WIN
  1782. CSimpleStringA strResultLog = strUnzipPath + "\\result.log";//结果文件
  1783. #else
  1784. CSimpleStringA strResultLog = strUnzipPath + "/result.log";//结果文件
  1785. #endif
  1786. CSimpleStringA eErrorCode = "";
  1787. //获取结果文件
  1788. if (!GetSysUpgradeResult(strResultLog, eErrorCode, strErrMsg))
  1789. {
  1790. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd is fail, get result from result.log fail, %s", strErrMsg.GetData());
  1791. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail ,get result from result.log fail, %s", strErrMsg.GetData());
  1792. return 0;//失败
  1793. }
  1794. if (eErrorCode == "0")
  1795. {
  1796. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd is succ,[%s] ", destPath.GetData());
  1797. return 1;//成功
  1798. }else{
  1799. #ifdef RVC_OS_WIN
  1800. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
  1801. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
  1802. #else
  1803. DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
  1804. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
  1805. #endif
  1806. return 0;//失败
  1807. }
  1808. }
  1809. }
  1810. else
  1811. {
  1812. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, run file [%s] is not Exist",destPath.GetData());
  1813. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecRunCmd")("ExecRunCmd is fail, run file [%s] is not Exist",destPath.GetData());
  1814. return 0;//失败
  1815. }
  1816. }
  1817. bool CUpgradeTaskFSM::ExecDeleteCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
  1818. {
  1819. //只删除同一层目录下的文件和文件夹
  1820. CSimpleStringA destPath ;//目的路径+通配符
  1821. if(ins->dstPathType=="0"){
  1822. CSimpleStringA rootPath;
  1823. if(GetRootTypePath(1,rootPath)){
  1824. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
  1825. }else{
  1826. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 1 is fail");
  1827. return false;
  1828. }
  1829. }else if(ins->dstPathType=="1"){
  1830. destPath = ins->dstPath;//绝对路径
  1831. }else if(ins->dstPathType=="2"){
  1832. CSimpleStringA rootPath;
  1833. if(GetRootTypePath(2,rootPath)){
  1834. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
  1835. }else{
  1836. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 2 is fail");
  1837. return false;
  1838. }
  1839. }else if(ins->dstPathType=="3"){
  1840. CSimpleStringA rootPath;
  1841. if(GetRootTypePath(3,rootPath)){
  1842. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
  1843. }else{
  1844. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 3 is fail");
  1845. return false;
  1846. }
  1847. }else{
  1848. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("ExecDeleteCmd destPathType is invalid %s",ins->dstPathType.GetData());
  1849. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPathType is invalid %s",ins->dstPathType.GetData());
  1850. return false;//不支持的路径类型
  1851. }
  1852. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("ExecDeleteCmd destPath is %s",destPath.GetData());
  1853. if(destPath.IndexOf("*")>0){
  1854. CSimpleStringA strFileFilter = _GetFileName(destPath);
  1855. CSimpleStringA strDestDir = destPath.SubString(0, destPath.GetLength()-strFileFilter.GetLength()-1);
  1856. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match filter name [%s] in dir [%s]", strFileFilter.GetData(), strDestDir.GetData());
  1857. // 删除所有匹配文件
  1858. bool bRet = true;
  1859. auto arr = fileutil_get_sub_files(strDestDir.GetData());
  1860. if (arr != NULL)
  1861. {
  1862. for (int i = 0; i < arr->nelts; ++i)
  1863. {
  1864. char *file = ARRAY_IDX(arr, i, char*);
  1865. if (IsFileMatch(strFileFilter, _GetFileName(file)))
  1866. {
  1867. if(RemoveFileA(file)){
  1868. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match file succ: [%s]", file);
  1869. }else{
  1870. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match file fail: [%s]", file);
  1871. strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", file);
  1872. bRet = false;
  1873. break;
  1874. }
  1875. }
  1876. else
  1877. {
  1878. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("ignore not match file: [%s]", file);
  1879. }
  1880. }
  1881. toolkit_array_free2(arr);
  1882. if(!bRet){
  1883. return bRet;
  1884. }
  1885. }
  1886. // 删除所有匹配子目录
  1887. auto subdirs = fileutil_get_sub_dirs(strDestDir.GetData());
  1888. if (subdirs != NULL)
  1889. {
  1890. for (int i = 0; i < subdirs->nelts; ++i)
  1891. {
  1892. const char *dir = ARRAY_IDX(subdirs, i, char*);
  1893. if (IsFileMatch(strFileFilter, _GetFileName(dir)))
  1894. {
  1895. if(RemoveDirRecursive(dir)){
  1896. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match dir succ: [%s]", dir);
  1897. }else{
  1898. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match dir fail: [%s]", dir);
  1899. strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", dir);
  1900. bRet = false;
  1901. break;
  1902. }
  1903. }
  1904. else
  1905. {
  1906. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("ignore not match dir: [%s]", dir);
  1907. }
  1908. }
  1909. toolkit_array_free2(subdirs);
  1910. if(!bRet){
  1911. return bRet;
  1912. }
  1913. }
  1914. return bRet;
  1915. }else{
  1916. //直接删除文件
  1917. bool bRet = true;
  1918. if (ExistsFileA(destPath.GetData()))
  1919. {
  1920. if(RemoveFileA(destPath.GetData())){
  1921. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match file succ: [%s]", destPath.GetData());
  1922. }else{
  1923. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match file fail: [%s]", destPath.GetData());
  1924. strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", destPath.GetData());
  1925. bRet = false;
  1926. }
  1927. return bRet;
  1928. }
  1929. else if (ExistsDirA(destPath.GetData()))
  1930. {
  1931. if(RemoveDirRecursiveA(destPath.GetData())){
  1932. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match dir succ: [%s]", destPath.GetData());
  1933. }else{
  1934. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete match dir fail: [%s]", destPath.GetData());
  1935. strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", destPath.GetData());
  1936. bRet = false;
  1937. }
  1938. return bRet;
  1939. }
  1940. else
  1941. {
  1942. //指定文件不再则忽略删除此文件
  1943. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecDeleteCmd")("delete file [%s] not exists,ignore delete file", destPath.GetData());
  1944. return bRet;
  1945. }
  1946. }
  1947. }
  1948. bool CUpgradeTaskFSM::ExecCpoyCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
  1949. {
  1950. CSimpleStringA sourcePath ;//路径+通配符
  1951. if(ins->srcPathType=="0"){
  1952. CSimpleStringA rootPath="";
  1953. if(GetRootTypePath(1,rootPath)){
  1954. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//相对路径
  1955. }else{
  1956. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 1 is fail");
  1957. return false;
  1958. }
  1959. }else if(ins->srcPathType=="1"){
  1960. sourcePath = ins->srcPath;//绝对路径
  1961. }else if(ins->srcPathType=="2"){
  1962. CSimpleStringA rootPath="";
  1963. if(GetRootTypePath(2,rootPath)){
  1964. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//当前版本相对路径
  1965. }else{
  1966. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 2 is fail");
  1967. return false;
  1968. }
  1969. }else if(ins->srcPathType=="3"){
  1970. CSimpleStringA rootPath="";
  1971. if(GetRootTypePath(4,rootPath)){
  1972. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//升级包相对路径
  1973. }else{
  1974. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 4 is fail");
  1975. return false;
  1976. }
  1977. }else{
  1978. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("ExecCpoyCmd srcPathType is invalid %s",ins->srcPathType.GetData());
  1979. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd srcPathType is invalid %s",ins->srcPathType.GetData());
  1980. return false;//不支持的路径类型
  1981. }
  1982. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("ExecCpoyCmd sourcePath is %s",sourcePath.GetData());
  1983. CSimpleStringA destPath ;//目的路径文件夹
  1984. if(ins->dstPathType=="0"){
  1985. CSimpleStringA rootPath="";
  1986. if(GetRootTypePath(1,rootPath)){
  1987. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
  1988. }else{
  1989. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 1 is fail");
  1990. return false;
  1991. }
  1992. }else if(ins->dstPathType=="1"){
  1993. destPath = ins->dstPath;//绝对路径
  1994. }else if(ins->dstPathType=="2"){
  1995. CSimpleStringA rootPath="";
  1996. if(GetRootTypePath(2,rootPath)){
  1997. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
  1998. }else{
  1999. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 2 is fail");
  2000. return false;
  2001. }
  2002. }else if(ins->dstPathType=="3"){
  2003. CSimpleStringA rootPath="";
  2004. if(GetRootTypePath(3,rootPath)){
  2005. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
  2006. }else{
  2007. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 3 is fail");
  2008. return false;
  2009. }
  2010. //}else if(ins->dstPathType=="4"){
  2011. // CSimpleStringA rootPath="";
  2012. // if(GetRootTypePath(4,rootPath)){
  2013. // destPath = CSimpleStringA::Format("%s\\%s",rootPath.GetData(),ins->dstPath.GetData());//升级包相对路径
  2014. // }else{
  2015. // strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 4 is fail");
  2016. // return false;
  2017. // }
  2018. }else{
  2019. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("ExecCpoyCmd dstPathType is invalid %s",ins->dstPathType.GetData());
  2020. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd dstPathType is invalid %s",ins->dstPathType.GetData());
  2021. return false;//不支持的路径类型
  2022. }
  2023. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("ExecCpoyCmd destPath is %s",destPath.GetData());
  2024. if(sourcePath.IndexOf("*")>0){
  2025. //循环匹配拷贝
  2026. //找到要扫描的文件夹
  2027. CSimpleStringA strFileDir = GetFileDirectory(sourcePath.GetData());
  2028. //过滤通配条件
  2029. CSimpleStringA strFileFilter = _GetFileName(sourcePath.GetData());
  2030. list<CSimpleStringA> fileList;
  2031. //获取所有根文件夹下的文件相对路径:如mod\test.dll
  2032. RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
  2033. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("find fileList =%d",fileList.size());
  2034. if(fileList.size()==0){
  2035. //判断mod文件夹未空则报错
  2036. if(sourcePath.IndexOf("mod")!=-1){
  2037. LogWarn(Severity_Low, Error_Exception, WARN_TASK_COPY_FILE_ZERO,CSimpleStringA::Format("ExecCpoyCmd sourcePath is [%s] file is 0",sourcePath.GetData()));
  2038. }
  2039. }
  2040. for(auto it = fileList.begin(); it != fileList.end(); it++)
  2041. {
  2042. if (IsFileMatch(strFileFilter, _GetFileName((const char*)(*it))))
  2043. {
  2044. CSimpleStringA strSrcName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", GetFileDirectory(sourcePath.GetData()).GetData(), (const char*)(*it));//源文件路径
  2045. CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(),(const char*)(*it));//目标文件路径
  2046. //匹配成功,开始拷贝文件
  2047. CSimpleStringA errMsg = "";
  2048. ErrorCodeEnum rc = CopyFileOperate(strSrcName.GetData(),strDestName.GetData(),3,errMsg);
  2049. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("copy file [%s] to [%s] %s", strSrcName.GetData(),strDestName.GetData(), rc == Error_Succeed ? "succeed" : "fail");
  2050. if (rc != Error_Succeed)
  2051. {
  2052. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("copy file [%s] fail: %s",strSrcName.GetData(),errMsg.GetData());
  2053. strErrMsg = CSimpleStringA::Format("copy file [%s] fail: %s",strSrcName.GetData(),errMsg.GetData());
  2054. return false;//报错
  2055. }
  2056. }
  2057. }
  2058. }else{
  2059. //直接拷贝文件:考虑有些文件因智能对比不一定下发,故如果文件不存在,则默认忽略此策略
  2060. CSimpleStringA errMsg = "";
  2061. CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), _GetFileName(sourcePath.GetData()));
  2062. if(ExistsFileA(sourcePath.GetData())){
  2063. ErrorCodeEnum rc = CopyFileOperate(sourcePath.GetData(),strDestName.GetData(),3,errMsg);
  2064. if (rc != Error_Succeed)
  2065. {
  2066. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("copy file [%s] fail:%s",sourcePath.GetData(),errMsg.GetData());
  2067. strErrMsg = CSimpleStringA::Format("copy file [%s] fail:%s",sourcePath.GetData(),errMsg.GetData());
  2068. return false;//报错
  2069. }
  2070. }else{
  2071. if(ins->srcPathType=="3"){
  2072. //升级包因智能升级不一定有指定的文件存在
  2073. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("拷贝指定的文件[%s]不存在,因智能升级对比过滤,故忽略此文件拷贝",sourcePath.GetData());
  2074. }else{
  2075. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ExecCpoyCmd")("copy file [%s] fail:file to copy not exist",sourcePath.GetData());
  2076. strErrMsg = CSimpleStringA::Format("copy file [%s] fail:file to copy not exist",sourcePath.GetData());
  2077. return false;//报错
  2078. }
  2079. }
  2080. }
  2081. return true;
  2082. }
  2083. bool CUpgradeTaskFSM::GetRootTypePath(int rootType,CSimpleStringA &Path)
  2084. {
  2085. CSimpleStringA tempPath;
  2086. if(rootType == 1){
  2087. ErrorCodeEnum Error =m_pEntity->GetFunction()->GetPath("Root",tempPath);//例如:C:\Run /opt/Run
  2088. if(Error_Succeed == Error){
  2089. if(!tempPath.IsNullOrEmpty()){
  2090. string runPathStr = tempPath.GetData();
  2091. int pos = runPathStr.find_last_of(SPLIT_SLASH);
  2092. Path = runPathStr.substr(0,pos).c_str();
  2093. }else{
  2094. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetRootTypePath")("get Root path is null");
  2095. return false;
  2096. }
  2097. }else{
  2098. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetRootTypePath")("get Root path is error");
  2099. return false;
  2100. }
  2101. }else if(rootType == 2){
  2102. ErrorCodeEnum Error =m_pEntity->GetFunction()->GetPath("Base",tempPath);//例如:C:\Run\version\4.8.1.1 /opt/Run/version/4.8.1.1
  2103. if(Error_Succeed == Error){
  2104. if(!tempPath.IsNullOrEmpty()){
  2105. Path = tempPath;
  2106. }else{
  2107. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetRootTypePath")("get currVer path is null");
  2108. return false;
  2109. }
  2110. }else{
  2111. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetRootTypePath")("get currVer path is error");
  2112. return false;
  2113. }
  2114. }else if(rootType == 3){
  2115. ErrorCodeEnum Error =m_pEntity->GetFunction()->GetPath("RootVer",tempPath);//例如:C:\Run\version\4.9.1.1 /opt/Run/version/4.9.1.1
  2116. if(Error_Succeed == Error){
  2117. if(!tempPath.IsNullOrEmpty()){
  2118. Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
  2119. }else{
  2120. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetRootTypePath")("get currVer path is null");
  2121. return false;
  2122. }
  2123. }else{
  2124. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetRootTypePath")("get upgradeVer path is error");
  2125. return false;
  2126. }
  2127. }else if(rootType == 4){
  2128. ErrorCodeEnum Error =m_pEntity->GetFunction()->GetPath("Downloads",tempPath);//例如:C:\rvc\Downloads\4.8.1.1 /opt/rvc/Downloads/4.8.1.1
  2129. if(Error_Succeed == Error){
  2130. if(!tempPath.IsNullOrEmpty()){
  2131. CSimpleStringA strUnzipDir;
  2132. strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_name.GetData());
  2133. //解压去除了.zip后缀
  2134. if (strUnzipDir.IsEndWith(".zip")){
  2135. Path = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
  2136. }else{
  2137. Path = strUnzipDir;
  2138. }
  2139. }else{
  2140. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetRootTypePath")("get upgradePack path is null");
  2141. return false;
  2142. }
  2143. }else{
  2144. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetRootTypePath")("get upgradePack path is error");
  2145. return false;
  2146. }
  2147. }
  2148. return true;
  2149. }
  2150. ErrorCodeEnum CUpgradeTaskFSM::CopyFileOperate(const char* srcPath, const char* destPath, int nCopyMode, CSimpleStringA &strErrMsg)
  2151. {
  2152. //源文件是否存在
  2153. if (!ExistsFileA(srcPath))
  2154. {
  2155. strErrMsg = CSimpleStringA::Format("CopyFileOperate file [%s] to copy not exist", srcPath);
  2156. return Error_NotExist;
  2157. }
  2158. //目标文件夹是否存在
  2159. CSimpleStringA strDestDir = GetFileDirectory(destPath);
  2160. if (!ExistsDirA(strDestDir.GetData())){
  2161. if(!CreateDirA(strDestDir.GetData(), TRUE)){
  2162. strErrMsg = CSimpleStringA::Format("CopyFileOperate create strDestDir[%s] fail", strDestDir.GetData());
  2163. return Error_Exception;
  2164. }
  2165. }
  2166. //目标文件是否存在
  2167. BOOL bDestFileExists = ExistsFileA(destPath);
  2168. if (bDestFileExists){
  2169. RemoveFileReadOnlyAttributeA(destPath);
  2170. }
  2171. BOOL bRet = TRUE;
  2172. switch (nCopyMode)
  2173. {
  2174. case 1:
  2175. {
  2176. if (bDestFileExists) {
  2177. #ifdef RVC_OS_WIN
  2178. bRet = CopyFileA(srcPath, destPath, FALSE);
  2179. #else
  2180. if (fileutil_copy_file(destPath, srcPath) == 0) {
  2181. bRet = TRUE;
  2182. }
  2183. else {
  2184. bRet = FALSE;
  2185. }
  2186. #endif
  2187. }
  2188. else {
  2189. LOG_TRACE("ignore file [%s] copy for dest file not exists", srcPath);
  2190. }
  2191. }
  2192. break;
  2193. case 2:
  2194. {
  2195. if (!bDestFileExists)
  2196. #ifdef RVC_OS_WIN
  2197. bRet = CopyFileA(srcPath, destPath, TRUE);
  2198. #else
  2199. if (fileutil_copy_file(destPath, srcPath) == 0) {
  2200. bRet = TRUE;
  2201. }
  2202. else {
  2203. bRet = FALSE;
  2204. }
  2205. #endif
  2206. else
  2207. LOG_TRACE("ignore file [%s] copy for dest file exists", srcPath);
  2208. }
  2209. break;
  2210. case 3:
  2211. #ifdef RVC_OS_WIN
  2212. bRet = CopyFileA(srcPath, destPath, FALSE);
  2213. #else
  2214. if (fileutil_copy_file(destPath, srcPath) == 0) {
  2215. bRet = TRUE;
  2216. }
  2217. else {
  2218. bRet = FALSE;
  2219. }
  2220. #endif
  2221. break;
  2222. case 4:
  2223. {
  2224. // 不发生拷贝,只进行判断
  2225. if(bDestFileExists)
  2226. LOG_TRACE("file [%s] exist", srcPath);
  2227. else
  2228. LOG_TRACE("file [%s] not exist", srcPath);
  2229. }
  2230. break;
  2231. }
  2232. if (bRet){
  2233. RemoveFileReadOnlyAttributeA(destPath);
  2234. }else{
  2235. #ifdef RVC_OS_WIN
  2236. strErrMsg = CSimpleStringA::Format("CopyFileOperate copy file fail:%d", GetLastError());
  2237. #else
  2238. strErrMsg = CSimpleStringA::Format("CopyFileOperate copy file fail:%d", errno);
  2239. #endif
  2240. }
  2241. ErrorCodeEnum rc = bRet ? Error_Succeed : Error_Unexpect;
  2242. return rc;
  2243. }
  2244. ErrorCodeEnum CUpgradeTaskFSM::SetRunSucceed(const char* pPackFile)
  2245. {
  2246. // 拷贝升级包到Upgraded目录
  2247. CSimpleStringA strDownloadPath, strUpgradedPath;
  2248. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadPath);
  2249. if(rc!=Error_Succeed){
  2250. return rc;
  2251. }
  2252. rc = m_pEntity->GetFunction()->GetPath("Upgraded", strUpgradedPath);
  2253. if(rc!=Error_Succeed){
  2254. return rc;
  2255. }
  2256. CSimpleStringA strSourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strDownloadPath, pPackFile);
  2257. CSimpleStringA strDestPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strUpgradedPath, pPackFile);
  2258. #ifdef RVC_OS_WIN
  2259. CopyFileA(strSourcePath.GetData(), strDestPath.GetData(), FALSE);
  2260. #else
  2261. fileutil_copy_file(strDestPath.GetData(), strSourcePath.GetData());
  2262. #endif
  2263. return Error_Succeed;
  2264. }
  2265. ErrorCodeEnum CUpgradeTaskFSM::UpgradeToNewVersion()
  2266. {
  2267. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpgradeToNewVersion")("begin UpgradeToNewVersion");
  2268. //获取新版本号
  2269. if(m_currentTask.NewVersion.IsNullOrEmpty()){
  2270. if(m_currentTask.pack_version.IsNullOrEmpty()){
  2271. return Error_Succeed;
  2272. }else{
  2273. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpgradeToNewVersion")("NewVersion is null, pack_version=[%s] is not null,UpgradeToNewVersion fail, taskID=[%s]",m_currentTask.pack_version.GetData(), m_currentTask.upgradeTaskId.GetData());
  2274. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, NewVersion is null, pack_version [%s] is not null,fail",m_currentTask.pack_version.GetData()).GetData());
  2275. return Error_Unexpect;//这种情况有问题,需要清除此任务
  2276. }
  2277. }else{
  2278. CSimpleStringA rootVerPath;
  2279. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
  2280. if(rc!=Error_Succeed){
  2281. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpgradeToNewVersion")("UpgradeToNewVersion fail , get RootVer path is fail");
  2282. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,"UpgradeToNewVersion: get RootVer path is fail");
  2283. return Error_Bug;
  2284. }
  2285. CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.NewVersion.GetData());
  2286. if(!ExistsDirA(strNewVerPath.GetData())){
  2287. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, strNewVerPath =%s is not exist,fail",strNewVerPath.GetData()).GetData());
  2288. return Error_Unexpect;//这种情况有问题,需要清除此任务
  2289. }
  2290. //修改运行时文件
  2291. //修改active配置
  2292. CSimpleStringA strActiveFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "active.txt", rootVerPath.GetData());
  2293. if(!ExistsFileA(strActiveFile.GetData())){
  2294. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail,active file is not exist");
  2295. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,"UpgradeToNewVersion fail, active file is not exist");
  2296. return Error_Unexpect;
  2297. }
  2298. //先做active文件备份,后面写入失败再copy回去
  2299. #ifdef RVC_OS_WIN
  2300. bool backupSucc = true;
  2301. CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\back_active.txt", rootVerPath.GetData());
  2302. if(!CopyFileA(strActiveFile.GetData(),strBackupActiveFile.GetData(),FALSE)){
  2303. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, back up active.txt fail, err=%d",(int)GetLastError()).GetData());
  2304. backupSucc = false;
  2305. }
  2306. FILE* fp = fopen(strActiveFile.GetData(),"wb+");
  2307. if(fp==NULL){
  2308. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
  2309. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open write active.txt fail, err=%d",(int)GetLastError()).GetData());
  2310. return Error_Unexpect;
  2311. }
  2312. int ret = fwrite(m_currentTask.NewVersion.GetData(),m_currentTask.NewVersion.GetLength(),1,fp);
  2313. if(ret!=1){
  2314. //LogError(Severity_Low, Error_Unexpect, 0, "write active.txt fail");
  2315. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, write active.txt fail, err=%d",(int)GetLastError()).GetData());
  2316. fclose(fp);
  2317. if(backupSucc){
  2318. if(CopyFileA(strBackupActiveFile.GetData(),strActiveFile.GetData(),FALSE)){
  2319. RemoveFileA(strBackupActiveFile.GetData());
  2320. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpgradeToNewVersion")("back_active.txt copy to active.txt is succ");
  2321. }else{
  2322. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, back_active.txt copy to active.txt is fail, err=%d",(int)GetLastError()).GetData());
  2323. }
  2324. }
  2325. return Error_Unexpect;
  2326. }else{
  2327. fflush(fp);
  2328. fclose(fp);
  2329. if (ExistsFileA(strBackupActiveFile.GetData())) {
  2330. RemoveFileA(strBackupActiveFile.GetData());
  2331. }
  2332. }
  2333. //重新读active文件,看文件内容是什么
  2334. fp = fopen(strActiveFile.GetData(),"rb");
  2335. if(fp==NULL){
  2336. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
  2337. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open read active.txt fail, err=%d",(int)GetLastError()).GetData());
  2338. return Error_Unexpect;
  2339. }
  2340. char cVer[16] = {0};
  2341. int re = fread(cVer,m_currentTask.NewVersion.GetLength(),1,fp);
  2342. if(re!=1){
  2343. //LogError(Severity_Low, Error_Unexpect, 0, "Read active.txt fail");
  2344. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, read active.txt fail, err=%d",(int)GetLastError()).GetData());
  2345. }else{
  2346. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpgradeToNewVersion")("read active.txt, version[%s]", cVer);
  2347. }
  2348. fclose(fp);
  2349. return Error_Succeed;
  2350. #else
  2351. bool backupSucc = true;
  2352. CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\back_active.txt", rootVerPath.GetData());
  2353. if (fileutil_copy_file( strBackupActiveFile.GetData(),strActiveFile.GetData())!=0) {
  2354. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, back up active.txt fail, err=%d", errno).GetData());
  2355. backupSucc = false;
  2356. }
  2357. FILE* fp = fopen(strActiveFile.GetData(),"wb+");
  2358. if(fp==NULL){
  2359. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
  2360. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, open write active.txt fail, err=%d", errno).GetData());
  2361. return Error_Unexpect;
  2362. }
  2363. int ret = fwrite(m_currentTask.NewVersion.GetData(),m_currentTask.NewVersion.GetLength(),1,fp);
  2364. if(ret!=1){
  2365. //LogError(Severity_Low, Error_Unexpect, 0, "write active.txt fail");
  2366. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, write active.txt fail, err=%d", errno).GetData());
  2367. fclose(fp);
  2368. if (backupSucc) {
  2369. if (fileutil_copy_file(strActiveFile.GetData(), strBackupActiveFile.GetData())==0) {
  2370. RemoveFileA(strBackupActiveFile.GetData());
  2371. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpgradeToNewVersion")("back_active.txt copy to active.txt is succ");
  2372. }else{
  2373. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, back_active.txt copy to active.txt is fail, err=%d", errno).GetData());
  2374. }
  2375. }
  2376. return Error_Unexpect;
  2377. }else{
  2378. fflush(fp);
  2379. fclose(fp);
  2380. if (ExistsFileA(strBackupActiveFile.GetData())) {
  2381. RemoveFileA(strBackupActiveFile.GetData());
  2382. }
  2383. }
  2384. //重新读active文件,看文件内容是什么
  2385. fp = fopen(strActiveFile.GetData(),"rb");
  2386. if(fp==NULL){
  2387. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
  2388. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open read active.txt fail, err=%d", errno).GetData());
  2389. return Error_Unexpect;
  2390. }
  2391. char cVer[16] = {0};
  2392. int re = fread(cVer,m_currentTask.NewVersion.GetLength(),1,fp);
  2393. if(re!=1){
  2394. //LogError(Severity_Low, Error_Unexpect, 0, "Read active.txt fail");
  2395. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, read active.txt fail, err=%d", errno).GetData());
  2396. }else{
  2397. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UpgradeToNewVersion")("read active.txt, version[%s]", cVer);
  2398. }
  2399. fclose(fp);
  2400. return Error_Succeed;
  2401. #endif
  2402. }
  2403. }
  2404. ErrorCodeEnum CUpgradeTaskFSM::RollBackToHistoryVersion(CVersion historyVersion)
  2405. {
  2406. // 判断目标版本是否小于当前版本
  2407. CVersion v=m_currentVersion;//当前版本
  2408. CVersion curVersion(v.GetMajor(), v.GetMinor(), v.GetRevision(), v.GetBuild());
  2409. if (curVersion <= historyVersion)
  2410. {
  2411. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("history version [%s] >= current version [%s]", historyVersion.ToString().GetData(), curVersion.ToString().GetData()).GetData());
  2412. return Error_Param;
  2413. }
  2414. // 检查对应文件夹是否存在
  2415. CSimpleStringA strHisVersion = historyVersion.ToString();
  2416. CSimpleStringA rootVerPath;
  2417. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
  2418. if(rc!=Error_Succeed){
  2419. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryVersion fail , get RootVer path is fail");
  2420. return Error_Bug;
  2421. }
  2422. CSimpleStringA strHisVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), strHisVersion.GetData());
  2423. if (!ExistsDirA(strHisVerPath.GetData()))
  2424. {
  2425. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryVersion fail, history version dir [%s] not exists", strHisVerPath.GetData()).GetData());
  2426. return Error_NotExist;
  2427. }
  2428. //删除当时的运行缓存值
  2429. // 修改active.txt文件,可能存在失败
  2430. CSimpleStringA strActiveFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "active.txt", rootVerPath.GetData());
  2431. if(!ExistsFileA(strActiveFile.GetData())){
  2432. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryVersion fail, active file is not exist");
  2433. return Error_Unexpect;
  2434. }
  2435. //先做active文件备份,后面写入失败再copy回去
  2436. #ifdef RVC_OS_WIN
  2437. bool backupSucc = true;
  2438. CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\Rollback_active.txt", rootVerPath.GetData());
  2439. if(!CopyFileA(strActiveFile.GetData(),strBackupActiveFile.GetData(),FALSE)){
  2440. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL,CSimpleStringA::Format("RRollBackToHistoryVersion fail, back up active.txt fail, err=%d",(int)GetLastError()).GetData());
  2441. backupSucc = false;
  2442. }
  2443. FILE* fp = fopen(strActiveFile.GetData(),"wb+");
  2444. if(fp==NULL){
  2445. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open write active.txt fail,err=%d", (int)GetLastError()).GetData());
  2446. return Error_Unexpect;
  2447. }
  2448. int ret = fwrite(strHisVersion.GetData(),strHisVersion.GetLength(),1,fp);
  2449. if(ret!=1){
  2450. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, write active.txt fail,err=%d", (int)GetLastError()).GetData());
  2451. fclose(fp);
  2452. if(backupSucc){
  2453. if(CopyFileA(strBackupActiveFile.GetData(),strActiveFile.GetData(),FALSE)){
  2454. RemoveFileA(strBackupActiveFile.GetData());
  2455. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RollBackToHistoryVersion")("Rollback_active.txt copy to active.txt is succ");
  2456. }else{
  2457. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL,CSimpleStringA::Format("RRollBackToHistoryVersion fail, Rollback_active.txt copy to active.txt is fail, err=%d",(int)GetLastError()).GetData());
  2458. }
  2459. }
  2460. return Error_Unexpect;
  2461. }else{
  2462. fflush(fp);
  2463. fclose(fp);
  2464. if (ExistsFileA(strBackupActiveFile.GetData())) {
  2465. RemoveFileA(strBackupActiveFile.GetData());
  2466. }
  2467. }
  2468. //重新读active文件,看文件内容是什么
  2469. fp = fopen(strActiveFile.GetData(),"rb");
  2470. if(fp==NULL){
  2471. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open read active.txt fail,err=%d", (int)GetLastError()).GetData());
  2472. return Error_Unexpect;
  2473. }
  2474. char cVer[16] = {0};
  2475. int re = fread(cVer,strHisVersion.GetLength(),1,fp);
  2476. if(re!=1){
  2477. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Read active.txt fail,err=%d", (int)GetLastError()).GetData());
  2478. }else{
  2479. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RollBackToHistoryVersion")("read active.txt, version[%s]", cVer);
  2480. }
  2481. fclose(fp);
  2482. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RollBackToHistoryVersion")("set rollback to history version [%s] succeed", (const char*)strHisVersion);
  2483. return Error_Succeed;
  2484. #else
  2485. bool backupSucc = true;
  2486. CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\Rollback_active.txt", rootVerPath.GetData());
  2487. if (fileutil_copy_file(strBackupActiveFile.GetData(), strActiveFile.GetData())!=0) {
  2488. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, back up active.txt fail, err=%d", errno).GetData());
  2489. backupSucc = false;
  2490. }
  2491. FILE* fp = fopen(strActiveFile.GetData(),"wb+");
  2492. if(fp==NULL){
  2493. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open write active.txt fail,err=%d", errno).GetData());
  2494. return Error_Unexpect;
  2495. }
  2496. int ret = fwrite(strHisVersion.GetData(),strHisVersion.GetLength(),1,fp);
  2497. if(ret!=1){
  2498. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, write active.txt fail,err=%d", errno).GetData());
  2499. fclose(fp);
  2500. if (backupSucc) {
  2501. if (fileutil_copy_file(strActiveFile.GetData(), strBackupActiveFile.GetData())==0) {
  2502. RemoveFileA(strBackupActiveFile.GetData());
  2503. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RollBackToHistoryVersion")("Rollback_active.txt copy to active.txt is succ");
  2504. }else{
  2505. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Rollback_active.txt copy to active.txt is fail, err=%d", errno).GetData());
  2506. }
  2507. }
  2508. return Error_Unexpect;
  2509. }else{
  2510. fflush(fp);
  2511. fclose(fp);
  2512. if (ExistsFileA(strBackupActiveFile.GetData())) {
  2513. RemoveFileA(strBackupActiveFile.GetData());
  2514. }
  2515. }
  2516. //重新读active文件,看文件内容是什么
  2517. fp = fopen(strActiveFile.GetData(),"rb");
  2518. if(fp==NULL){
  2519. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open read active.txt fail,err=%d", errno).GetData());
  2520. return Error_Unexpect;
  2521. }
  2522. char cVer[16] = {0};
  2523. int re = fread(cVer,strHisVersion.GetLength(),1,fp);
  2524. if(re!=1){
  2525. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Read active.txt fail,err=%d", errno).GetData());
  2526. }else{
  2527. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RollBackToHistoryVersion")("read active.txt, version[%s]", cVer);
  2528. }
  2529. fclose(fp);
  2530. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RollBackToHistoryVersion")("set rollback to history version [%s] succeed", (const char*)strHisVersion);
  2531. return Error_Succeed;
  2532. #endif
  2533. }
  2534. void CUpgradeTaskFSM::RecursiveGetSubFiles(const char *pszDir, const char *pszTrimStart, list<CSimpleStringA>& retList)
  2535. {
  2536. if (!ExistsDirA(pszDir))
  2537. return;
  2538. auto arr = fileutil_get_sub_files(pszDir);
  2539. if (arr != NULL)
  2540. {
  2541. for (int i = 0; i < arr->nelts; ++i)
  2542. {
  2543. char *file = ARRAY_IDX(arr, i, char*);
  2544. #ifdef RVC_OS_WIN
  2545. //不区分大小写
  2546. if (pszTrimStart != NULL && strnicmp(file, pszTrimStart, strlen(pszTrimStart))==0) {
  2547. #else
  2548. //区分大小写
  2549. if (pszTrimStart != NULL && strncmp(file, pszTrimStart, strlen(pszTrimStart)) == 0) {
  2550. #endif
  2551. file += strlen(pszTrimStart);
  2552. if (*file == SPLIT_SLASH)
  2553. file++;
  2554. }
  2555. retList.push_back(file);
  2556. }
  2557. toolkit_array_free2(arr);
  2558. }
  2559. arr = fileutil_get_sub_dirs(pszDir);
  2560. if (arr != NULL)
  2561. {
  2562. for (int i = 0; i < arr->nelts; ++i)
  2563. {
  2564. char *dir = ARRAY_IDX(arr, i, char*);
  2565. RecursiveGetSubFiles(dir, pszTrimStart, retList);
  2566. }
  2567. toolkit_array_free2(arr);
  2568. }
  2569. }
  2570. bool CUpgradeTaskFSM::IsFileMatch(const char *pszFilter, const char *pszFileName)
  2571. {
  2572. const char *p1 = pszFilter;
  2573. const char *p2 = pszFileName;
  2574. if (p1 == NULL)
  2575. return true;
  2576. if (p2 == NULL)
  2577. return false;
  2578. if (*p1 ==NULL && *p2 ==NULL)
  2579. return true;
  2580. else if (*p1 == NULL)
  2581. return false;
  2582. else if (*p2 == NULL)
  2583. {
  2584. // 查找*p1是否全是*
  2585. while(*p1 == '*')
  2586. p1++;
  2587. if (*p1 == NULL)
  2588. return true;
  2589. else
  2590. return false;
  2591. }
  2592. if (*p1 != '*')
  2593. {
  2594. if (tolower(*p1) != tolower(*p2))
  2595. return false;
  2596. else
  2597. return IsFileMatch(p1+1, p2+1);
  2598. }
  2599. else
  2600. {
  2601. while(*++p1 == '*');
  2602. if (*p1 == NULL)
  2603. return true;
  2604. while (*p2)
  2605. {
  2606. while(tolower(*p1) != tolower(*p2) && *++p2);
  2607. if (*p2 == NULL)
  2608. return false;
  2609. if(IsFileMatch(p1+1, p2+1))
  2610. return true;
  2611. p2++;
  2612. }
  2613. return false;
  2614. }
  2615. }
  2616. bool CUpgradeTaskFSM::RecursiveCopyDir(const char *pszSourceDir, const char *pszDestDir,CSimpleStringA &strErrInfo)
  2617. {
  2618. array_header_t *arr;
  2619. #ifdef RVC_OS_WIN
  2620. if (!ExistsDirA(pszSourceDir))
  2621. {
  2622. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("source dir [%s] not exists: %d", pszSourceDir,GetLastError());
  2623. strErrInfo = CSimpleStringA::Format("source dir [%s] not exists: %d", pszSourceDir, GetLastError());
  2624. return false;
  2625. }
  2626. if (!ExistsDirA(pszDestDir))
  2627. {
  2628. if (!CreateDirRecursiveA(pszDestDir))
  2629. {
  2630. strErrInfo = CSimpleStringA::Format("create dir [%s] fail: %d", pszDestDir, GetLastError());
  2631. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("create dir fail: %s",strErrInfo.GetData());
  2632. return false;
  2633. }
  2634. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("create dir [%s] succ", pszDestDir);
  2635. }
  2636. #else
  2637. if (!ExistsDirA(pszSourceDir))
  2638. {
  2639. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("source dir [%s] not exists: %d", pszSourceDir, errno);
  2640. strErrInfo = CSimpleStringA::Format("source dir [%s] not exists: %d", pszSourceDir, errno);
  2641. return false;
  2642. }
  2643. if (!ExistsDirA(pszDestDir))
  2644. {
  2645. if (!CreateDirRecursiveA(pszDestDir))
  2646. {
  2647. strErrInfo = CSimpleStringA::Format("create dir [%s] fail: %d", pszDestDir, errno);
  2648. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("create dir fail: %s",strErrInfo.GetData());
  2649. return false;
  2650. }
  2651. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("create dir [%s] succ", pszDestDir);
  2652. }
  2653. #endif
  2654. arr = fileutil_get_sub_files_a(pszSourceDir);
  2655. if (arr)
  2656. {
  2657. int i;
  2658. for (i = 0; i < arr->nelts; ++i)
  2659. {
  2660. char szDestFile[256] = { 0 };
  2661. char *file = ARRAY_IDX(arr, i, char*);
  2662. strcpy(szDestFile, pszDestDir);
  2663. if (szDestFile[strlen(szDestFile) - 1] != SPLIT_SLASH)
  2664. strcat(szDestFile, SPLIT_SLASH_STR);
  2665. strcat(szDestFile, strrchr(file, SPLIT_SLASH) + 1);
  2666. #ifdef RVC_OS_WIN
  2667. if (!CopyFileA(file, szDestFile, FALSE))
  2668. {
  2669. strErrInfo = CSimpleStringA::Format("copy file [%s] fail: %d", file, GetLastError());
  2670. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("copy file fail:%s",strErrInfo.GetData());
  2671. toolkit_array_free2(arr);
  2672. return false;
  2673. }
  2674. #else
  2675. if (fileutil_copy_file(szDestFile, file)!=0)
  2676. {
  2677. strErrInfo = CSimpleStringA::Format("copy file [%s] fail: %d", file, errno);
  2678. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("copy file fail:%s",strErrInfo.GetData());
  2679. toolkit_array_free2(arr);
  2680. return false;
  2681. }
  2682. #endif
  2683. }
  2684. toolkit_array_free2(arr);
  2685. }
  2686. arr = fileutil_get_sub_dirs_a(pszSourceDir);
  2687. if (arr)
  2688. {
  2689. int i;
  2690. for (i = 0; i < arr->nelts; ++i)
  2691. {
  2692. char szDestSubDir[256] = { 0 };
  2693. char *dir = ARRAY_IDX(arr, i, char*);
  2694. strcpy(szDestSubDir, pszDestDir);
  2695. if (szDestSubDir[strlen(szDestSubDir) - 1] != SPLIT_SLASH)
  2696. strcat(szDestSubDir, SPLIT_SLASH_STR);
  2697. strcat(szDestSubDir, strrchr(dir, SPLIT_SLASH) + 1);
  2698. if (!RecursiveCopyDir(dir, szDestSubDir,strErrInfo))
  2699. {
  2700. #ifdef RVC_OS_WIN
  2701. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("copy dir [%s] fail: %d", dir, GetLastError());
  2702. if(strErrInfo.IsNullOrEmpty()){
  2703. strErrInfo = CSimpleStringA::Format("copy dir [%s] fail: %d", dir, GetLastError());
  2704. }
  2705. toolkit_array_free2(arr);
  2706. return false;
  2707. #else
  2708. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("copy dir [%s] fail: %d", dir, errno);
  2709. if (strErrInfo.IsNullOrEmpty()) {
  2710. strErrInfo = CSimpleStringA::Format("copy dir [%s] fail: %d", dir, errno);
  2711. }
  2712. toolkit_array_free2(arr);
  2713. return false;
  2714. #endif
  2715. }
  2716. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("RecursiveCopyDir")("copy dir [%s] succ", dir);
  2717. }
  2718. toolkit_array_free2(arr);
  2719. }
  2720. return true;
  2721. }
  2722. CSimpleStringA CUpgradeTaskFSM::GetFileDirectory(const char *pszFullPath)
  2723. {
  2724. int i=strlen(pszFullPath)-1;
  2725. for( ; i>0 && pszFullPath[i]!= SPLIT_SLASH; i--)NULL;
  2726. return CSimpleStringA(pszFullPath, i);
  2727. }
  2728. bool CUpgradeTaskFSM::IsWow64Process()
  2729. {
  2730. #ifdef RVC_OS_WIN
  2731. typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  2732. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
  2733. BOOL bIsWow64 = FALSE;
  2734. if (NULL != fnIsWow64Process)
  2735. {
  2736. if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
  2737. {
  2738. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("IsWow64Process")("call IsWow64Process error: %d", GetLastError());
  2739. return false;
  2740. }
  2741. return bIsWow64 == TRUE;
  2742. }
  2743. else
  2744. {
  2745. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("IsWow64Process")("get IsWow64Process error: %d", GetLastError());
  2746. return false;
  2747. }
  2748. #endif
  2749. return true;
  2750. }
  2751. int CUpgradeTaskFSM::system_on(string cmdFilePath, bool isWait,CSimpleStringA &errMsg)
  2752. {
  2753. #ifdef RVC_OS_WIN
  2754. string cmdLine = "cmd /c ";
  2755. cmdLine.append(cmdFilePath.c_str());
  2756. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("system_on")("exec bat %s",cmdLine.c_str());
  2757. return waitSystem("cmd.exe", cmdLine.c_str(), true, errMsg);
  2758. #else
  2759. //linux直接用system函数即可
  2760. return system(cmdFilePath.c_str());
  2761. #endif
  2762. }
  2763. //返回值是0则正常执行,其他都是非正常未知状态
  2764. int CUpgradeTaskFSM::waitSystem(string cmd, const char * par, bool nShow,CSimpleStringA &errMsg)
  2765. {
  2766. #ifdef RVC_OS_WIN
  2767. SHELLEXECUTEINFOA ShExecInfo = { 0 };
  2768. ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
  2769. ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  2770. ShExecInfo.hwnd = NULL;
  2771. ShExecInfo.lpVerb = NULL;
  2772. ShExecInfo.lpFile = cmd.c_str(); //调用的程序名
  2773. ShExecInfo.lpParameters = par; //调用程序的命令行参数
  2774. ShExecInfo.lpDirectory = NULL;
  2775. ShExecInfo.nShow = nShow ? SW_MINIMIZE: SW_HIDE; //窗口状态为隐藏
  2776. ShExecInfo.hInstApp = NULL;
  2777. if (!ShellExecuteEx(&ShExecInfo))
  2778. {
  2779. errMsg = CSimpleStringA::Format("shellExecute is fail :%d",GetLastError());
  2780. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("shellExecute is fail :%s",errMsg.GetData());
  2781. return -1;
  2782. }
  2783. //等到该进程结束,如果5分钟没结束,强行杀死进程
  2784. if (WaitForSingleObject(ShExecInfo.hProcess, 5*60*1000) == WAIT_TIMEOUT)
  2785. {
  2786. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("shellExecute is time out");
  2787. errMsg = CSimpleStringA::Format("shellExecute is time out");
  2788. if (TerminateProcess(ShExecInfo.hProcess, 0))
  2789. {
  2790. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("TerminateProcess is succ");
  2791. }else {
  2792. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("TerminateProcess is fail :%d",GetLastError());
  2793. }
  2794. if (CloseHandle(ShExecInfo.hProcess))
  2795. {
  2796. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("shellExecute CloseHandle is succ");
  2797. }else {
  2798. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("shellExecute CloseHandle is fail");
  2799. }
  2800. return -1;
  2801. }
  2802. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("shellExecute is succ");
  2803. DWORD exitCode = 0;
  2804. if (!GetExitCodeProcess(ShExecInfo.hProcess, &exitCode))
  2805. {
  2806. errMsg = CSimpleStringA::Format("GetExitCodeProcess is fail:%d",GetLastError());
  2807. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("GetExitCodeProcess is fail:%s",errMsg.GetData());
  2808. return -1;
  2809. }
  2810. if (CloseHandle(ShExecInfo.hProcess))
  2811. {
  2812. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("shellExecute CloseHandle is succ");
  2813. }else {
  2814. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("shellExecute CloseHandle is fail");
  2815. }
  2816. if(exitCode!=0){
  2817. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("waitSystem")("GetExitCodeProcess ret exitCode=%d",(int)exitCode);
  2818. errMsg = CSimpleStringA::Format("GetExitCodeProcess ret exitCode=%d",(int)exitCode);
  2819. }
  2820. return exitCode;
  2821. #else
  2822. return 0;
  2823. #endif
  2824. }
  2825. char* CUpgradeTaskFSM::ConvertUtf8ToGBK(const char* strUtf8)
  2826. {
  2827. int len = MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, NULL, 0);
  2828. WCHAR* wszGBK = new WCHAR[len + 1];
  2829. memset(wszGBK, 0, len * 2 + 2);
  2830. MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, wszGBK, len);
  2831. len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
  2832. char* szGBK = new char[len + 1];
  2833. memset(szGBK, 0, len + 1);
  2834. WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
  2835. delete[] wszGBK;
  2836. return szGBK;
  2837. }
  2838. void CUpgradeTaskFSM::ConvertUtf8ToGBK(std::string &str)
  2839. {
  2840. char *dst = ConvertUtf8ToGBK(str.c_str());
  2841. str = dst;
  2842. delete[] dst;
  2843. }
  2844. char* CUpgradeTaskFSM::ConvertGBKToUtf8(const char* gbk, int *n)
  2845. {
  2846. int len = MultiByteToWideChar(CP_ACP, 0, gbk, -1, NULL, 0);
  2847. WCHAR* wszGBK = new WCHAR[len + 1];
  2848. memset(wszGBK, 0, len * 2 + 2);
  2849. MultiByteToWideChar(CP_ACP, 0, gbk, -1, wszGBK, len);
  2850. len = WideCharToMultiByte(CP_UTF8, 0, wszGBK, -1, NULL, 0, NULL, NULL);
  2851. char* szUtf8 = new char[len + 1];
  2852. memset(szUtf8, 0, len + 1);
  2853. WideCharToMultiByte(CP_UTF8, 0, wszGBK, -1, szUtf8, len, NULL, NULL);
  2854. delete[] wszGBK;
  2855. *n = len - 1;
  2856. return szUtf8;
  2857. }
  2858. void CUpgradeTaskFSM::ConvertGBKToUtf8(std::string &str)
  2859. {
  2860. int len = 0;
  2861. char *dst = ConvertGBKToUtf8(str.c_str(), &len);
  2862. str = dst;
  2863. delete[] dst;
  2864. }
  2865. bool CUpgradeTaskFSM::is_str_utf8(const char* str)
  2866. {
  2867. unsigned int nBytes = 0;//UFT8可用1-6个字节编码,ASCII用一个字节
  2868. unsigned char chr = *str;
  2869. bool bAllAscii = true;
  2870. for (unsigned int i = 0; str[i] != '\0'; ++i) {
  2871. chr = *(str + i);
  2872. //判断是否ASCII编码,如果不是,说明有可能是UTF8,ASCII用7位编码,最高位标记为0,0xxxxxxx
  2873. if (nBytes == 0 && (chr & 0x80) != 0) {
  2874. bAllAscii = false;
  2875. }
  2876. if (nBytes == 0) {
  2877. //如果不是ASCII码,应该是多字节符,计算字节数
  2878. if (chr >= 0x80) {
  2879. if (chr >= 0xFC && chr <= 0xFD) {
  2880. nBytes = 6;
  2881. }
  2882. else if (chr >= 0xF8) {
  2883. nBytes = 5;
  2884. }
  2885. else if (chr >= 0xF0) {
  2886. nBytes = 4;
  2887. }
  2888. else if (chr >= 0xE0) {
  2889. nBytes = 3;
  2890. }
  2891. else if (chr >= 0xC0) {
  2892. nBytes = 2;
  2893. }
  2894. else {
  2895. return false;
  2896. }
  2897. nBytes--;
  2898. }
  2899. }
  2900. else {
  2901. //多字节符的非首字节,应为 10xxxxxx
  2902. if ((chr & 0xC0) != 0x80) {
  2903. return false;
  2904. }
  2905. //减到为零为止
  2906. nBytes--;
  2907. }
  2908. }
  2909. //违返UTF8编码规则
  2910. if (nBytes != 0) {
  2911. return false;
  2912. }
  2913. if (bAllAscii) { //如果全部都是ASCII, 也是UTF8
  2914. return true;
  2915. }
  2916. return true;
  2917. }
  2918. ErrorCodeEnum CUpgradeTaskFSM::UnzipPack(const char* unZipPackName)
  2919. {
  2920. #ifdef RVC_OS_WIN
  2921. // 设定解压临时目录
  2922. char szOldPath[MAX_PATH] = {};
  2923. GetCurrentDirectoryA(MAX_PATH, szOldPath);
  2924. CSimpleStringA strDownloadsPath;
  2925. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
  2926. if(rc!=Error_Succeed){
  2927. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,get Downloads Path is fail");
  2928. return Error_Unexpect;
  2929. }
  2930. CSimpleStringA strZipFile = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), unZipPackName);
  2931. //升级包是否存在
  2932. if(!ExistsFileA(strZipFile)){
  2933. LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
  2934. return Error_NotExist;
  2935. }
  2936. CSimpleStringA strUnzipDir;
  2937. strUnzipDir = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), unZipPackName);
  2938. //解压去除了.zip后缀
  2939. if (strUnzipDir.IsEndWith(".zip")){
  2940. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
  2941. }
  2942. // 解压目录是否存在,则先删除
  2943. if (ExistsDirA(strUnzipDir.GetData()))
  2944. {
  2945. if(!RemoveDirRecursiveA(strUnzipDir.GetData())){
  2946. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,delete exist temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
  2947. return Error_Unexpect;
  2948. }
  2949. }
  2950. // 创建临时解压目录
  2951. if(!CreateDirectoryA(strUnzipDir.GetData(), NULL)){
  2952. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,create temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
  2953. return Error_Unexpect;
  2954. }
  2955. //设置当前目录为主目录
  2956. if(!SetCurrentDirectoryA(strUnzipDir.GetData())){
  2957. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzipPack is fail,SetCurrentDirectoryA dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
  2958. return Error_Unexpect;
  2959. }
  2960. // 解压
  2961. HZIP hz = OpenZip((void*)(const char*)strZipFile,0,ZIP_FILENAME);
  2962. if (hz == 0)
  2963. {
  2964. SetCurrentDirectoryA(szOldPath);
  2965. LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("open zip file [%s] fail", unZipPackName).GetData());
  2966. return Error_Unexpect;
  2967. }
  2968. ZIPENTRY ze;
  2969. ZRESULT zrc = GetZipItemA(hz,-1,&ze);
  2970. if(zrc == ZR_OK){
  2971. int numitems=ze.index;
  2972. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UnzipPack")("zip entry count is %d",ze.index);
  2973. for (int i=0; i<numitems; i++)
  2974. {
  2975. zrc = GetZipItemA(hz,i,&ze);
  2976. if(zrc==ZR_OK){
  2977. //兼容压缩包里面中文名称是utf8编码
  2978. if(is_str_utf8(ze.name)){
  2979. char *pGBK = ConvertUtf8ToGBK((const char*)ze.name);
  2980. zrc = UnzipItem(hz,i,pGBK,0,ZIP_FILENAME);
  2981. if(zrc ==ZR_OK){
  2982. //Dbg("unzip [%s] UTF8 item succeed", pGBK);
  2983. delete[] pGBK;
  2984. }else{
  2985. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip [%s] UTF8 item fail,result=0x%X", pGBK,(int)zrc);
  2986. delete[] pGBK;
  2987. break;
  2988. }
  2989. }else{
  2990. zrc = UnzipItem(hz,i,ze.name,0,ZIP_FILENAME);
  2991. if(zrc ==ZR_OK){
  2992. //Dbg("unzip [%s] GBK item succeed", ze.name);
  2993. }else{
  2994. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip [%s] GBK item fail,result=0x%X", ze.name,(int)zrc);
  2995. break;
  2996. }
  2997. }
  2998. }else{
  2999. //出错,退出
  3000. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("UnzipPack")("unzip GetZipItemA [%d] item fail,fail=0x%X",i,(int)zrc);
  3001. break;
  3002. }
  3003. }
  3004. CloseZip(hz);
  3005. }else{
  3006. CloseZip(hz);
  3007. }
  3008. // 恢复当前目录
  3009. SetCurrentDirectoryA(szOldPath);
  3010. if(zrc!=ZR_OK){
  3011. return Error_Exception;
  3012. }
  3013. return Error_Succeed;
  3014. #else
  3015. CSimpleStringA strDownloadsPath;
  3016. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
  3017. if (rc != Error_Succeed) {
  3018. Dbg("unzipPack is fail,get Downloads Path is fail");
  3019. return Error_Unexpect;
  3020. }
  3021. CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
  3022. //升级包是否存在
  3023. if (!ExistsFileA(strZipFile)) {
  3024. LogError(Severity_Low, Error_NotExist, 0, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
  3025. return Error_NotExist;
  3026. }
  3027. CSimpleStringA strUnzipDir;
  3028. strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
  3029. //解压去除了.zip后缀
  3030. if (strUnzipDir.IsEndWith(".zip")) {
  3031. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  3032. }
  3033. // 解压目录是否存在,存在先删除
  3034. if (ExistsDirA(strUnzipDir.GetData()))
  3035. {
  3036. if (!RemoveDirRecursiveA(strUnzipDir.GetData())) {
  3037. Dbg("unzipPack is fail,delete exist temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), errno);
  3038. return Error_Unexpect;
  3039. }
  3040. }
  3041. // 创建临时解压目录
  3042. if (!CreateDirA(strUnzipDir.GetData(), false)) {
  3043. // 创建临时解压目录失败
  3044. Dbg("unzipPack is fail,create temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), errno);
  3045. return Error_Unexpect;
  3046. }
  3047. if (changeFileAtt(strZipFile.GetData())!=0) {
  3048. //改变文件属性
  3049. Dbg("unzipPack is fail,changeFileAtt zip [%s] fail,err=%d", strZipFile.GetData(), errno);
  3050. return Error_Unexpect;
  3051. }
  3052. // 解压
  3053. string zipFileStr = strZipFile.GetData();
  3054. string zipTempDir = strUnzipDir.GetData();
  3055. if (UnZipToDir(zipFileStr, zipTempDir) != 0)
  3056. {
  3057. LogError(Severity_Low, Error_Unexpect, 0, CSimpleStringA::Format("unzip pack [%s] fail", unZipPackName));
  3058. return Error_NotExist;
  3059. }
  3060. return Error_Succeed;
  3061. #endif
  3062. }
  3063. ErrorCodeEnum CUpgradeTaskFSM::DeleteUnzipDir()
  3064. {
  3065. CSimpleStringA strDownloadsPath;
  3066. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
  3067. if(rc!=Error_Succeed){
  3068. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DeleteUnzipDir")("DeleteUnzipDir is fail,get Downloads Path is fail");
  3069. return Error_Unexpect;
  3070. }
  3071. //判断解压缩文件夹名是否存在,不存在告警
  3072. if (m_currentTask.pack_name.IsNullOrEmpty()) {
  3073. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("DeleteUnzipDir")("DeleteUnzipDir is fail ,temp unzip dir name is null");
  3074. return Error_Unexpect;
  3075. }
  3076. CSimpleStringA strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), m_currentTask.pack_name.GetData());
  3077. //解压去除了.zip后缀
  3078. if (strUnzipDir.IsEndWith(".zip")){
  3079. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
  3080. }
  3081. // 解压目录是否存在,存在则删除
  3082. if (ExistsDirA(strUnzipDir.GetData()))
  3083. {
  3084. if(!RemoveDirRecursiveA(strUnzipDir.GetData())){
  3085. #ifdef RVC_OS_WIN
  3086. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DeleteUnzipDir")("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),(int)GetLastError());
  3087. #else
  3088. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DeleteUnzipDir")("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(), errno);
  3089. #endif
  3090. return Error_Unexpect;
  3091. }else{
  3092. return Error_Succeed;
  3093. }
  3094. }
  3095. return Error_Succeed;
  3096. }
  3097. void CUpgradeTaskFSM::SendUpgradeTaskProgress(CTaskProcess &process)
  3098. {
  3099. Json::Value root;
  3100. Json::FastWriter fw;//写入对象
  3101. if(!process.strPackName.IsNullOrEmpty()){
  3102. root["strPackName"]=process.strPackName.GetData();
  3103. }else{
  3104. root["strPackName"]="";
  3105. }
  3106. if(process.installVersion.IsNullOrEmpty()){
  3107. root["installVersion"]="0.0.0.0";
  3108. }else{
  3109. root["installVersion"]=process.installVersion.GetData();
  3110. }
  3111. string currentBuildStr = CSimpleStringA::Format("%d.%d.%d",process.CurrentVersion.GetMajor(),process.CurrentVersion.GetMinor(),process.CurrentVersion.GetRevision()).GetData();
  3112. root["CurrentVersion"]=process.CurrentVersion.ToString().GetData();
  3113. root["CurrentBuild"]=currentBuildStr.c_str();
  3114. root["upgradeTimeStr"]=CSmallDateTime::GetNow().ToTimeString().GetData();
  3115. if(!process.cInstallState.IsNullOrEmpty()){
  3116. root["cInstallState"]=process.cInstallState.GetData();
  3117. }else{
  3118. root["cInstallState"]="";
  3119. }
  3120. if(!process.strInstallComment.IsNullOrEmpty()){
  3121. CSimpleStringA comment = "task:";
  3122. comment.Append(process.strInstallComment.GetData());
  3123. root["strInstallComment"]=comment.GetData();
  3124. }else{
  3125. root["strInstallComment"]="";
  3126. }
  3127. string upgradeStr = fw.write(root);
  3128. if(!upgradeStr.empty()){
  3129. LogWarn(Severity_Low,Error_Succeed,LOG_WRAN_UPGRADE_PROGRESS,upgradeStr.c_str());
  3130. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SendUpgradeTaskProgress")(upgradeStr.c_str());
  3131. }else{
  3132. LogError(Severity_Middle,Error_Unexpect,ERR_WRAN_UPGRADE_PROGRESS,"获取升级过程信息错误");
  3133. }
  3134. }
  3135. ErrorCodeEnum CUpgradeTaskFSM::GetRunConfigStrValue(const char *pszSection, const char *pszKey, CSimpleStringA &strValue)
  3136. {
  3137. CSmartPointer<IConfigInfo> pConfig;
  3138. ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_Run, pConfig);
  3139. if (rc != Error_Succeed){
  3140. return rc;
  3141. }
  3142. return pConfig->ReadConfigValue(pszSection, pszKey, strValue);
  3143. }
  3144. ErrorCodeEnum CUpgradeTaskFSM::SetRunConfigStrValue(const char *pszSection, const char *pszKey, const char *pszValue)
  3145. {
  3146. CSmartPointer<IConfigInfo> pConfig;
  3147. ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_Run, pConfig);
  3148. if (rc != Error_Succeed){
  3149. return rc;
  3150. }
  3151. return pConfig->WriteConfigValue(pszSection, pszKey, pszValue);
  3152. }
  3153. bool CUpgradeTaskFSM::ClearCurrTaskInfo()
  3154. {
  3155. if(SetRunConfigStrValue("upgradeTask","UpgradeTaskId","")!=Error_Succeed){
  3156. return false;
  3157. }
  3158. if(SetRunConfigStrValue("upgradeTask","CreateTaskVersion","")!=Error_Succeed){
  3159. return false;
  3160. }
  3161. if(SetRunConfigStrValue("upgradeTask","PackName","")!=Error_Succeed){
  3162. return false;
  3163. }
  3164. if(SetRunConfigStrValue("upgradeTask","PendingState","")!=Error_Succeed){
  3165. return false;
  3166. }
  3167. if(SetRunConfigStrValue("upgradeTask","NewVersion","")!=Error_Succeed){
  3168. return false;
  3169. }
  3170. //试着删除可能临时下载的升级包文件
  3171. CSimpleStringA strPath;
  3172. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strPath);
  3173. if(Error_Succeed != rc){
  3174. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ClearCurrTaskInfo")("ClearCurrTaskInfo get Downloads path fail,upgradeTaskId=%s",m_currentTask.upgradeTaskId.GetData());
  3175. return false;
  3176. }
  3177. CSimpleStringA tempPackPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s%s", strPath.GetData(), m_currentTask.pack_name.GetData(),".tmp");
  3178. if(ExistsFileA(tempPackPath.GetData())){
  3179. if(!RemoveFileA(tempPackPath.GetData())){
  3180. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ClearCurrTaskInfo")("ClearCurrTaskInfo delete tempPack fail,packPath=%s",tempPackPath.GetData());
  3181. return false;
  3182. }
  3183. }
  3184. //清空内存变量
  3185. m_currentTask.upgradeTaskId = "";
  3186. m_currentTask.createTaskVersion = "";
  3187. m_currentTask.pack_name = "";
  3188. m_currentTask.cPendingState = "";
  3189. m_currentTask.NewVersion="";
  3190. m_currentTask.pack_version = "";
  3191. m_currentTask.stop_media_play =false;
  3192. m_currentTask.reboot_type = 0;
  3193. m_currentTask.file_path="";
  3194. m_currentTask.download_url = "";
  3195. m_currentTask.pack_hash = "";
  3196. m_currentTask.pack_length = 0;
  3197. //清理安装步骤
  3198. //int iCount = m_currentTask.install_step.size();
  3199. //for (int j = 0; j < iCount; j++){
  3200. // CInstallStep* tmp = m_currentTask.install_step.front();
  3201. // m_currentTask.install_step.pop();
  3202. // delete tmp;//删除对象
  3203. //}
  3204. ClearInstallStep();
  3205. return true;
  3206. }
  3207. bool CUpgradeTaskFSM::ClearInstallStep()
  3208. {
  3209. //清理安装步骤
  3210. int iCount = m_currentTask.install_step.size();
  3211. for (int j = 0; j < iCount; j++){
  3212. CInstallStep* tmp = m_currentTask.install_step.front();
  3213. m_currentTask.install_step.pop();
  3214. delete tmp;//删除对象
  3215. }
  3216. return true;
  3217. }
  3218. ErrorCodeEnum CUpgradeTaskFSM::LoadPersistTaskInfo()
  3219. {
  3220. // 从运行配置中读出上次未处理完的任务
  3221. // 上次未安装结束
  3222. CTaskInfo taskInfo = {};
  3223. CSimpleStringA strValue;
  3224. ErrorCodeEnum rc = GetRunConfigStrValue("upgradeTask", "UpgradeTaskId", strValue);
  3225. if(rc!=Error_Succeed){
  3226. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, read [upgradeTask][UpgradeTaskId] fail ,err=%d",(int)rc);
  3227. return rc;
  3228. }
  3229. taskInfo.upgradeTaskId = strValue;
  3230. rc = GetRunConfigStrValue("upgradeTask", "CreateTaskVersion", strValue);
  3231. if(rc!=Error_Succeed){
  3232. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, read [upgradeTask][CreateTaskVersion] fail ,err=%d",(int)rc);
  3233. return rc;
  3234. }
  3235. taskInfo.createTaskVersion = strValue;
  3236. rc = GetRunConfigStrValue("upgradeTask", "PackName", strValue);
  3237. if(rc!=Error_Succeed){
  3238. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, read [upgradeTask][PackName] fail ,err=%d",(int)rc);
  3239. return rc;
  3240. }
  3241. taskInfo.pack_name = strValue;
  3242. rc = GetRunConfigStrValue("upgradeTask", "PendingState", strValue);
  3243. if(rc!=Error_Succeed){
  3244. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, read [upgradeTask][PendingState] fail ,err=%d",(int)rc);
  3245. return rc;
  3246. }
  3247. taskInfo.cPendingState = strValue;
  3248. rc = GetRunConfigStrValue("upgradeTask", "NewVersion", strValue);
  3249. if(rc!=Error_Succeed){
  3250. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, read [upgradeTask][NewVersion] fail ,err=%d",(int)rc);
  3251. return rc;
  3252. }
  3253. taskInfo.NewVersion = strValue;
  3254. //初始化其他变量
  3255. //CSimpleStringA pack_version; //升级包指定的版本号
  3256. //CSimpleStringA to_copy; //拷贝文件列表
  3257. //CSimpleStringA to_run; //体系外运行脚本文件名称
  3258. //bool reboot_type; //重启类型
  3259. //CSimpleStringA download_url; //升级包下载地址
  3260. //CSimpleStringA pack_hash; //升级包hash值
  3261. //long pack_length; //升级包长度
  3262. taskInfo.pack_version = "";
  3263. taskInfo.reboot_type = 0;
  3264. taskInfo.file_path = "";
  3265. taskInfo.download_url = "";
  3266. taskInfo.pack_hash = "";
  3267. taskInfo.pack_length = 0;
  3268. taskInfo.stop_media_play = true;
  3269. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, UpgradeTaskId=%s", taskInfo.upgradeTaskId.GetData());
  3270. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, CreateTaskVersion=%s",taskInfo.createTaskVersion.GetData());
  3271. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, PackName=%s",taskInfo.pack_name.GetData());
  3272. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, PendingState=%s",taskInfo.cPendingState.GetData());
  3273. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("LoadPersistTaskInfo")("recover upgrade state from run config, NewVersion=%s",taskInfo.NewVersion.GetData());
  3274. m_currentTask = taskInfo;
  3275. return Error_Succeed;
  3276. }
  3277. ErrorCodeEnum CUpgradeTaskFSM::loadCenterCfgInfo()
  3278. {
  3279. //访问http地址的读取
  3280. CSmartPointer<IConfigInfo> spConfig;
  3281. ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  3282. if (rc == Error_Succeed){
  3283. CSimpleStringA str="";
  3284. //加载后端服务访问地址
  3285. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryPreTaskUrl", str);
  3286. if(rc==Error_Succeed){
  3287. m_centerUrl.queryPreTaskUrl = str;
  3288. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini QueryPreTaskUrl=%s",str.GetData());
  3289. }else{
  3290. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryPreTaskUrl error");
  3291. return rc;
  3292. }
  3293. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryContinueTaskUrl", str);
  3294. if(rc==Error_Succeed){
  3295. m_centerUrl.queryContinueTaskUrl = str;
  3296. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini QueryContinueTaskUrl=%s",str.GetData());
  3297. }else{
  3298. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryContinueTaskUrl error");
  3299. return rc;
  3300. }
  3301. rc = spConfig->ReadConfigValue("UpgradeManager", "UpdateTaskUrl", str);
  3302. if(rc==Error_Succeed){
  3303. m_centerUrl.updateTaskUrl = str;
  3304. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini UpdateTaskUrl=%s",str.GetData());
  3305. }else{
  3306. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini UpdateTaskUrl error");
  3307. return rc;
  3308. }
  3309. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryCurrTaskUrl", str);
  3310. if(rc==Error_Succeed){
  3311. m_centerUrl.queryCurrTaskUrl = str;
  3312. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini QueryCurrTaskUrl=%s",str.GetData());
  3313. }else{
  3314. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryCurrTaskUrl error");
  3315. return rc;
  3316. }
  3317. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryNewTaskUrl", str);
  3318. if(rc==Error_Succeed){
  3319. m_centerUrl.queryNewTaskUrl = str;
  3320. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini QueryNewTaskUrl=%s",str.GetData());
  3321. }else{
  3322. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryNewTaskUrl error");
  3323. return rc;
  3324. }
  3325. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryTaskStatus", str);
  3326. if(rc==Error_Succeed){
  3327. m_centerUrl.queryTaskStatus = str;
  3328. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini QueryTaskStatus=%s",str.GetData());
  3329. }else{
  3330. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryTaskStatus error");
  3331. return rc;
  3332. }
  3333. rc = spConfig->ReadConfigValue("UpgradeManager", "SendSM3TaskUrl", str);
  3334. if(rc==Error_Succeed){
  3335. m_centerUrl.sendSM3TaskUrl = str;
  3336. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini SendSM3TaskUrl=%s",str.GetData());
  3337. }else{
  3338. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini SendSM3TaskUrl error");
  3339. return rc;
  3340. }
  3341. //加载下载分段切片长度值(单位M)
  3342. rc = spConfig->ReadConfigValue("UpgradeManager", "EachDownloadLen", str);
  3343. if(rc==Error_Succeed){
  3344. if(str.IsNullOrEmpty()){
  3345. m_eachDownloadLen = DOWNLOAD_CONTENT_EACH_LEN;
  3346. }else{
  3347. m_eachDownloadLen = atoi(str.GetData())*1024*1024;
  3348. }
  3349. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini EachDownloadLen=%s m",str.GetData());
  3350. }else{
  3351. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini EachDownloadLen error");
  3352. return rc;
  3353. }
  3354. //新的下载分段切片长度值(单位K)
  3355. rc = spConfig->ReadConfigValue("UpgradeManager", "NewEachDownloadLen", str);
  3356. if(rc==Error_Succeed){
  3357. if(str.IsNullOrEmpty()){
  3358. m_newEachDownloadLen = DOWNLOAD_CONTENT_EACH_LEN;
  3359. }else{
  3360. if(atoi(str.GetData())>16){
  3361. m_newEachDownloadLen = atoi(str.GetData())*1024;
  3362. }else{
  3363. m_newEachDownloadLen = 16*1024;//设置默认最小值
  3364. }
  3365. }
  3366. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini NewEachDownloadLen=%s K",str.GetData());
  3367. }else{
  3368. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini NewEachDownloadLen error");
  3369. return rc;
  3370. }
  3371. //加载是否打印http通讯日志
  3372. int printlogInt =0;
  3373. rc = spConfig->ReadConfigValueInt("UpgradeManager", "PrintLog", printlogInt);
  3374. if(rc==Error_Succeed){
  3375. if(printlogInt==0){
  3376. m_PrintHttpLog = false;
  3377. }else{
  3378. m_PrintHttpLog = true;
  3379. }
  3380. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini PrintLog=%d",printlogInt);
  3381. }else{
  3382. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini PrintLog error");
  3383. return rc;
  3384. }
  3385. int startFlagInt =0;
  3386. rc = spConfig->ReadConfigValueInt("UpgradeManager", "StartFlag", startFlagInt);
  3387. if(rc==Error_Succeed){
  3388. if(startFlagInt==0){
  3389. m_startFlag = false;
  3390. }else{
  3391. m_startFlag = true;
  3392. }
  3393. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini StartFlag=%d",startFlagInt);
  3394. }else{
  3395. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini StartFlag error");
  3396. return rc;
  3397. }
  3398. //加载扫描hash配置文件列表
  3399. rc = spConfig->ReadConfigValue("UpgradeManager", "relativeDir", str);
  3400. if(rc==Error_Succeed){
  3401. m_hashScanSet.relativeDir = str;
  3402. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini relativeDir=%s",str.GetData());
  3403. }else{
  3404. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini relativeDir error");
  3405. return rc;
  3406. }
  3407. rc = spConfig->ReadConfigValue("UpgradeManager", "absoluteDir", str);
  3408. if(rc==Error_Succeed){
  3409. m_hashScanSet.absoluteDir = str;
  3410. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini absoluteDir=%s",str.GetData());
  3411. }else{
  3412. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini absoluteDir error");
  3413. return rc;
  3414. }
  3415. rc = spConfig->ReadConfigValue("UpgradeManager", "currVerDir", str);
  3416. if(rc==Error_Succeed){
  3417. m_hashScanSet.currVerDir = str;
  3418. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini currVerDir=%s",str.GetData());
  3419. }else{
  3420. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini currVerDir error");
  3421. return rc;
  3422. }
  3423. rc = spConfig->ReadConfigValue("UpgradeManager", "blackFile", str);
  3424. if(rc==Error_Succeed){
  3425. m_hashScanSet.blackFile = str;
  3426. CAutoArray<CSimpleStringA> arr = str.Split('|');
  3427. for(int i=0; i< arr.GetCount(); i++)
  3428. {
  3429. m_FileBlacklist.push_back(arr[i]);
  3430. }
  3431. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini blackFile=%s",str.GetData());
  3432. }else{
  3433. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini blackFile error");
  3434. return rc;
  3435. }
  3436. rc = spConfig->ReadConfigValue("UpgradeManager", "blackDir", str);
  3437. if(rc==Error_Succeed){
  3438. m_hashScanSet.blackDir = str;
  3439. CAutoArray<CSimpleStringA> arr = str.Split('|');
  3440. for(int i=0; i< arr.GetCount(); i++)
  3441. {
  3442. m_DirBlacklist.push_back(arr[i]);
  3443. }
  3444. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("loadCenterCfgInfo")("init read CenterSetting.ini blackDir=%s",str.GetData());
  3445. }else{
  3446. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini blackDir error");
  3447. return rc;
  3448. }
  3449. }else{
  3450. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini error");
  3451. return rc;
  3452. }
  3453. return Error_Succeed;
  3454. }
  3455. bool CUpgradeTaskFSM::GetFileLength(const char* filePath,long &fileLen)
  3456. {
  3457. FILE* file = fopen(filePath, "rb");
  3458. if (file!=NULL)
  3459. {
  3460. #ifdef RVC_OS_WIN
  3461. fileLen = filelength(fileno(file));
  3462. fclose(file);
  3463. return true;
  3464. #else
  3465. if (fseek(file, 0, SEEK_END)!=0) {
  3466. Dbg("GetFileLength fseek is error,%s",strerror(errno));
  3467. fclose(file);
  3468. fileLen = 0;
  3469. return false;
  3470. }
  3471. fileLen = ftell(file); ///求出当前文件指针距离文件开始的字节数
  3472. if (fileLen == -1) {
  3473. Dbg("GetFileLength ftell is error,%s", strerror(errno));
  3474. fclose(file);
  3475. fileLen = 0;
  3476. return false;
  3477. }
  3478. else {
  3479. fclose(file);
  3480. return true;
  3481. }
  3482. #endif
  3483. } else{
  3484. fileLen = 0;
  3485. return false;
  3486. }
  3487. return true;
  3488. }
  3489. ErrorCodeEnum CUpgradeTaskFSM::GetSM3List(CSimpleStringA &strSM3List)
  3490. {
  3491. if (!m_fileSM3List.IsNullOrEmpty())
  3492. {
  3493. strSM3List = m_fileSM3List;
  3494. return Error_Succeed;
  3495. }
  3496. m_fileSM3Map.clear();//生成文件hash列表前先清空
  3497. //根据配置项开始扫描文件和计算hash
  3498. ErrorCodeEnum rc = Error_Succeed ;
  3499. if(!m_hashScanSet.absoluteDir.IsNullOrEmpty()){
  3500. //绝对路径扫描
  3501. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3List")("GetSM3List scan absoluteDir=%s",m_hashScanSet.absoluteDir.GetData());
  3502. rc = ScanSM3ByType(1,m_hashScanSet.absoluteDir);
  3503. if(rc!=Error_Succeed){
  3504. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3List")("GetMD5List fail ,scan absoluteDir is fail");
  3505. return rc;
  3506. }
  3507. }
  3508. if(!m_hashScanSet.relativeDir.IsNullOrEmpty()){
  3509. //相对路径扫描
  3510. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3List")("GetSM3List scan relativeDir=%s",m_hashScanSet.relativeDir.GetData());
  3511. ScanSM3ByType(2,m_hashScanSet.relativeDir);
  3512. if(rc!=Error_Succeed){
  3513. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3List")("GetMD5List fail ,scan relativeDir is fail");
  3514. return rc;
  3515. }
  3516. }
  3517. if(!m_hashScanSet.currVerDir.IsNullOrEmpty()){
  3518. //当前版本扫描
  3519. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3List")("GetSM3List scan currVerDir=%s",m_hashScanSet.currVerDir.GetData());
  3520. ScanSM3ByType(3,m_hashScanSet.currVerDir);
  3521. if(rc!=Error_Succeed){
  3522. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3List")("GetMD5List fail ,scan currVerDir is fail");
  3523. return rc;
  3524. }
  3525. }
  3526. if(m_iBlackFileCount>50){
  3527. LogWarn(Severity_Low, rc, WARN_BLACK_FILE_SUM, CSimpleStringA::Format("get MD5List black file count=%d",m_iBlackFileCount));
  3528. }
  3529. m_iBlackFileCount=0;
  3530. for(auto it=m_fileSM3Map.begin(); it!=m_fileSM3Map.end(); it++)
  3531. {
  3532. strSM3List += it->first;
  3533. strSM3List += ",";
  3534. strSM3List += it->second;
  3535. strSM3List += ";";
  3536. }
  3537. m_fileSM3List = strSM3List;
  3538. return Error_Succeed;
  3539. }
  3540. ErrorCodeEnum CUpgradeTaskFSM::ScanSM3ByType(int type,CSimpleStringA pathFilter)
  3541. {
  3542. if(!pathFilter.IsNullOrEmpty()){
  3543. CSimpleStringA rootPath;//根路径
  3544. CSimpleStringA replacePath;//替换路径
  3545. CSimpleStringA currPath;//当前版本路径
  3546. CSimpleStringA tempPath ="";
  3547. ErrorCodeEnum Error =m_pEntity->GetFunction()->GetPath("Root",tempPath);//例如:C:\Run /opt/Run
  3548. if(Error_Succeed == Error){
  3549. if(!tempPath.IsNullOrEmpty()){
  3550. string runPathStr = tempPath.GetData();
  3551. int pos = runPathStr.find_last_of(SPLIT_SLASH);
  3552. rootPath = runPathStr.substr(0,pos).c_str();
  3553. }else{
  3554. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ScanSM3ByType")("ScanSM3ByType get Root path is null");
  3555. return Error_Null;
  3556. }
  3557. }else{
  3558. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ScanSM3ByType")("ScanSM3ByType get Root path is error");
  3559. return Error;
  3560. }
  3561. CSimpleStringA tempCurrPath = "";
  3562. Error =m_pEntity->GetFunction()->GetPath("Base",tempCurrPath);//例如:C:\Run\version\4.8.1.1 /opt/Run/version/4.8.1.1
  3563. if(Error_Succeed == Error){
  3564. if(!tempCurrPath.IsNullOrEmpty()){
  3565. currPath = tempCurrPath;
  3566. }else{
  3567. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ScanSM3ByType")("ScanSM3ByType get currVer path is null");
  3568. return Error_Null;
  3569. }
  3570. }else{
  3571. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("ScanSM3ByType")("ScanSM3ByType get currVer path is error");
  3572. return Error;
  3573. }
  3574. //路径扫描
  3575. CAutoArray<CSimpleStringA> copyList = pathFilter.Split('|');
  3576. for(int i=0; i<copyList.GetCount(); i++)
  3577. {
  3578. CSimpleStringA file = copyList[i];
  3579. #ifdef RVC_OS_WIN
  3580. #else
  3581. //UOS把路径改为反斜杠
  3582. string replaceStr = file.GetData();
  3583. std::replace(replaceStr.begin(), replaceStr.end(), '\\', '/');
  3584. file = replaceStr.c_str();
  3585. #endif
  3586. if(file.IsNullOrEmpty()){
  3587. continue;
  3588. }else{
  3589. //构造扫描的绝对路径
  3590. CSimpleStringA scanFilter = "";
  3591. CSimpleStringA replaceDir = "";
  3592. if(type==1){
  3593. //绝对路径
  3594. scanFilter = file;
  3595. replaceDir = GetFileDirectory(file.GetData());
  3596. }else if(type==2){
  3597. //相对路径
  3598. scanFilter = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),file.GetData());
  3599. replaceDir = GetFileDirectory(file.GetData());
  3600. }else if(type==3){
  3601. //当前版本路径:特殊处理下替换路径为Run\version\4.8.1.1
  3602. scanFilter = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",currPath.GetData(),file.GetData());
  3603. CSimpleStringA temp = scanFilter.SubString(rootPath.GetLength()+1,scanFilter.GetLength()-(rootPath.GetLength()+1));
  3604. replaceDir = GetFileDirectory(temp.GetData());
  3605. }
  3606. //替换路径前缀
  3607. ErrorCodeEnum ret = NewSM3Folder(scanFilter,replaceDir);
  3608. if(ret!=Error_Succeed){
  3609. return ret;
  3610. }
  3611. }
  3612. }
  3613. }
  3614. return Error_Succeed;
  3615. }
  3616. ErrorCodeEnum CUpgradeTaskFSM::NewSM3Folder(CSimpleStringA scanFilter,CSimpleStringA replaceDir)
  3617. {
  3618. if(scanFilter.IsNullOrEmpty()){
  3619. return Error_Succeed;
  3620. }
  3621. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("NewSM3Folder")("scan file scanFilter is %s",scanFilter.GetData());
  3622. //通配符
  3623. if(scanFilter.IndexOf("*")>0){
  3624. //找到要扫描的文件夹
  3625. CSimpleStringA strFileDir = GetFileDirectory(scanFilter.GetData());
  3626. //过滤通配条件
  3627. CSimpleStringA strFileFilter = _GetFileName(scanFilter.GetData());
  3628. list<CSimpleStringA> fileList;
  3629. //获取所有根文件夹下的文件相对路径:如mod\test.dll
  3630. RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
  3631. for(auto it = fileList.begin(); it != fileList.end(); it++)
  3632. {
  3633. CSimpleStringA tempFile = *it;
  3634. if (IsFileMatch(strFileFilter, _GetFileName(tempFile.GetData())))
  3635. {
  3636. CSimpleStringA tempFullName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",strFileDir.GetData(),tempFile.GetData());
  3637. CSimpleStringA tempFileName = _GetFileName(tempFile.GetData());
  3638. CSimpleStringA tempFileDir = GetFileDirectory(tempFile.GetData());
  3639. //整个黑名单文件过滤
  3640. bool isBlackFile = false;
  3641. list<CSimpleStringA>::iterator itorFile = m_FileBlacklist.begin();
  3642. while(itorFile!=m_FileBlacklist.end())
  3643. {
  3644. CSimpleStringA fileBlack = *itorFile;
  3645. //if(tempFileName.IsEndWith(fileBlack.GetData(),true)){
  3646. // isBlackFile=true;
  3647. // break;
  3648. //}
  3649. if(IsFileMatch(fileBlack.GetData(),tempFileName.GetData())){
  3650. isBlackFile=true;
  3651. break;
  3652. }
  3653. itorFile++;
  3654. }
  3655. if(isBlackFile){
  3656. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("NewSM3Folder")("BlackFile Filter don't add to md5 list, file = [%s]", tempFullName.GetData());
  3657. m_iBlackFileCount++;
  3658. continue;
  3659. }
  3660. //整个黑名单文件夹过滤
  3661. bool isBlackDir = false;
  3662. list<CSimpleStringA>::iterator itorDir = m_DirBlacklist.begin();
  3663. while(itorDir!=m_DirBlacklist.end())
  3664. {
  3665. CSimpleStringA dirBlack = *itorDir;
  3666. if(tempFileDir.IndexOf(dirBlack.GetData())>0){
  3667. isBlackDir=true;
  3668. break;
  3669. }
  3670. itorDir++;
  3671. }
  3672. if(isBlackDir){
  3673. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("NewSM3Folder")("BlackDir Filter don't add to md5 list, dir = [%s]", tempFullName.GetData());
  3674. continue;
  3675. }
  3676. //计算hash值,加入到hash列表
  3677. CSimpleStringA strMD5Val;
  3678. ErrorCodeEnum rErrcode = SM3FileToStr(tempFullName, strMD5Val,false);
  3679. if (Error_Succeed != rErrcode)
  3680. {
  3681. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("NewSM3Folder")("%s get sm3 fail ,error:%d", tempFullName.GetData(), (int)rErrcode);
  3682. return rErrcode;
  3683. }
  3684. CSimpleStringA relativePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",replaceDir.GetData(),tempFile.GetData());
  3685. //Dbg("scan file succ [%s]",relativePath.GetData());
  3686. m_fileSM3Map[relativePath] = strMD5Val;
  3687. Sleep(100);//时间片
  3688. }
  3689. }
  3690. }else{
  3691. if(ExistsFileA(scanFilter.GetData())){
  3692. //整个黑名单文件过滤
  3693. bool isBlackFile = false;
  3694. CSimpleStringA tempFileName = _GetFileName(scanFilter.GetData());//文件名称
  3695. CSimpleStringA tempFileDir = GetFileDirectory(scanFilter.GetData());//文件夹名称
  3696. list<CSimpleStringA>::iterator itorFile = m_FileBlacklist.begin();
  3697. while(itorFile!=m_FileBlacklist.end())
  3698. {
  3699. CSimpleStringA fileBlack = *itorFile;
  3700. //if(scanFilter.IsEndWith(fileBlack.GetData(),true)){
  3701. // isBlackFile=true;
  3702. // break;
  3703. //}
  3704. if(IsFileMatch(fileBlack.GetData(),tempFileName.GetData())){
  3705. isBlackFile=true;
  3706. break;
  3707. }
  3708. itorFile++;
  3709. }
  3710. if(isBlackFile){
  3711. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("NewSM3Folder")("BlackFile Filter don't add to md5 list, file = [%s]", scanFilter.GetData());
  3712. m_iBlackFileCount++;
  3713. }
  3714. //整个黑名单文件夹过滤
  3715. bool isBlackDir = false;
  3716. list<CSimpleStringA>::iterator itorDir = m_DirBlacklist.begin();
  3717. while(itorDir!=m_DirBlacklist.end())
  3718. {
  3719. CSimpleStringA dirBlack = *itorDir;
  3720. if(tempFileDir.IndexOf(dirBlack.GetData())>0){
  3721. isBlackDir=true;
  3722. break;
  3723. }
  3724. itorDir++;
  3725. }
  3726. if(isBlackDir){
  3727. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("NewSM3Folder")("BlackDir Filter don't add to md5 list, dir = [%s]", scanFilter.GetData());
  3728. }
  3729. if(!isBlackDir&&!isBlackFile){
  3730. //加入hash列表
  3731. CSimpleStringA strMD5Val;
  3732. ErrorCodeEnum rErrcode = SM3FileToStr(scanFilter, strMD5Val,false);
  3733. if (Error_Succeed != rErrcode)
  3734. {
  3735. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("NewSM3Folder")("%s get sm3 fail ,error:%d", scanFilter.GetData(), (int)rErrcode);
  3736. return rErrcode;
  3737. }
  3738. CSimpleStringA tempFileName = _GetFileName(scanFilter.GetData());
  3739. CSimpleStringA relativePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",replaceDir.GetData(),tempFileName.GetData());
  3740. //Dbg("scan file succ [%s]",relativePath.GetData());
  3741. #ifdef RVC_OS_WIN
  3742. #else
  3743. Sleep(100);//加入时间碎片
  3744. #endif
  3745. m_fileSM3Map[relativePath] = strMD5Val;
  3746. }
  3747. }
  3748. }
  3749. return Error_Succeed;
  3750. }
  3751. ErrorCodeEnum CUpgradeTaskFSM::SM3FileToStr(CSimpleStringA strFilePath, CSimpleStringA &strSM3,bool isSub)
  3752. {
  3753. if(strFilePath.IsNullOrEmpty()){
  3754. return Error_Null;
  3755. }
  3756. int nlen = strlen(strFilePath.GetData());
  3757. char* pchar = new char[nlen+1];
  3758. strcpy(pchar,strFilePath.GetData());
  3759. BYTE md5[32]={0};
  3760. try
  3761. {
  3762. if(SM3File(pchar,md5)){
  3763. delete[] pchar;
  3764. //获取16进制的字符串
  3765. if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
  3766. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3 to hex str fail,file=%s",strFilePath.GetData());
  3767. return Error_Unexpect;
  3768. }
  3769. return Error_Succeed;
  3770. }else{
  3771. delete[] pchar;
  3772. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3 encrypt fail ,file=%s",strFilePath.GetData());
  3773. return Error_Unexpect;
  3774. }
  3775. }
  3776. catch (...)
  3777. {
  3778. delete[] pchar;
  3779. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3FileToStr")("sm3 encrypt exception ,file=%s",strFilePath.GetData());
  3780. return Error_Exception;
  3781. }
  3782. }
  3783. ErrorCodeEnum CUpgradeTaskFSM::SM3DataToStr(CSimpleStringA strData, CSimpleStringA &strSM3,bool isSub)
  3784. {
  3785. if(strData.IsNullOrEmpty()){
  3786. return Error_Null;
  3787. }
  3788. BYTE md5[32]={0};
  3789. try
  3790. {
  3791. if(SM3Hash((BYTE*)strData.GetData(),strlen(strData.GetData()),md5)){
  3792. //获取16进制的字符串
  3793. if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
  3794. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3DataToStr")("sm3 to hex str fail");
  3795. return Error_Unexpect;
  3796. }
  3797. return Error_Succeed;
  3798. }else{
  3799. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3DataToStr")("sm3 encrypt fail");
  3800. return Error_Unexpect;
  3801. }
  3802. }
  3803. catch (...)
  3804. {
  3805. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SM3DataToStr")("sm3 encrypt exception");
  3806. return Error_Exception;
  3807. }
  3808. }
  3809. ErrorCodeEnum CUpgradeTaskFSM::SM3_Str(CSimpleStringA &strSM3,BYTE * SM3Byte,bool isSub)
  3810. {
  3811. if(SM3Byte == NULL){
  3812. return Error_Exception;
  3813. }
  3814. int SM3_len=64;
  3815. if(isSub){
  3816. SM3_len=32;
  3817. }
  3818. int i;
  3819. char* file_SM3 = (char*)malloc((SM3_len + 1) * sizeof(char));
  3820. if(file_SM3 == NULL)
  3821. {
  3822. fprintf(stderr, "SM3 malloc failed.\n");
  3823. return Error_Exception;
  3824. }
  3825. memset(file_SM3, 0, (SM3_len + 1));
  3826. if(SM3_len == 32)
  3827. {
  3828. for(i=0; i<16; i++)
  3829. { //SM3截取中间16位字节,8-24位字节数,小写
  3830. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i+8]);
  3831. }
  3832. }
  3833. else if(SM3_len == 64)
  3834. {
  3835. for(i=0; i<32; i++)
  3836. {
  3837. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i]);
  3838. }
  3839. }
  3840. strSM3=file_SM3;
  3841. free(file_SM3);
  3842. return Error_Succeed;
  3843. }
  3844. bool CUpgradeTaskFSM::IsPackDownloaded(const char *packPath,const char* packHash,long packLen)
  3845. {
  3846. if(!ExistsFileA(packPath)){
  3847. return false;//文件不存在,下载
  3848. }
  3849. //计算hash值
  3850. CSimpleStringA strMD5Val;
  3851. ErrorCodeEnum rc = SM3FileToStr(packPath, strMD5Val,false);
  3852. if (Error_Succeed != rc)
  3853. {
  3854. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("IsPackDownloaded")("%s get download pack sm3 fail ,error:%d", packPath, (int)rc);
  3855. return false;//获取hash码失败,下载
  3856. }
  3857. //不区分大小写比较文件hash
  3858. #ifdef RVC_OS_WIN
  3859. if(stricmp(strMD5Val.GetData(),packHash)==0){
  3860. #else
  3861. if(strcmp(strMD5Val.GetData(),packHash)==0){
  3862. #endif
  3863. return true;//相同,不下载
  3864. }else{
  3865. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("IsPackDownloaded")("%s sm3[%s] is no equal upgrade sm3[%s], retry download.", packPath, strMD5Val.GetData(), packHash);
  3866. return false;//不相同,下载
  3867. }
  3868. }
  3869. bool CUpgradeTaskFSM::DownloadFileWrite(byte* content,long contentLen,const char* filePath)
  3870. {
  3871. if(contentLen==0){
  3872. return true;
  3873. }
  3874. FILE* tempFp = fopen(filePath,"ab");
  3875. if(tempFp==NULL){
  3876. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadFileWrite")("DownloadFileWrite open file fail");
  3877. return false;
  3878. }
  3879. int ret = fwrite(content,(size_t)contentLen,1,tempFp);
  3880. fclose(tempFp);
  3881. if(ret!=1){
  3882. #ifdef RVC_OS_WIN
  3883. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadFileWrite")("DownloadFileWrite write file fail,ret = %d,errno = %d",ret,(int)GetLastError());
  3884. return false;
  3885. #else
  3886. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadFileWrite")("DownloadFileWrite write file fail,ret = %d,errno = %d",ret, errno);
  3887. return false;
  3888. #endif
  3889. }
  3890. return true;
  3891. }
  3892. bool CUpgradeTaskFSM::CheckIfCanSwitchNow()
  3893. {
  3894. //对于终端初始化安装时,直接通过。
  3895. if (isTerminalInstall()) {
  3896. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow terminal new install,return true");
  3897. return true;
  3898. }
  3899. //非重启操作,则直接可以进行切换,不用等待时机
  3900. if(m_currentTask.reboot_type == 0){
  3901. return true;
  3902. }
  3903. CSimpleStringA strCustomerHandle;
  3904. CSimpleStringA strCallState;
  3905. // 无交互N、客户关注A、客户在控制终端C、柜员协助T、柜员代操作G
  3906. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetSysVar("CustomerHandle", strCustomerHandle);
  3907. if(rc!=Error_Succeed){
  3908. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow get CustomerHandle value is fail ,err=%d",(int)rc);
  3909. return false;
  3910. }
  3911. // 离线O、尝试连线柜员C、免提通话H、连线失败F、断线B
  3912. rc = m_pEntity->GetFunction()->GetSysVar("CallState", strCallState);
  3913. if(rc!=Error_Succeed){
  3914. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow get CallState value is fail ,err=%d",(int)rc);
  3915. return false;
  3916. }
  3917. #ifdef RVC_OS_WIN
  3918. SYSTEMTIME st = {};
  3919. GetLocalTime(&st);
  3920. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("hour is %d",(int)st.wHour);
  3921. bool bOffworkTime = st.wHour < 8 || st.wHour >= 21;
  3922. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("hour is %d, strCustomerHandle=%s, strCallState=%s, bOffworkTime=%d",(int)st.wHour,strCustomerHandle.GetData(),strCallState.GetData(),(int)bOffworkTime);
  3923. #else
  3924. time_t nowTime = time(NULL);
  3925. tm nowTimeTm = { 0 };
  3926. localtime_r(&nowTime, &nowTimeTm);
  3927. //Dbg("hour is %d", (int)nowTimeTm.tm_hour);
  3928. bool bOffworkTime = nowTimeTm.tm_hour < 8 || nowTimeTm.tm_hour >= 21;
  3929. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("hour is %d, strCustomerHandle=%s, strCallState=%s, bOffworkTime=%d",(int)nowTimeTm.tm_hour,strCustomerHandle.GetData(),strCallState.GetData(),(int)bOffworkTime);
  3930. #endif
  3931. // 或者下班时间且非连线状态 @20151202
  3932. // 客户关注状态A,不允许切换 by zl 20191113
  3933. if (strCustomerHandle[0] == 'N' || (bOffworkTime && strCallState[0] == 'O')) {
  3934. return true;
  3935. }
  3936. else {
  3937. // 防止感知一直误报有人状态,加入以下特例:如果是一天当中首次从切换状态直接跳转过来的升级切换,并且当前是首页则进行切换
  3938. if (!bOffworkTime) {
  3939. CSimpleStringA strUIState;
  3940. // M 首页
  3941. rc = m_pEntity->GetFunction()->GetSysVar("UIState", strUIState);
  3942. if (rc != Error_Succeed) {
  3943. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow get strUIState value is fail ,err=%d", (int)rc);
  3944. return false;
  3945. }
  3946. #ifdef RVC_OS_WIN
  3947. CSimpleStringA nowStr = CSimpleStringA::Format("%d-%d-%d", st.wYear, st.wMonth, st.wDay).GetData();
  3948. #else
  3949. CSimpleStringA nowStr = CSimpleStringA::Format("%d-%d-%d", nowTimeTm.tm_year+1900, nowTimeTm.tm_mon+1, nowTimeTm.tm_mday).GetData();
  3950. #endif
  3951. //读取强制切换的日期
  3952. CSimpleStringA ForceSwitchDateStr = "";
  3953. ErrorCodeEnum rc = GetRunConfigStrValue("upgradeTask", "ForceSwitchDate", ForceSwitchDateStr);
  3954. if (rc != Error_Succeed) {
  3955. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow read from run config, read [upgradeTask][ForceSwitchDate] fail ,err=%d", (int)rc);
  3956. return false;
  3957. }
  3958. //首页并且切换状态直接进入
  3959. if (strUIState.Compare("M") == 0 && m_bSwitchFlag) {
  3960. //当天是否切换过
  3961. if (ForceSwitchDateStr.Compare(nowStr.GetData()) == 0) {
  3962. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow is not ForceSwitch, ForceSwitchDate[%s]", ForceSwitchDateStr.GetData());
  3963. return false;
  3964. }
  3965. else {
  3966. //直接切换,并写入强制切换日期
  3967. if (SetRunConfigStrValue("upgradeTask", "ForceSwitchDate", nowStr.GetData()) != Error_Succeed) {
  3968. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow write run config, write [upgradeTask][ForceSwitchDate] fail[%s],err=%d", nowStr.GetData(), (int)rc);
  3969. }
  3970. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow ForceSwitch, ForceSwitchDate[%s]", nowStr.GetData());
  3971. return true;
  3972. }
  3973. }
  3974. else {
  3975. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("CheckIfCanSwitchNow")("CheckIfCanSwitchNow is not ForceSwitch, UIState=%s,m_bSwitchFlag=%d", strUIState.GetData(),(int)m_bSwitchFlag);
  3976. return false;
  3977. }
  3978. }
  3979. else {
  3980. return false;
  3981. }
  3982. }
  3983. }
  3984. ErrorCodeEnum CUpgradeTaskFSM::SwitchUpgradeNow()
  3985. {
  3986. //默认轻量包不重启系统和框架,体系外系统不重启系统,系统升级重启框架
  3987. //根据重启策略类型去重启
  3988. //重启策略类型(0:不启动 1:重启框架 2:重启系统)
  3989. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SwitchUpgradeNow")("begin SwitchUpgradeNow");
  3990. if(m_currentTask.reboot_type == 0){
  3991. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SwitchUpgradeNow")("upgrade to new version [%s] succeed, taskID=[%s] ", m_currentVersion.ToString().GetData(),m_currentTask.upgradeTaskId.GetData());
  3992. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  3993. }else if(m_currentTask.reboot_type == 1){
  3994. if(m_currentTask.NewVersion.IsNullOrEmpty()){
  3995. //非版本升级
  3996. LogEvent(Severity_Middle, Event_Req_Framework_No_Upgrade_Restart,
  3997. CSimpleStringA::Format("upgrade to new version [%s] succeed, request to no upgrade restart framework , taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  3998. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  3999. }else{
  4000. //版本升级,健康有后续回退处理
  4001. LogEvent(Severity_Middle, Event_Req_Framework_Restart,
  4002. CSimpleStringA::Format("upgrade to new version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  4003. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  4004. }
  4005. }else if(m_currentTask.reboot_type == 2){
  4006. LogEvent(Severity_Middle, Event_Req_OS_Restart,
  4007. CSimpleStringA::Format("SysPackInstall upgrade to new version [%s] succeed, request to restart OS, taskID=[%s]", m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData()));
  4008. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  4009. }else{
  4010. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("SwitchUpgradeNow")("reSetType=[%d] is invalid ,upgrade to new version [%s] fail, taskID=[%s]",m_currentTask.reboot_type, m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData());
  4011. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  4012. }
  4013. // 强制刷新日志
  4014. m_pEntity->GetFunction()->FlushLogFile();
  4015. return Error_Succeed;
  4016. }
  4017. ErrorCodeEnum CUpgradeTaskFSM::DownloadProgress(long tempFileLen,long fileSumLen)
  4018. {
  4019. UpgradeDownloadProgress dProgress;
  4020. dProgress.currentFile = m_currentTask.pack_name;
  4021. dProgress.fileNum = 1;
  4022. dProgress.progress=0;
  4023. if(fileSumLen!=0){
  4024. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("tempFileLen =%d , fileSumLen =%d",tempFileLen,fileSumLen);
  4025. dProgress.progress = (int)(tempFileLen/(fileSumLen/100));
  4026. if(dProgress.progress ==10||dProgress.progress ==20||dProgress.progress ==30||dProgress.progress ==40||dProgress.progress ==50
  4027. ||dProgress.progress ==60||dProgress.progress ==70||dProgress.progress ==80||dProgress.progress ==90)
  4028. {
  4029. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("download progress is %d ,tempFileLen =%d , fileSumLen =%d",dProgress.progress,tempFileLen,fileSumLen);
  4030. }
  4031. //Dbg("download file [%s] progress is %d",dProgress.currentFile.GetData(),dProgress.progress);
  4032. ErrorCodeEnum retError = SpSendBroadcast(GetEntityBase()->GetFunction(), SP_MSG_OF(UpgradeDownloadProgress), SP_MSG_SIG_OF(UpgradeDownloadProgress), dProgress);
  4033. return retError;
  4034. }else{
  4035. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("download file [%s] progress is fail,sumlen=0");
  4036. return Error_Exception;
  4037. }
  4038. }
  4039. char CUpgradeTaskFSM::GetInstallState(int nState)
  4040. {
  4041. if (nState == s4)
  4042. return 'U';
  4043. else if (nState == s5)
  4044. return 'I';
  4045. else if (nState == s6)
  4046. return 'S';
  4047. else
  4048. return 'N';
  4049. }
  4050. ErrorCodeEnum CUpgradeTaskFSM::GetUpgradeState(bool &bInstalling, CSimpleStringA &strPackFile, CSimpleStringA &strExecID, char &cInstallState, bool &bSysInstall, bool &bLightPack, CSimpleStringA &strNewVersion)
  4051. {
  4052. bInstalling = !m_currentTask.upgradeTaskId.IsNullOrEmpty();
  4053. if (bInstalling)
  4054. {
  4055. strPackFile = m_currentTask.pack_name;
  4056. strExecID = m_currentTask.upgradeTaskId;
  4057. cInstallState = GetInstallState(m_iState);
  4058. bSysInstall = false;
  4059. bLightPack = false;
  4060. //if(!m_currentTask.to_run.IsNullOrEmpty()){
  4061. // bSysInstall = true;
  4062. //}else{
  4063. // bSysInstall = false;
  4064. //}
  4065. //if(m_currentTask.pack_version.IsNullOrEmpty()){
  4066. // bLightPack = true;
  4067. //}else{
  4068. // bLightPack = false;
  4069. //}
  4070. strNewVersion = m_currentTask.NewVersion;
  4071. }
  4072. return Error_Succeed;
  4073. }
  4074. void CUpgradeTaskFSM::HttpsLogCallBack(const char* logtxt)
  4075. {
  4076. DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI("HttpsLogCallBack")("http dbg: %s",logtxt);
  4077. }
  4078. bool CUpgradeTaskFSM::isWork()
  4079. {
  4080. //兜底方案是判断集中配置一个参数,去除其他变量的判断,但是容易出现任务状态更新不准的情况。
  4081. if(m_startFlag){
  4082. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("isWork")("upgrade startFlag is true");
  4083. return true;
  4084. }
  4085. //判断是否在设备安装状态,不受一般升级影响
  4086. if (isTerminalInstall()) {
  4087. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("isWork")("isTerminalInstall get TerminalStage is N");
  4088. return true;
  4089. }
  4090. else {
  4091. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("isWork")("isTerminalInstall get TerminalStage is not N");
  4092. }
  4093. //判断升级实体是否工作
  4094. //1.当有版本升级任务时,判断是否处于Guardian升级回退过程,如果已经升级成功或者回退成功,则开始工作,否则等待中
  4095. //2.当无任务或者非版本升级任务时,判断TerminalStage这个变量,非X状态,当A状态并且进入首页,则开始工作
  4096. //升级任务
  4097. if((!m_currentTask.NewVersion.IsNullOrEmpty())&&(m_currentTask.cPendingState=="T"||m_currentTask.cPendingState=="C"||m_currentTask.cPendingState=="X")){
  4098. CSimpleStringA strRunInfo,strStartTime;
  4099. if (m_pEntity->GetFunction()->GetPath("RunInfo",strRunInfo) == Error_Succeed){
  4100. #ifdef RVC_OS_WIN
  4101. strStartTime = strRunInfo + "\\runcfg\\starttime.dat";
  4102. #else
  4103. strStartTime = strRunInfo + "/runcfg/starttime.dat";
  4104. #endif
  4105. if(!ExistsFileA(strStartTime.GetData())){
  4106. return true;//完成升级过程,通过
  4107. }else{
  4108. #ifdef RVC_OS_WIN
  4109. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("isWork")("upgrade process is not end ,file \\runcfg\\starttime is exist");
  4110. #else
  4111. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("isWork")("upgrade process is not end ,file /runcfg/starttime is exist");
  4112. #endif
  4113. return false;//继续等待
  4114. }
  4115. }else{
  4116. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("isWork")("upgrade process is not end ,get runinfo path is error");
  4117. return false;//失败,继续等待
  4118. }
  4119. }
  4120. //非升级任务和无任务
  4121. CSimpleStringA strValue;
  4122. if(m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed){
  4123. if(strValue.Compare("X")==0){
  4124. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("isWork")("TerminalStage = X ,continue wait");
  4125. return false;//状态是x继续等待
  4126. }
  4127. if(strValue.Compare("A")==0){
  4128. if(((CUpgradeMgrEntity*)m_pEntity)->m_bStartUp){
  4129. return true;//通过
  4130. }else{
  4131. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("isWork")("TerminalStage = A ,but UIState is not M , continue wait");
  4132. return false;//准入过,但进入首页,继续等待
  4133. }
  4134. }
  4135. return true;//剩余其他状态都可以通过
  4136. }else{
  4137. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("isWork")("get TerminalStage is error , continue wait");
  4138. return false;//失败,继续等待
  4139. }
  4140. }
  4141. bool CUpgradeTaskFSM::isAuthSucc() {
  4142. CSimpleStringA strValue;
  4143. if (m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed) {
  4144. if (strValue.Compare("A") == 0) {
  4145. return true;
  4146. }
  4147. else {
  4148. return false;
  4149. }
  4150. }
  4151. else {
  4152. return false;
  4153. }
  4154. }
  4155. bool CUpgradeTaskFSM::isTerminalInstall() {
  4156. CSimpleStringA strValue;
  4157. if (m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed) {
  4158. if (strValue.Compare("N") == 0) {
  4159. return true; //表示安装模式
  4160. }else{
  4161. return false;
  4162. }
  4163. }
  4164. else {
  4165. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("isTerminalInstall")("isTerminalInstall get TerminalStage is error , default return fasle");
  4166. return false;//默认认为在升级状态
  4167. }
  4168. }
  4169. void CUpgradeTaskFSM::upgradeSuccStateBroadCast() {
  4170. UpgradeStateEvent stateEvent;
  4171. stateEvent.strPackName = m_currentTask.pack_name.GetData();
  4172. stateEvent.strExecID = m_currentTask.upgradeTaskId.GetData();
  4173. stateEvent.cInstallState = 'A';//表示成功状态
  4174. stateEvent.bSysInstall = false;
  4175. stateEvent.bLightPack = false;
  4176. stateEvent.strNewVersion = m_currentTask.NewVersion;
  4177. SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
  4178. }
  4179. #ifdef RVC_OS_WIN
  4180. #else
  4181. int CUpgradeTaskFSM::changeFileAtt(const char* path)
  4182. {
  4183. struct stat attr_of_del;
  4184. if (lstat(path, &attr_of_del) == 0)
  4185. {
  4186. //修改为775属性
  4187. mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
  4188. if (chmod(path, f_attrib) != 0)
  4189. {
  4190. Dbg("set file attribute is fail,errno=%d, file=%s", errno, path);
  4191. return -1;
  4192. }
  4193. return 0;
  4194. }
  4195. else {
  4196. Dbg("get file attribute is fail,errno=%d, file=%s", errno, path);
  4197. return -1;
  4198. }
  4199. }
  4200. #endif
  4201. void CUpgradeTaskFSM::OnStateTrans(int iSrcState, int iDstState)
  4202. {
  4203. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnStateTrans")("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
  4204. if (iSrcState >= s4 && iDstState <= s3)
  4205. {
  4206. // 发送状态广播(通知业务界面清除状态)
  4207. UpgradeStateEvent stateEvent;
  4208. stateEvent.strPackName = "";
  4209. stateEvent.strExecID = "";
  4210. stateEvent.cInstallState = 'N';
  4211. stateEvent.bSysInstall = false;
  4212. stateEvent.bLightPack = false;
  4213. stateEvent.strNewVersion = "";
  4214. SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
  4215. }
  4216. else if (iDstState >= s4)
  4217. {
  4218. //assert(HasRunningUpdate());
  4219. //SetRunConfigStrValue("Install", "Pack", m_strIntallingPack);
  4220. //if (iDstState == s3)
  4221. // SetRunConfigStrValue("Install", "PendingState", "U");
  4222. //else if (iDstState == s4)
  4223. // SetRunConfigStrValue("Install", "PendingState", "I");
  4224. //else if (iDstState == s5)
  4225. // SetRunConfigStrValue("Install", "PendingState", "C");
  4226. //else if (iDstState == s6)
  4227. // SetRunConfigStrValue("Install", "PendingState", "S");
  4228. // 发送状态广播
  4229. UpgradeStateEvent stateEvent;
  4230. stateEvent.strPackName = m_currentTask.pack_name.GetData();
  4231. stateEvent.strExecID = m_currentTask.upgradeTaskId.GetData();
  4232. stateEvent.cInstallState = GetInstallState(iDstState);
  4233. stateEvent.bSysInstall = false;
  4234. stateEvent.bLightPack = false;
  4235. stateEvent.strNewVersion = m_currentTask.NewVersion;
  4236. SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
  4237. }
  4238. }
  4239. void CUpgradeTaskFSM::OnSysVarEvent(const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName)
  4240. {
  4241. //监听系统变量状态
  4242. if(strcmp("CallState",pszKey)==0){
  4243. if (pszValue[0] == 'O') {
  4244. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnSysVarEvent")("m_bDownloadIdle is false ");
  4245. m_bDownloadIdle = false;//可以下载
  4246. } else {
  4247. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnSysVarEvent")("m_bDownloadIdle is true");
  4248. m_bDownloadIdle = true;//不能下载
  4249. }
  4250. }
  4251. }
  4252. ErrorCodeEnum CUpgradeTaskFSM::OnInit()
  4253. {
  4254. //初始化
  4255. ErrorCodeEnum rc = LoadPersistTaskInfo();//加载运行时文件
  4256. if(rc!=Error_Succeed){
  4257. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("LoadPersistTaskInfo fail");
  4258. return rc;
  4259. }
  4260. rc = loadCenterCfgInfo();//加载集中配置文件
  4261. if(rc!=Error_Succeed){
  4262. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("loadCenterCfgInfo fail");
  4263. return rc;
  4264. }
  4265. //加载终端启动的版本号
  4266. CSystemStaticInfo info;
  4267. rc = m_pEntity->GetFunction()->GetSystemStaticInfo(info);
  4268. if(rc!=Error_Succeed){
  4269. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("load GetSystemStaticInfo fail ");
  4270. return rc;
  4271. }else{
  4272. m_currentVersion = info.InstallVersion;//当前版本号赋值
  4273. }
  4274. //注册callstate变量监控
  4275. rc = m_pEntity->GetFunction()->RegistSysVarEvent("CallState", this);
  4276. if(rc!=Error_Succeed){
  4277. LogWarn(Severity_Middle, rc, ERR_WRAN_REGIST_SYS_VAR_FAIL, CSimpleStringA::Format("RegistSysVarEvent CallState is fail,%d",(int)rc).GetData());
  4278. return rc;//自检失败
  4279. }else{
  4280. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("OnInit")("RegistSysVarEvent UIState succ");
  4281. }
  4282. AddStateHooker(this);
  4283. ((CUpgradeMgrEntity*)m_pEntity)->testActive();//添加测试active文件是否被占用的方法
  4284. return Error_Succeed;
  4285. }
  4286. ErrorCodeEnum CUpgradeTaskFSM::OnExit()
  4287. {
  4288. m_pEntity->GetFunction()->UnregistSysVarEvent("CallState");
  4289. RemoveStateHooker(this);
  4290. return Error_Succeed;
  4291. }
  4292. void CUpgradeTaskFSM::s1_on_entry()
  4293. {
  4294. //判断是否进入了首页
  4295. CSimpleStringA strValue;
  4296. if(isWork()&&((CUpgradeMgrEntity*)m_pEntity)->m_initSucc){
  4297. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("====upgrade is start up ====");
  4298. ScheduleTimer(2,10*1000);//首次进入等待hash时间
  4299. }else{
  4300. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("last upgrade progress is not end or is not initSucc,wait 10s ");
  4301. ScheduleTimer(1, 10*1000);//等待一段时间再判断是否进入首页
  4302. }
  4303. }
  4304. void CUpgradeTaskFSM::s1_on_exit()
  4305. {
  4306. CancelTimer(1);//等待进入首页计时器
  4307. CancelTimer(2);//等待hash计算计时器
  4308. }
  4309. unsigned int CUpgradeTaskFSM::s1_on_event(FSMEvent* event)
  4310. {
  4311. if (event->iEvt == EVT_TIMER)
  4312. {
  4313. if(event->param1 == 1){
  4314. CSimpleStringA strValue;
  4315. if(isWork()&&((CUpgradeMgrEntity*)m_pEntity)->m_initSucc){
  4316. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("====upgrade is start up ====");
  4317. ScheduleTimer(2,10*1000);//首次进入等待hash时间
  4318. }else{
  4319. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("last upgrade progress is not end or is not initSucc,wait 10s ");
  4320. ScheduleTimer(1, 10*1000);//等待一段时间再判断是否进入首页
  4321. }
  4322. }else if(event->param1 ==2){
  4323. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入s2
  4324. }
  4325. }
  4326. return 0;
  4327. }
  4328. void CUpgradeTaskFSM::s2_on_entry()
  4329. {
  4330. //判断是否存在残留任务
  4331. if(m_currentTask.upgradeTaskId.IsNullOrEmpty()&&m_currentTask.cPendingState.IsNullOrEmpty()){
  4332. //直接进入查询新任务
  4333. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  4334. }else{
  4335. //处理上个任务
  4336. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));
  4337. }
  4338. }
  4339. void CUpgradeTaskFSM::s2_on_exit()
  4340. {
  4341. CancelTimer(1);//更新任务状态计时器
  4342. CancelTimer(2);//查询当前任务计时器
  4343. }
  4344. unsigned int CUpgradeTaskFSM::s2_on_event(FSMEvent* event)
  4345. {
  4346. if (event->iEvt == EVT_TIMER){
  4347. if(event->param1 == 1){
  4348. Task::UpdateTaskStatus* uTask = new Task::UpdateTaskStatus(this);
  4349. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(uTask);
  4350. if(Error_Succeed!=rc){
  4351. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create UpdateTaskStatus is fail,%d",(int)rc);
  4352. ScheduleTimer(1,60*1000);//继续更新任务状态
  4353. }
  4354. }else if(event->param1 == 2){
  4355. Task::QueryCurrTask* qTask = new Task::QueryCurrTask(this);
  4356. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
  4357. if(Error_Succeed!=rc){
  4358. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create QueryCurrTask is fail,%d",(int)rc);
  4359. ScheduleTimer(2,4*60*1000);//继续查询当前任务
  4360. }
  4361. }
  4362. }else if (event->iEvt == Event_DealCurrTask)
  4363. {
  4364. //处理运行时文件异常记录的情况
  4365. if(m_currentTask.upgradeTaskId.IsNullOrEmpty()||m_currentTask.createTaskVersion.IsNullOrEmpty()
  4366. ||m_currentTask.cPendingState.IsNullOrEmpty()||m_currentTask.pack_name.IsNullOrEmpty()){
  4367. //有任务时,则4个字段不能为空,否则任务有问题
  4368. CSimpleStringA errStr = CSimpleStringA::Format("current Task param is null, clear this task, upgradeTaskId=[%s],createTaskVersion=[%s],cPendingState=[%s],PackName=[%s]",
  4369. m_currentTask.upgradeTaskId.GetData(),m_currentTask.createTaskVersion.GetData(),m_currentTask.cPendingState.GetData(),m_currentTask.pack_name.GetData());
  4370. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK,errStr.GetData());
  4371. if(ClearCurrTaskInfo()){
  4372. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  4373. }else{
  4374. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
  4375. Sleep(5 * 1000);//等待五秒,继续清理
  4376. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
  4377. }
  4378. }else{
  4379. //任务已到最终状态
  4380. if(m_currentTask.cPendingState=="T"||m_currentTask.cPendingState=="C"||m_currentTask.cPendingState=="X"){
  4381. //取消任务C和切换任务T时,更新任务状态
  4382. Task::UpdateTaskStatus* uTask = new Task::UpdateTaskStatus(this);
  4383. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(uTask);
  4384. if(Error_Succeed!=rc){
  4385. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create UpdateTaskStatus is fail,%d",(int)rc);
  4386. ScheduleTimer(1,60*1000);//继续更新任务状态
  4387. }
  4388. }else{
  4389. //当前任务
  4390. if(m_currentTask.createTaskVersion!=m_currentVersion.ToString()){
  4391. //比较遗留任务的创建版本号是否和现在版本一致,不一致,则可能出现拷贝别的终端文件或者已经手工改了别的版本引发,这种情况下自动清理此次任务。
  4392. CSimpleStringA errStr = CSimpleStringA::Format("current Task createTaskVersion[%s] is not equal to currentVersion[%s],clear this task",m_currentTask.createTaskVersion.GetData(),m_currentVersion.ToString().GetData());
  4393. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK,errStr.GetData());
  4394. if(ClearCurrTaskInfo()){
  4395. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  4396. }else{
  4397. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 2,retry int 5's");
  4398. Sleep(5 * 1000);//等待五秒,继续清理
  4399. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
  4400. }
  4401. }else{
  4402. Task::QueryCurrTask* qTask = new Task::QueryCurrTask(this);
  4403. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
  4404. if(Error_Succeed!=rc){
  4405. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create QueryCurrTask is fail,%d",(int)rc);
  4406. ScheduleTimer(2,4*60*1000);//继续查询当前任务
  4407. }
  4408. }
  4409. }
  4410. }
  4411. }else if(event->iEvt == Event_EndUpdateTask){
  4412. //更新任务状态返回结果
  4413. UpdateTaskStatusEvent* pEvent = (UpdateTaskStatusEvent*)event;
  4414. if(pEvent->isSucc){
  4415. //告警回滚和升级成功
  4416. if(m_currentTask.cPendingState=="T"){
  4417. if(m_currentTask.NewVersion==m_currentVersion.ToString()||m_currentTask.NewVersion==""){
  4418. //安装成功
  4419. struct CTaskProcess up;
  4420. up.strPackName = m_currentTask.pack_name;//安装包名
  4421. up.installVersion = m_currentVersion.ToString();//当前的版本
  4422. up.CurrentVersion = m_currentVersion;//当前的版本
  4423. up.cInstallState = "A";
  4424. up.strInstallComment = "启动成功";
  4425. SendUpgradeTaskProgress(up);
  4426. upgradeSuccStateBroadCast();//广播告知升级成功
  4427. if(m_currentTask.NewVersion.IsNullOrEmpty()){
  4428. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_START_ID)("体系外升级启动成功");
  4429. }else{
  4430. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_START_ID)("终端版本升级启动成功");
  4431. }
  4432. }else{
  4433. //回滚
  4434. struct CTaskProcess upRoll;
  4435. upRoll.strPackName = m_currentTask.pack_name;//安装包名
  4436. upRoll.installVersion = m_currentTask.NewVersion.GetData();//任务升级后的版本号
  4437. upRoll.CurrentVersion = m_currentVersion;//当前的版本
  4438. upRoll.cInstallState = "R";
  4439. upRoll.strInstallComment = "自动倒回";
  4440. SendUpgradeTaskProgress(upRoll);
  4441. if(m_currentTask.NewVersion.IsNullOrEmpty()){
  4442. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_START_ID).setResultCode("RTA5632")("升级启动失败,回滚上一个版本");
  4443. }else{
  4444. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_START_ID).setResultCode("RTA5631")("升级启动失败,回滚上一个版本");
  4445. }
  4446. }
  4447. ErrorCodeEnum rc = SetRunSucceed(m_currentTask.pack_name.GetData());
  4448. if(rc!=Error_Succeed){
  4449. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("SetRunSucceed is fail: %d",(int)rc);
  4450. }
  4451. }
  4452. //清除运行时文件和内存任务,跳转到S3
  4453. if(ClearCurrTaskInfo()){
  4454. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  4455. }else{
  4456. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndUpdateTask clear current task is fail,retry int 5's");
  4457. Sleep(5 * 1000);//等待五秒,继续清理
  4458. PostEventFIFO(new UpdateTaskStatusEvent(true));//继续更新任务状态
  4459. }
  4460. }else{
  4461. ScheduleTimer(1,60*1000);//继续更新任务状态
  4462. }
  4463. }else if(event->iEvt == Event_EndQueryCurrTask){
  4464. //查询当前任务返回结果
  4465. QueryCurrTaskEvent* pEvent = (QueryCurrTaskEvent*)event;
  4466. if(pEvent->isSucc){
  4467. if(pEvent->isTask_valid){
  4468. //根据不同任务状态值,进入不同阶段。U:下载阶段,I:安装阶段,S切换阶段
  4469. if(m_currentTask.cPendingState=="U"){
  4470. return 4;//下载
  4471. }else if(m_currentTask.cPendingState=="I"){
  4472. return 5;//安装
  4473. }else if(m_currentTask.cPendingState=="S"){
  4474. //加入切换标志,用于切换时判断是否是切换进入的流程。
  4475. m_bSwitchFlag = true;
  4476. return 6;//切换
  4477. }else{
  4478. //无效状态
  4479. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_STATUS_FAIL,CSimpleStringA::Format("invalid pending state : %s",m_currentTask.cPendingState.GetData()).GetData());
  4480. //任务无效,清理任务
  4481. if(ClearCurrTaskInfo()){
  4482. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  4483. }else{
  4484. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndQueryCurrTask clear current task is fail 2,retry int 5's");
  4485. Sleep(5 * 1000);//等待五秒,继续清理
  4486. PostEventFIFO(new QueryCurrTaskEvent(true,true));//继续清理当前任务
  4487. }
  4488. }
  4489. }else{
  4490. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK,CSimpleStringA::Format("current task is invalid taskid=%s, begin delete",m_currentTask.upgradeTaskId.GetData()).GetData());
  4491. //任务无效,清理任务
  4492. if(ClearCurrTaskInfo()){
  4493. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  4494. }else{
  4495. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndQueryCurrTask clear current task is fail 1,retry int 5's");
  4496. Sleep(5 * 1000);//等待五秒,继续清理
  4497. PostEventFIFO(new QueryCurrTaskEvent(true,false));//继续清理当前任务
  4498. }
  4499. }
  4500. }else{
  4501. ScheduleTimer(2,4*60*1000);//继续查询当前任务
  4502. }
  4503. }
  4504. return 0;
  4505. }
  4506. void CUpgradeTaskFSM::s3_on_entry()
  4507. {
  4508. //查询新任务:先预查询任务,传送hash,接着查询任务
  4509. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("entery S3");
  4510. m_queryNewTaskCount = 0;
  4511. m_strPreTaskId = "";
  4512. m_bNeedHash=0;
  4513. m_fileSM3List="";
  4514. m_fileSM3ListHash="";
  4515. isSendHash=false;
  4516. //预查询任务
  4517. Task::QueryNewPreTask* qTask = new Task::QueryNewPreTask(this);
  4518. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
  4519. if(rc!=Error_Succeed){
  4520. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewPreTask fail,wait 4 min retry ,err=%d",(int)rc);
  4521. ScheduleTimer(1, 4*60*1000);//等待4分钟后再次查询是否有新任务
  4522. }
  4523. }
  4524. void CUpgradeTaskFSM::s3_on_exit()
  4525. {
  4526. CancelTimer(1);//预查询任务计时器
  4527. CancelTimer(2);//上传hash计时器
  4528. CancelTimer(3);//继续任务计时器
  4529. m_queryNewTaskCount =0;
  4530. m_strPreTaskId = "";
  4531. m_bNeedHash=0;
  4532. m_fileSM3List="";
  4533. m_fileSM3ListHash="";
  4534. isSendHash=false;
  4535. }
  4536. unsigned int CUpgradeTaskFSM::s3_on_event(FSMEvent* event)
  4537. {
  4538. if(event->iEvt == EVT_TIMER){
  4539. if(event->param1 == 1){
  4540. //发起预查询任务
  4541. Task::QueryNewPreTask* nTask = new Task::QueryNewPreTask(this);
  4542. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  4543. if(rc!=Error_Succeed){
  4544. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewPreTask fail,wait 4 min retry ,err=%d",(int)rc);
  4545. ScheduleTimer(1, 4*60*1000);//等待4分钟后再次查询是否有新任务
  4546. }
  4547. }else if(event->param1 == 2){
  4548. //上传hash
  4549. Task::SendSM3Task* SM3Task = new Task::SendSM3Task(this);
  4550. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(SM3Task);
  4551. if(rc!=Error_Succeed){
  4552. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create SendSM3Task fail,err=%d",(int)rc);
  4553. ScheduleTimer(2, 60*1000);//等待1分钟过后再次发送
  4554. }
  4555. }else if(event->param1 == 3){
  4556. //继续任务
  4557. Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
  4558. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  4559. if(rc!=Error_Succeed){
  4560. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
  4561. ScheduleTimer(3, 4*60*1000);//等待4分钟过后再次发送
  4562. }
  4563. }
  4564. }
  4565. else if(event->iEvt == Event_EndPrePoll){
  4566. QueryNewPreTaskEvent* pEvent = (QueryNewPreTaskEvent*)event;
  4567. if(pEvent->isSucc){
  4568. if(m_strPreTaskId.IsNullOrEmpty()){
  4569. m_queryNewTaskCount++;
  4570. if(m_queryNewTaskCount>=QUERY_NO_TASK_WARN_LIMIT){
  4571. LogWarn(Severity_Low, Error_Exception, ERR_TASK_QUERY_NO_TASK,"QueryNewPreTask 15 times succ,no new task");
  4572. m_queryNewTaskCount=0;
  4573. }
  4574. if (isAuthSucc()) {
  4575. ScheduleTimer(1, 4 * 60 * 1000);//等待4分钟后再次查询是否有新任务
  4576. }
  4577. else {
  4578. ScheduleTimer(1, 30 * 1000);//等待30s后再次查询是否有新任务
  4579. }
  4580. }else{
  4581. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewPreTask succ, task_id=%s",m_strPreTaskId.GetData());
  4582. if(m_bNeedHash){
  4583. //预查询成功
  4584. if(isSendHash){
  4585. //之前发送hash成功,直接开始继续任务查询线程
  4586. Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
  4587. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  4588. if(rc!=Error_Succeed){
  4589. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
  4590. ScheduleTimer(3, 60*1000);//再次查询是否有新任务
  4591. }
  4592. }else{
  4593. //之前未发送hash成功,开始计算hash线程
  4594. Task::SendSM3Task* SM3Task = new Task::SendSM3Task(this);
  4595. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(SM3Task);
  4596. if(rc!=Error_Succeed){
  4597. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create SendSM3Task fail,err=%d",(int)rc);
  4598. ScheduleTimer(2, 60*1000);//等待一分钟过后再次发送
  4599. }
  4600. }
  4601. }else{
  4602. //不需要hash,直接继续查询新任务
  4603. Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
  4604. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  4605. if(rc!=Error_Succeed){
  4606. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
  4607. ScheduleTimer(3, 60*1000);//等待4分钟后再次查询是否有新任务
  4608. }
  4609. }
  4610. }
  4611. }else{
  4612. //预查询失败
  4613. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewPreTask fail,wait 4 min retry");
  4614. if (isAuthSucc()) {
  4615. ScheduleTimer(1, 4 * 60 * 1000);//等待4分钟后再次预查询是否有新任务
  4616. }
  4617. else {
  4618. ScheduleTimer(1, 30 * 1000);//等待30s后再次查询是否有新任务
  4619. }
  4620. }
  4621. }
  4622. else if(event->iEvt == Event_EndSendSM3Task){
  4623. Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
  4624. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  4625. if(rc!=Error_Succeed){
  4626. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
  4627. ScheduleTimer(3, 60*1000);//等待4分钟后再次查询是否有新任务
  4628. }
  4629. }
  4630. else if(event->iEvt == Event_EndContinuePoll){
  4631. QueryNewContinueTaskEvent* pEvent = (QueryNewContinueTaskEvent*)event;
  4632. if(pEvent->retParam == 0){
  4633. //查询失败,继续查询
  4634. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask fail,wait 4 min retry");
  4635. if (isAuthSucc()) {
  4636. ScheduleTimer(3, 4 * 60 * 1000);//等待4分钟后再次查询继续新任务
  4637. }
  4638. else {
  4639. ScheduleTimer(3, 30 * 1000);//等待30s后再次查询继续新任务
  4640. }
  4641. }else if(pEvent->retParam == 1){
  4642. //查询成功,跳到下一个状态,写入运行时文件
  4643. bool isWriteOk=false;
  4644. while(true){
  4645. if(SetRunConfigStrValue("upgradeTask","NewVersion","")!=Error_Succeed){
  4646. break;
  4647. }
  4648. if(SetRunConfigStrValue("upgradeTask","PendingState","U")!=Error_Succeed){
  4649. break;
  4650. }
  4651. if(SetRunConfigStrValue("upgradeTask","CreateTaskVersion",m_currentTask.createTaskVersion.GetData())!=Error_Succeed){
  4652. break;
  4653. }
  4654. if(SetRunConfigStrValue("upgradeTask","PackName",m_currentTask.pack_name.GetData())!=Error_Succeed){
  4655. break;
  4656. }
  4657. if(SetRunConfigStrValue("upgradeTask","UpgradeTaskId",m_currentTask.upgradeTaskId.GetData())!=Error_Succeed){
  4658. break;
  4659. }
  4660. isWriteOk=true;
  4661. break;
  4662. }
  4663. if(isWriteOk){
  4664. //告警下载
  4665. struct CTaskProcess up;
  4666. up.strPackName = m_currentTask.pack_name;//安装包名
  4667. up.installVersion = m_currentTask.pack_version;//安装的版本
  4668. up.CurrentVersion = m_currentVersion;//当前的版本
  4669. up.cInstallState = "D";
  4670. up.strInstallComment = "正在下载";
  4671. SendUpgradeTaskProgress(up);
  4672. m_currentTask.cPendingState = "U";//改变内存变量为U
  4673. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDownload));//进入S4
  4674. }else{
  4675. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndPoll write runinfo is fail,retry int 5's");
  4676. Sleep(5 * 1000);//等待五秒,继续创建
  4677. PostEventFIFO(new QueryNewContinueTaskEvent(1));//继续创建任务
  4678. }
  4679. }else{
  4680. //跳出,重新预检查任务
  4681. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask fail,jump to PreTask");
  4682. if (isAuthSucc()) {
  4683. ScheduleTimer(1, 4 * 60 * 1000);//等待4分钟后再次预查询是否有新任务
  4684. }
  4685. else {
  4686. ScheduleTimer(1, 30 * 1000);//等待30s后再次预查询是否有新任务
  4687. }
  4688. }
  4689. }
  4690. return 0;
  4691. }
  4692. void CUpgradeTaskFSM::s4_on_entry()
  4693. {
  4694. //下载升级包
  4695. m_bTaskCancel = false;//默认任务非取消
  4696. if(m_bDownloadIdle){
  4697. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//进入不可下载状态
  4698. }else{
  4699. Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
  4700. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  4701. if(rc!=Error_Succeed){
  4702. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
  4703. ScheduleTimer(1, 15*1000);//等待15秒再试
  4704. }
  4705. }
  4706. ScheduleTimer(2, 30*1000);//启动查询任务是否有效
  4707. }
  4708. void CUpgradeTaskFSM::s4_on_exit()
  4709. {
  4710. CancelTimer(1);//正常下载计时器
  4711. CancelTimer(2);//查询任务是否取消计时器
  4712. CancelTimer(3);//外部状态中止下载计时器
  4713. }
  4714. unsigned int CUpgradeTaskFSM::s4_on_event(FSMEvent* event)
  4715. {
  4716. if (event->iEvt == EVT_TIMER)
  4717. {
  4718. if(event->param1 == 1){
  4719. Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
  4720. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  4721. if(rc!=Error_Succeed){
  4722. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
  4723. ScheduleTimer(1, 15*1000);//再次下载升级包
  4724. }
  4725. }else if(event->param1 == 2){
  4726. Task::QueryTaskStatus* dTask = new Task::QueryTaskStatus(this);
  4727. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  4728. if(rc!=Error_Succeed){
  4729. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create QueryTaskStatus fail,err=%d",(int)rc);
  4730. ScheduleTimer(2, 30*1000);//再次查询任务是否有效
  4731. }
  4732. }else if(event->param1 == 3){
  4733. //无效状态
  4734. if(m_bDownloadIdle){
  4735. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask download entry idle 10s");
  4736. ScheduleTimer(3,10*1000);//等待下次是否空闲
  4737. }else{
  4738. Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
  4739. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  4740. if(rc!=Error_Succeed){
  4741. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
  4742. ScheduleTimer(3, 10*1000);//等待下次是否空闲
  4743. }
  4744. }
  4745. }
  4746. }else if (event->iEvt == Event_EndQueryTaskStatus){
  4747. QueryTaskStatusEvent* pEvent = (QueryTaskStatusEvent*)event;
  4748. if(pEvent->isSucc){
  4749. if(pEvent->isTask_valid){
  4750. ScheduleTimer(2, 30*1000);//有效,再次查询任务是否有效
  4751. m_bTaskCancel = false;
  4752. }else{
  4753. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("query upgradeTask is cancel,set m_bTaskCancel=true");
  4754. m_bTaskCancel = true;//取消下载,结束查询任务是否有效计时器
  4755. }
  4756. }else{
  4757. ScheduleTimer(2, 30*1000);//通讯失败,再次查询任务是否有效
  4758. }
  4759. }else if (event->iEvt == Event_EndDownload){
  4760. DownloadPackTaskEvent* pEvent = (DownloadPackTaskEvent*)event;
  4761. if(pEvent->isSucc){
  4762. if(SetRunConfigStrValue("upgradeTask","PendingState","I")==Error_Succeed){
  4763. //下载成功
  4764. m_currentTask.cPendingState = "I";//改变内存变量为I
  4765. if(m_currentTask.pack_version.IsNullOrEmpty()){
  4766. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID)("体系外下载成功");
  4767. }else{
  4768. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID)("终端版本下载成功");
  4769. }
  4770. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartInstall));//进入S5
  4771. }else{
  4772. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndDownload write runinfo is fail,retry in 5's");
  4773. Sleep(5 * 1000);//等待五秒
  4774. PostEventFIFO(new DownloadPackTaskEvent(true));//继续写运行时文件
  4775. }
  4776. }else{
  4777. if (m_currentTask.pack_version.IsNullOrEmpty()) {
  4778. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID).setResultCode("RTA5634")("体系外下载失败,通讯报错");
  4779. }
  4780. else {
  4781. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID).setResultCode("RTA5633")("终端版本下载失败,通讯报错");
  4782. }
  4783. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("download pack is fail , wait for 2 min retry download");
  4784. ScheduleTimer(1, 120*1000);//下载失败,等2分钟,再次下载任务
  4785. }
  4786. }else if (event->iEvt == Event_Download_Fail){
  4787. DownloadPackTaskFailEvent* pEvent = (DownloadPackTaskFailEvent*)event;
  4788. //写入运行时文件,状态为C
  4789. if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
  4790. //告警下载失败
  4791. struct CTaskProcess up;
  4792. up.strPackName = m_currentTask.pack_name;//安装包名
  4793. up.installVersion = m_currentTask.pack_version;//安装的版本
  4794. up.CurrentVersion = m_currentVersion;//当前的版本
  4795. up.cInstallState = "C";
  4796. up.strInstallComment = pEvent->errMsg.c_str();
  4797. SendUpgradeTaskProgress(up);
  4798. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask download is fail ,prepare to s2");
  4799. m_currentTask.cPendingState = "C";//改变内存变量C
  4800. if (m_currentTask.pack_version.IsNullOrEmpty()) {
  4801. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID).setResultCode("RTA5636")("体系外下载失败:%s", pEvent->errMsg.c_str());
  4802. }
  4803. else {
  4804. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID).setResultCode("RTA5635")("终端版本下载失败:%s", pEvent->errMsg.c_str());
  4805. }
  4806. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  4807. }else{
  4808. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_Download_Fail write runinfo is fail,retry in 5's");
  4809. Sleep(5 * 1000);//等待五秒
  4810. PostEventFIFO(new DownloadPackTaskFailEvent(pEvent->errMsg));//继续写运行时文件
  4811. }
  4812. }else if (event->iEvt == Event_Download_Idle){
  4813. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask download entry idle 10s");
  4814. ScheduleTimer(3,10*1000);//等待下次是否空闲
  4815. }else if (event->iEvt == Event_CancelTask){
  4816. //取消任务,清理任务
  4817. if(ClearCurrTaskInfo()){
  4818. //告警下载取消
  4819. struct CTaskProcess up;
  4820. up.strPackName = m_currentTask.pack_name;//安装包名
  4821. up.installVersion = m_currentTask.pack_version;//安装的版本
  4822. up.CurrentVersion = m_currentVersion;//当前的版本
  4823. up.cInstallState = "C";
  4824. up.strInstallComment = "升级任务策略已取消";
  4825. SendUpgradeTaskProgress(up);
  4826. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask is cancel,prepare to s3");
  4827. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  4828. }else{
  4829. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry in 5's");
  4830. Sleep(5 * 1000);//等待五秒,继续清理
  4831. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//继续取消任务
  4832. }
  4833. }
  4834. return 0;
  4835. }
  4836. void CUpgradeTaskFSM::s5_on_entry()
  4837. {
  4838. //停止播放广告和音频
  4839. Task::StopMediaPlayTask* nTask = new Task::StopMediaPlayTask(this);
  4840. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  4841. if(rc!=Error_Succeed){
  4842. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create StopMediaPlayTask fail,err=%d",(int)rc);
  4843. ScheduleTimer(1, 30*1000);//等待30秒再试
  4844. }
  4845. }
  4846. void CUpgradeTaskFSM::s5_on_exit()
  4847. {
  4848. CancelTimer(1);//停止广播和声音计时器
  4849. CancelTimer(2);//解压计时器
  4850. CancelTimer(3);//安装计时器
  4851. CancelTimer(4);//等待跳转切换计时器
  4852. }
  4853. unsigned int CUpgradeTaskFSM::s5_on_event(FSMEvent* event)
  4854. {
  4855. if(event->iEvt == EVT_TIMER){
  4856. if(event->param1 == 1){
  4857. //再次发起任务查询
  4858. Task::StopMediaPlayTask* nTask = new Task::StopMediaPlayTask(this);
  4859. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  4860. if(rc!=Error_Succeed){
  4861. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create StopMediaPlayTask fail,err=%d",(int)rc);
  4862. ScheduleTimer(1, 30*1000);//等待30秒再停止播放广告和音频
  4863. }
  4864. }else if(event->param1 == 2){
  4865. Task::UnzipPackTask* iTask = new Task::UnzipPackTask(this);
  4866. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  4867. if(rc!=Error_Succeed){
  4868. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create UnzipPackTask fail,err=%d",(int)rc);
  4869. ScheduleTimer(2, 30*1000);//等待30秒再解压包
  4870. }
  4871. }else if(event->param1 == 3){
  4872. BOOL doInstall = true;
  4873. if(!m_startFlag) //非强制安装
  4874. {
  4875. if (m_currentTask.pack_version.GetLength() == 0) //体系外升级
  4876. {
  4877. CSimpleStringA strState;
  4878. ErrorCodeEnum err = m_pEntity->GetFunction()->GetSysVar("UIState", strState);
  4879. if (/*TRUE ||*/ err == Error_Succeed && strState != CSimpleStringA("M")) //非主界面不安装
  4880. {
  4881. doInstall = false;
  4882. }
  4883. }
  4884. }
  4885. //对于终端初始化安装时,直接通过。
  4886. if (isTerminalInstall()) {
  4887. doInstall = true;
  4888. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask terminal new install");
  4889. }
  4890. if (doInstall)
  4891. {
  4892. Task::InstallPackTask* iTask = new Task::InstallPackTask(this);
  4893. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  4894. if (rc != Error_Succeed) {
  4895. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask fail,err=%d", (int)rc);
  4896. ScheduleTimer(3, 30 * 1000);//等待30秒再安装
  4897. }
  4898. }
  4899. else {
  4900. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 UIState is not M , create InstallPackTask wait for the next time");
  4901. ScheduleTimer(3, 30 * 1000);//等待30秒再安装
  4902. }
  4903. }
  4904. else if (event->param1 == 4) {
  4905. //已安装成功,直接进入切换状态
  4906. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask succ, enter into S6");
  4907. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
  4908. }
  4909. }else if(event->iEvt == Event_EndStopMediaPlayTask){
  4910. StopMediaPlayTaskEvent* pEvent = (StopMediaPlayTaskEvent*)event;
  4911. if(pEvent->isSucc){
  4912. //开始解压
  4913. Task::UnzipPackTask* iTask = new Task::UnzipPackTask(this);
  4914. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  4915. if(rc!=Error_Succeed){
  4916. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create UnzipPackTask fail,err=%d",(int)rc);
  4917. ScheduleTimer(2, 30*1000);//等待30秒再解压包
  4918. }
  4919. }else{
  4920. ScheduleTimer(1, 30*1000);//等待30秒再停止播放广告和音频
  4921. }
  4922. }else if (event->iEvt == Event_EndUnzipPackTask){
  4923. UnzipPackTaskEvent* pEvent = (UnzipPackTaskEvent*)event;
  4924. if(pEvent->isSucc){
  4925. //开始安装
  4926. BOOL doInstall = true;
  4927. if (!m_startFlag) //非强制安装
  4928. {
  4929. if (m_currentTask.pack_version.GetLength() == 0) //体系外升级
  4930. {
  4931. CSimpleStringA strState;
  4932. ErrorCodeEnum err = m_pEntity->GetFunction()->GetSysVar("UIState", strState);
  4933. if (/*TRUE ||*/ err == Error_Succeed && strState != CSimpleStringA("M")) //非主界面不安装
  4934. {
  4935. doInstall = false;
  4936. }
  4937. }
  4938. }
  4939. //对于终端初始化安装时,直接通过。
  4940. if (isTerminalInstall()) {
  4941. doInstall = true;
  4942. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask terminal new install");
  4943. }
  4944. if (doInstall)
  4945. {
  4946. Task::InstallPackTask* iTask = new Task::InstallPackTask(this);
  4947. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  4948. if (rc != Error_Succeed) {
  4949. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask fail,err=%d", (int)rc);
  4950. ScheduleTimer(3, 30 * 1000);//等待30秒再安装
  4951. }
  4952. }
  4953. else{
  4954. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 UIState is not M , create InstallPackTask wait for the next time");
  4955. ScheduleTimer(3, 30 * 1000);//等待30秒再安装
  4956. }
  4957. }else{
  4958. if(m_currentTask.stop_media_play){
  4959. //恢复广告和音频播放
  4960. ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
  4961. if(Error_Succeed != rc){
  4962. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("unzip fail set UpdateState to 0 fail, err=%d",(int)rc);
  4963. }
  4964. }
  4965. //解压失败,写入运行时文件,状态为C
  4966. if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
  4967. //告警下载取消
  4968. struct CTaskProcess up;
  4969. up.strPackName = m_currentTask.pack_name;//安装包名
  4970. up.installVersion = m_currentTask.pack_version;//安装的版本
  4971. up.CurrentVersion = m_currentVersion;//当前的版本
  4972. up.cInstallState = "C";
  4973. up.strInstallComment = "解压失败";
  4974. SendUpgradeTaskProgress(up);
  4975. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("unzip pack is fail ,prepare to s2");
  4976. m_currentTask.cPendingState = "C";//改变内存变量C
  4977. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  4978. }else{
  4979. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndUnzipPackTask write runinfo is fail,retry int 5's");
  4980. Sleep(5 * 1000);//等待五秒
  4981. PostEventFIFO(new UnzipPackTaskEvent(false));//继续写运行时文件
  4982. }
  4983. }
  4984. }else if (event->iEvt == Event_EndInstallPackTask){
  4985. if(m_currentTask.stop_media_play){
  4986. //恢复广告和音频播放
  4987. ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
  4988. if(Error_Succeed != rc){
  4989. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("EndInstallPackTask set UpdateState to 0 fail, err=%d",(int)rc);
  4990. }
  4991. }
  4992. InstallPackTaskEvent* pEvent = (InstallPackTaskEvent*)event;
  4993. if(pEvent->isSucc){
  4994. //安装成功进入切换,设置状态为S和新版本号
  4995. //写入运行时文件
  4996. bool isWriteOk=false;
  4997. while(true){
  4998. if(SetRunConfigStrValue("upgradeTask","NewVersion",m_currentTask.NewVersion.GetData())!=Error_Succeed){
  4999. break;
  5000. }
  5001. if(SetRunConfigStrValue("upgradeTask","PendingState","S")!=Error_Succeed){
  5002. break;
  5003. }
  5004. isWriteOk=true;
  5005. break;
  5006. }
  5007. if(isWriteOk){
  5008. //告警安装
  5009. struct CTaskProcess up;
  5010. up.strPackName = m_currentTask.pack_name;//安装包名
  5011. if(m_currentTask.NewVersion.IsNullOrEmpty()){
  5012. up.installVersion = m_currentVersion.ToString();//当前版本号
  5013. }else{
  5014. up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
  5015. }
  5016. up.CurrentVersion = m_currentVersion;//当前的版本
  5017. up.cInstallState = "W";
  5018. up.strInstallComment = "安装成功";
  5019. SendUpgradeTaskProgress(up);
  5020. m_currentTask.cPendingState = "S";//改变内存变量S
  5021. if(m_currentTask.pack_version.IsNullOrEmpty()){
  5022. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_INSTALL_ID)("体系外安装成功");
  5023. }else{
  5024. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_INSTALL_ID)("终端版本安装成功");
  5025. }
  5026. //modify by lwt 修改为非兜底升级时等待一段时间再进入切换状态。
  5027. if (m_startFlag) {
  5028. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
  5029. }
  5030. else {
  5031. ScheduleTimer(4, 20 * 1000);//等待20秒再进入切换状态
  5032. }
  5033. }else{
  5034. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
  5035. Sleep(5 * 1000);//等待五秒
  5036. PostEventFIFO(new InstallPackTaskEvent(true,"",0));//继续写运行时文件
  5037. }
  5038. }else{
  5039. if(pEvent->failStatus==0){
  5040. //安装失败,设置状态为C
  5041. if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
  5042. //告警下载取消
  5043. struct CTaskProcess up;
  5044. up.strPackName = m_currentTask.pack_name;//安装包名
  5045. up.installVersion = m_currentTask.pack_version;//安装的版本
  5046. up.CurrentVersion = m_currentVersion;//当前的版本
  5047. up.cInstallState = "C";
  5048. up.strInstallComment = pEvent->errMsg;//错误信息
  5049. SendUpgradeTaskProgress(up);
  5050. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("install pack is fail ,prepare to s2");
  5051. m_currentTask.cPendingState = "C";//改变内存变量C
  5052. if (m_currentTask.pack_version.IsNullOrEmpty()) {
  5053. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_INSTALL_ID).setResultCode("RTA5638")("体系外安装失败");
  5054. }else{
  5055. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_INSTALL_ID).setResultCode("RTA5637")("终端版本安装失败");
  5056. }
  5057. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  5058. }else{
  5059. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
  5060. Sleep(5 * 1000);//等待五秒
  5061. PostEventFIFO(new InstallPackTaskEvent(false,pEvent->errMsg,0));//继续写运行时文件
  5062. }
  5063. }else if(pEvent->failStatus==-1){
  5064. //安装失败,设置状态为X 未知
  5065. if(SetRunConfigStrValue("upgradeTask","PendingState","X")==Error_Succeed){
  5066. //告警下载取消
  5067. struct CTaskProcess up;
  5068. up.strPackName = m_currentTask.pack_name;//安装包名
  5069. up.installVersion = m_currentTask.pack_version;//安装的版本
  5070. up.CurrentVersion = m_currentVersion;//当前的版本
  5071. up.cInstallState = "X";
  5072. up.strInstallComment = pEvent->errMsg;//错误信息
  5073. SendUpgradeTaskProgress(up);
  5074. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("install pack is fail ,prepare to s2");
  5075. m_currentTask.cPendingState = "X";//改变内存变量X
  5076. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  5077. }else{
  5078. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
  5079. Sleep(5 * 1000);//等待五秒
  5080. PostEventFIFO(new InstallPackTaskEvent(false,pEvent->errMsg,-1));//继续写运行时文件
  5081. }
  5082. }
  5083. }
  5084. }
  5085. return 0;
  5086. }
  5087. void CUpgradeTaskFSM::s6_on_entry()
  5088. {
  5089. //进入切换处理流程:不同类型包判断不同
  5090. //时间长,需要判断后台是否取消任务
  5091. if (CheckIfCanSwitchNow())
  5092. {
  5093. ScheduleTimer(2,1000);//进行版本切换操作
  5094. }else{
  5095. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("not applicable time to switch, retry in 20's");
  5096. ScheduleTimer(1, 20*1000);//继续等待
  5097. }
  5098. ScheduleTimer(3, 30*1000);//启动查询任务是否有效
  5099. }
  5100. void CUpgradeTaskFSM::s6_on_exit()
  5101. {
  5102. CancelTimer(1);//判断是否切换时间计时器
  5103. CancelTimer(2);//切换运行时文件写入计时器
  5104. CancelTimer(3);//任务取消计时器
  5105. CancelTimer(4);//切换重启写入active文件计时器
  5106. CancelTimer(5);//active文件写入失败写运行时计时器
  5107. m_bSwitchFlag = false;//切换标志重置。
  5108. }
  5109. unsigned int CUpgradeTaskFSM::s6_on_event(FSMEvent* event)
  5110. {
  5111. if (event->iEvt == EVT_TIMER)
  5112. {
  5113. if(event->param1==1)
  5114. {
  5115. //进入切换处理流程:不同类型包判断不同
  5116. if (CheckIfCanSwitchNow())
  5117. {
  5118. ScheduleTimer(2,1000);//进行版本切换操作
  5119. }else{
  5120. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("not applicable time to switch, retry in 20's");
  5121. ScheduleTimer(1, 20*1000);//继续等待切换时机
  5122. }
  5123. }else if(event->param1==2){
  5124. //修改运行时文件状态T
  5125. if(SetRunConfigStrValue("upgradeTask","PendingState","T")==Error_Succeed){
  5126. //告警切换
  5127. struct CTaskProcess up;
  5128. up.strPackName = m_currentTask.pack_name;//安装包名
  5129. if(m_currentTask.NewVersion.IsNullOrEmpty()){
  5130. up.installVersion = m_currentVersion.ToString();//当前版本号
  5131. }else{
  5132. up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
  5133. }
  5134. up.CurrentVersion = m_currentVersion;//当前的版本
  5135. up.cInstallState = "S";
  5136. up.strInstallComment = "已设为启动版本";
  5137. SendUpgradeTaskProgress(up);
  5138. m_currentTask.cPendingState = "T";//改变内存变量
  5139. if(m_currentTask.pack_version.IsNullOrEmpty()){
  5140. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_SWTICH_ID)("体系外切换成功");
  5141. }else{
  5142. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_SWTICH_ID)("终端版本切换成功");
  5143. }
  5144. ScheduleTimer(4,5*1000);//等待告警上报,准备修改active文件,进行切换
  5145. }else{
  5146. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("switch write runinfo is fail,retry in 10's");
  5147. ScheduleTimer(1, 10*1000);//继续等待下次切换机会再重试
  5148. }
  5149. }else if(event->param1==3){
  5150. Task::QueryTaskStatus* dTask = new Task::QueryTaskStatus(this);
  5151. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  5152. if(rc!=Error_Succeed){
  5153. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s6 create QueryTaskStatus fail,err=%d",(int)rc);
  5154. ScheduleTimer(3, 30*1000);//再次查询任务是否有效
  5155. }
  5156. }else if(event->param1==4){
  5157. //修改active文件
  5158. if(UpgradeToNewVersion()==Error_Succeed){
  5159. SwitchUpgradeNow();//切换版本
  5160. }else{
  5161. ScheduleTimer(5,3*1000);//UpgradeToNewVersion执行失败后写运行时计时器
  5162. }
  5163. }else if(event->param1==5){
  5164. if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
  5165. //告警切换失败
  5166. struct CTaskProcess up;
  5167. up.strPackName = m_currentTask.pack_name;//安装包名
  5168. if(m_currentTask.NewVersion.IsNullOrEmpty()){
  5169. up.installVersion = m_currentVersion.ToString();//当前版本号
  5170. }else{
  5171. up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
  5172. }
  5173. up.CurrentVersion = m_currentVersion;//当前的版本
  5174. up.cInstallState = "C";
  5175. up.strInstallComment = "更新active文件失败";//错误信息
  5176. SendUpgradeTaskProgress(up);
  5177. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("UpgradeToNewVersion is fail ,prepare to s2");
  5178. m_currentTask.cPendingState = "C";//改变内存变量C
  5179. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  5180. }else{
  5181. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("UpgradeToNewVersion fail, write runinfo is fail,retry in 10's");
  5182. ScheduleTimer(5,10*1000);//继续重试写入运行时
  5183. }
  5184. }
  5185. }else if (event->iEvt == Event_EndQueryTaskStatus){
  5186. QueryTaskStatusEvent* pEvent = (QueryTaskStatusEvent*)event;
  5187. if(pEvent->isSucc){
  5188. if(pEvent->isTask_valid){
  5189. ScheduleTimer(3, 30*1000);//有效,再次查询任务是否有效
  5190. }else{
  5191. //无效,清理任务
  5192. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("query upgradeTask is cancel");
  5193. if(ClearCurrTaskInfo()){
  5194. //告警下载取消
  5195. struct CTaskProcess up;
  5196. up.strPackName = m_currentTask.pack_name;//安装包名
  5197. up.installVersion = m_currentTask.pack_version;//安装的版本
  5198. up.CurrentVersion = m_currentVersion;//当前的版本
  5199. up.cInstallState = "C";
  5200. up.strInstallComment = "升级任务策略已取消";
  5201. SendUpgradeTaskProgress(up);
  5202. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask is cancel,prepare to s3");
  5203. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  5204. }else{
  5205. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry in 5's");
  5206. Sleep(5 * 1000);//等待五秒,继续清理
  5207. PostEventFIFO(new QueryTaskStatusEvent(true,false));//继续取消任务
  5208. }
  5209. }
  5210. }else{
  5211. ScheduleTimer(3, 30*1000);//通讯失败,再次查询任务是否有效
  5212. }
  5213. }
  5214. return 0;
  5215. }
  5216. void CUpgradeTaskFSM::s7_on_entry()
  5217. {
  5218. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("enter disable state , wait framework restart or OS restart");
  5219. }
  5220. void CUpgradeTaskFSM::s7_on_exit()
  5221. {
  5222. }
  5223. unsigned int CUpgradeTaskFSM::s7_on_event(FSMEvent* event)
  5224. {
  5225. return 0;
  5226. }