UpgradeTaskFSM.cpp 243 KB

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