UpgradeTaskFSM.cpp 291 KB

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