123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350 |
- #include "UpgradeTaskFSM.h"
- #include "fileutil.h"
- #include "iniutil.h"
- #include "memutil.h"
- #include "osutil.h"
- #include "RVCComm.h"
- #include <regex>
- #include "mod_UpgradeMgr.h"
- #include "UpgradeManager_msg_g.h"
- #include "CommEntityUtil.hpp"
- #ifdef RVC_OS_WIN
- #include <WinBase.h>
- #include <io.h>
- #include "XUnzip.h"
- #include <ShellAPI.h>
- #else
- #include <sys/utsname.h>
- #include "XUnZipZilb.h"
- #endif
- #include "EventCode.h"
- #include "json/json.h"
- #include "RVCEventCode.h"
- #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/
- #define QUERY_CONTINUE_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/continue-task"
- #define QUERY_CURR_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/current/task"
- #define QUERY_NEW_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/new/task"
- #define QUERY_PRE_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/pre-task"
- #define SEND_SM3_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/upload/hash"
- #define UPDATE_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/update/upgrade/status"
- #define QUERY_TASK_STATUS_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/task/status"
- #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
- #define QUERY_CONTINUE_TASK_URL "https://upgrade.paasuat.cmbchina.cn/api/continueTask"
- #define QUERY_CURR_TASK_URL "https://upgrade.paasuat.cmbchina.cn/api/current/task"
- #define QUERY_NEW_TASK_URL "https://upgrade.paasuat.cmbchina.cn/api/new/task"
- #define QUERY_PRE_TASK_URL "https://upgrade.paasuat.cmbchina.cn/api/preTask"
- #define SEND_SM3_TASK_URL "https://upgrade.paasuat.cmbchina.cn/api/upload/hash"
- #define UPDATE_TASK_URL "https://upgrade.paasuat.cmbchina.cn/api/update/upgrade/status"
- #define QUERY_TASK_STATUS_URL "https://upgrade.paasuat.cmbchina.cn/api/task/status"
- #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
- #define QUERY_CONTINUE_TASK_URL "https://upgrade.paas.cmbchina.cn/api/continueTask"
- #define QUERY_CURR_TASK_URL "https://upgrade.paas.cmbchina.cn/api/current/task"
- #define QUERY_NEW_TASK_URL "https://upgrade.paas.cmbchina.cn/api/new/task"
- #define QUERY_PRE_TASK_URL "https://upgrade.paas.cmbchina.cn/api/preTask"
- #define SEND_SM3_TASK_URL "https://upgrade.paas.cmbchina.cn/api/upload/hash"
- #define UPDATE_TASK_URL "https://upgrade.paas.cmbchina.cn/api/update/upgrade/status"
- #define QUERY_TASK_STATUS_URL "https://upgrade.paas.cmbchina.cn/api/task/status"
- #else/*DevOps流水线编译,Dev环境&本地编译等非DevOps环境*/
- #define QUERY_CONTINUE_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/continue-task"
- #define QUERY_CURR_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/current/task"
- #define QUERY_NEW_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/new/task"
- #define QUERY_PRE_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/pre-task"
- #define SEND_SM3_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/upload/hash"
- #define UPDATE_TASK_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/update/upgrade/status"
- #define QUERY_TASK_STATUS_URL "https://accessproxy-service.paasst.cmbchina.cn/upgrade/api/task/status"
- #endif
- namespace Task
- {
- //计算和发送文件hash
- struct SendSM3Task : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit SendSM3Task(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- int tryCount=3;//总共3次机会
- bool SendHashOK= false;
- while(tryCount>0){
- //计算hash
- if(m_fsm->m_fileSM3ListHash.IsNullOrEmpty()){
- if(getSM3Hash()){
- 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());
- }else{
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_GET_SM3_HASH_FAIL, "get SM3 list fail");
- tryCount--;
- Sleep(60*1000);//等待60s再计算
- continue;
- }
- }
- //发送hash
- if(sendSM3Hash()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("send SM3 list succ");
- m_fsm->isSendHash=true;
- SendHashOK = true;
- break;
- }else{
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_SEND_SM3_HASH_FAIL, "send SM3 list fail");
- m_fsm->isSendHash=false;
- Sleep(60*1000);//等待60s再上传
- tryCount--;
- continue;
- }
- }
-
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::SendSM3TaskEvent(SendHashOK));//返回处理结果
- }
- bool getSM3Hash(){
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin get SM3 list");
- CSmallDateTime beginT = CSmallDateTime::GetNow();
- CSimpleStringA tempSM3ListStr = "";
- ErrorCodeEnum rc = m_fsm->GetSM3List(tempSM3ListStr);
- CSmallDateTime endT = CSmallDateTime::GetNow();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get SM3 list 耗时%d秒",(DWORD)(endT-beginT));
- if (rc != Error_Succeed)
- {
- LogWarn(Severity_Low, rc, ERR_TASK_GET_SM3_HASH_FAIL, "get SM3 list fail");
- return false;
- }
- else
- {
- //tempSM3ListStr 这个值有可能因为配置的文件夹下面没有文件,故为空
- if(tempSM3ListStr.IsNullOrEmpty()){
- m_fsm->m_fileSM3ListHash = "TerminalTempHash";
- return true;
- }else{
- CSimpleStringA tempSM3HashStr = "";
- if(Error_Succeed==m_fsm->SM3DataToStr(tempSM3ListStr,tempSM3HashStr,false)){
- m_fsm->m_fileSM3ListHash = tempSM3HashStr;
- return true;
- }else{
- LogWarn(Severity_Low, rc, ERR_TASK_GET_SM3_HASH_FAIL, "get SM3 list hash fail");
- return false;
- }
- }
- }
- }
- bool sendSM3Hash(){
- //LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- //发送hash
- bool bRet = SendSM3TaskImpl(client);
- client->Destory();
- return bRet;
- }
- bool SendSM3TaskImpl(IHttpFunc* client){
- HttpStruct::SendSM3TaskReq qTempReq;
- HttpStruct::SendSM3TaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SendSM3Task get CSystemStaticInfo fail");
- return false;
- }
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["software_version"] = m_fsm->m_currentVersion.ToString().GetData();
- rootReq["file_hash_list"] = m_fsm->m_fileSM3List.GetData();//hash集合
- rootReq["list_hash"] = m_fsm->m_fileSM3ListHash.GetData();//64位
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.sendSM3TaskUrl;//访问地址
- qTempReq.m_timeOut = 60;//设置传送超时时间为60s
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- PROCESS_LINK_CONTEXT("LR0402506SendSM3")
- if(!client->Post(qTempReq, qTempRet, &nextLink)){
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- if(rootRet["data"].asBool()){
- return true;//写入成功
- }else{
- return false;//写入失败
- }
- }else{
- return false;//写入失败
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SendSM3Task [success] is false");
- return false;//写入失败
- }
- }
- };
- //更新任务状态
- struct UpdateTaskStatus : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit UpdateTaskStatus(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- bool isSendSucc=false;//更新是否成功标志
- if(UpdateTaskStatusImpl(client)){
- isSendSucc = true;
- }else{
- isSendSucc = false;
- }
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::UpdateTaskStatusEvent(isSendSucc));//返回处理结果
- }
- bool UpdateTaskStatusImpl(IHttpFunc* client){
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus get CSystemStaticInfo fail,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- return false;
- }
- HttpStruct::UpdateTaskStatusReq qTempReq;
- HttpStruct::UpdateTaskStatusRet qTempRet;
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
- //状态为C时,为X时,或者T,版本不一致,则是回退,否则是成功
- //返回任务结果给服务器
- if(m_fsm->m_currentTask.cPendingState=="C"){
- rootReq["upgrade_status"] = "F";//失败
- }else if(m_fsm->m_currentTask.cPendingState=="X"){
- rootReq["upgrade_status"] = "X";//未知状态
- }else if(m_fsm->m_currentTask.cPendingState=="T"){
- if (m_fsm->m_currentTask.task_type.Compare("U") == 0) {
- if (m_fsm->isTerminalInstall()) {
- //安装状态时,达到终态就算成功
- rootReq["upgrade_status"] = "S";//成功
- }
- else {
- if (m_fsm->m_currentTask.NewVersion == m_fsm->m_currentVersion.ToString() ||
- m_fsm->m_currentTask.depNewVersion == m_fsm->m_currentDepVersion ||
- (m_fsm->m_currentTask.NewVersion == "" && m_fsm->m_currentTask.depNewVersion == "")) {
- //升级成功
- rootReq["upgrade_status"] = "S";//成功
- }
- else {
- //升级失败,回滚版本导致
- rootReq["upgrade_status"] = "F";//失败
- }
- }
- }
- else if (m_fsm->m_currentTask.task_type.Compare("R") == 0) {
- if (m_fsm->m_currentTask.NewVersion == m_fsm->m_currentVersion.ToString()||
- m_fsm->m_currentTask.depNewVersion == m_fsm->m_currentDepVersion) {
- //升级成功
- rootReq["upgrade_status"] = "S";//成功
- }
- else {
- //升级失败,回滚版本导致
- rootReq["upgrade_status"] = "F";//失败
- }
- }
- else {
- //不支持此类型,任务执行失败
- rootReq["upgrade_status"] = "X";//失败
- }
- }
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
-
- qTempReq.m_url=m_fsm->m_centerUrl.updateTaskUrl;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus req=%s",qTempReq.m_reqStr.c_str());
- PROCESS_LINK_CONTEXT("LR0402506UpdateTaskStatus")
- if(!client->Post(qTempReq, qTempRet, &nextLink)){
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- int isUpdate =rootRet["data"].asInt();
- //0:更新失败 1:更新成功 2:任务不属于此终端等异常情况,默认成功
- if(isUpdate==0){
- DbgWithLink(LOG_LEVEL_WARN,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setResultCode("RTA5673")("UpdateTaskStatus update fail: upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- return false;//更新失败
- }else if(isUpdate==1){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus update succ: req=%s",m_fsm->m_currentTask.upgradeTaskId.GetData(), jsonReq.c_str());
- return true;//更新成功
- }else if(isUpdate==2){
- 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());
- return true;//任务异常,更新成功
- }else{
- 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);
- return false;//更新失败
- }
- }else{
- 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());
- return false;//更新失败
- }
- }else{
- 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());
- return false;//更新失败
- }
- }
- };
- //查询当前任务
- struct QueryCurrTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit QueryCurrTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //根据任务ID查询任务当前的策略。
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- bool isSendSucc=false;//查询是否成功标志
- bool isTask_valid=false;//任务是否有效
- if(QueryCurrTaskImpl(client,isTask_valid)){
- isSendSucc = true;
- }else{
- isSendSucc = false;
- }
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryCurrTaskEvent(isSendSucc,isTask_valid));//返回处理结果
- }
- bool QueryCurrTaskImpl(IHttpFunc* client,bool &isValid){
- HttpStruct::QueryCurrTaskReq qTempReq;
- HttpStruct::QueryCurrTaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewTask get CSystemStaticInfo fail");
- return false;
- }
- //机器版本
- CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
- //框架版本
- CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
- //适配器版本
- CSimpleStringA strDepVersion = m_fsm->m_currentDepVersion;
- // OS版本
- #ifdef RVC_OS_WIN
- OSVERSIONINFO osvi;
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osvi);
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d",osvi.dwMajorVersion,osvi.dwMinorVersion,osvi.dwBuildNumber);
- #else
- DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
- struct utsname kernel_info;
- int ret = uname(&kernel_info);
- if (ret == 0) {
- int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
- }
- else {
- Dbg("get linux kernel version fail: %s", strerror(errno));
- }
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
- #endif
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
- rootReq["machine_type"] = info.strMachineType.GetData();
- rootReq["software_version"] = strInstallVersion.GetData();
- rootReq["os_version"] = strOSVersion.GetData();
- rootReq["machine_version"] = strMachineVersion.GetData();
- rootReq["dep_version"] = strDepVersion.GetData();//适配器版本
-
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.queryCurrTaskUrl;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- PROCESS_LINK_CONTEXT("LR0402506QueryCurrTask")
- if(!client->Post(qTempReq, qTempRet, &nextLink)){
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- if(rootRet["data"]["task_status"].asBool()){
- isValid = true;//任务有效
- if (rootRet["data"].isMember("task_type")) {
- m_fsm->m_currentTask.task_type = rootRet["data"]["task_type"].asString().c_str();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask query task_type=%s", m_fsm->m_currentTask.task_type.GetData());
- }
- else {
- m_fsm->m_currentTask.task_type = "U";//兼容旧服务端程序,无字段值时默认是升级模式
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask query task_type is not exist , use default value task_type = U");
- }
- if (m_fsm->m_currentTask.task_type.Compare("U") == 0) {
- //升级任务
- if (!ParamCheck(rootRet)) {
- 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());
- return false;//查询失败 升级任务参数效验失败,无法进行升级
- }
- else {
- CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
- if (m_fsm->m_currentTask.pack_name != packNameStr) {
- //异常情况
- CSimpleStringA errmsg = CSimpleStringA::Format("runinfo packName[%s] is not equal server packName[%s]", m_fsm->m_currentTask.pack_name.GetData(), packNameStr.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_PACKNAME_NOT_EQUAL, errmsg.GetData());
- }
- m_fsm->m_currentTask.pack_name = packNameStr;//用最新的包名进行后面的安装和下载
- m_fsm->m_currentTask.file_path = rootRet["data"]["file_path"].asString().c_str();
- m_fsm->m_currentTask.download_url = rootRet["data"]["download_url"].asString().c_str();
- m_fsm->m_currentTask.pack_hash = rootRet["data"]["pack_hash"].asString().c_str();
- m_fsm->m_currentTask.pack_length = (long)rootRet["data"]["pack_length"].asInt();
- m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
- m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
- m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
- //解析step json
- if (!ParseInstallStep(rootRet)) {
- m_fsm->ClearInstallStep();
- 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());
- return false;//解析安装步骤失败
- }
- 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());
- return true;//查询成功
- }
- }
- else if (m_fsm->m_currentTask.task_type.Compare("R") == 0) {
- //回退任务
- if (!rollbackParamCheck(rootRet)) {
- 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());
- return false;//查询失败 回退任务参数效验失败,无法进行回退
- }
- else {
- m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
- m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
- m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("current task id =%s", m_fsm->m_currentTask.upgradeTaskId.GetData());
- return true;//查询成功
- }
- }
- else {
- 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());
- return false;//查询失败
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask query task is invalid, taskid=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- isValid = false;//任务无效
- return true;//查询成功
- }
- }else{
- 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());
- return false;//查询失败
- }
- }else{
- 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());
- return false;//查询失败
- }
- }
- bool ParamCheck(Json::Value rootRet){
- CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_name] is %s",packNameStr.GetData());
- if(packNameStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_name] is null");
- return false;
- }
- CSimpleStringA filePathStr = rootRet["data"]["file_path"].asString().c_str();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [file_path] is %s",filePathStr.GetData());
- if(filePathStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [file_path] is null");
- return false;
- }
- CSimpleStringA downloadUrlStr = rootRet["data"]["download_url"].asString().c_str();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [download_url] is %s",downloadUrlStr.GetData());
- if(downloadUrlStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [download_url] is null");
- return false;
- }
- CSimpleStringA packHashStr = rootRet["data"]["pack_hash"].asString().c_str();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_hash] is %s",packHashStr.GetData());
- if(packHashStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_hash] is null");
- return false;
- }
- long packLengthLong = (long)rootRet["data"]["pack_length"].asInt();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_length] is %d",packLengthLong);
- int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [reboot_type] is %d",rebootTypeInt);
- if(rebootTypeInt!=1 && rebootTypeInt!=2 && rebootTypeInt!=0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [reboot_type] is invalid ,reboot_type=%d",rebootTypeInt);
- return false;
- }
- CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_version] is %s",packVersionStr.GetData());
- if(!packVersionStr.IsNullOrEmpty()){
- int rebootType = rootRet["data"]["reboot_type"].asInt();
- if(rebootType == 1 || rebootType == 2){
- return true;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_version] is not null ,[reboot_type] is not equal 1 or 2");
- return false;
- }
- }
- return true;
- }
- bool rollbackParamCheck(Json::Value rootRet) {
- int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
- if (rebootTypeInt != 1 && rebootTypeInt != 2) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [reboot_type] is invalid ,reboot_type=%d", rebootTypeInt);
- return false;
- }
- CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
- if (packVersionStr.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_version] is null");
- return false;
- }
- return true;
- }
- bool ParseInstallStep(Json::Value rootRet){
- //清理以前的遗留的安装步骤
- m_fsm->ClearInstallStep();
- string cmdstr = rootRet["data"]["cmd"].asString();
- if(cmdstr.empty()){
- return true;//为空则直接不解析
- }
- Json::Reader reader;
- Json::Value InstallRet;
- if (!reader.parse(cmdstr, InstallRet, false))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask parse cmd fail,cmdstr=%s",cmdstr.c_str()).GetData());
- return false;//解析失败
- }
- //install_step
- for(int i=0;i<InstallRet.size();i++){
- if(!InstallRet[i]["seq"].isInt()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][seq] is not int");
- return false;
- }
- int stepSeq = InstallRet[i]["seq"].asInt();
- if(!InstallRet[i]["cmdType"].isString()&&!InstallRet[i]["cmdType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][cmdType] is not string");
- return false;
- }
- CSimpleStringA cmdType = InstallRet[i]["cmdType"].asString().c_str();
- if(cmdType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][cmdType] is null");
- return false;
- }
- if(!InstallRet[i]["cmdFail"].isInt()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][cmdFail] is not int");
- return false;
- }
- int cmdFail = InstallRet[i]["cmdFail"].asInt();
- if(!InstallRet[i]["srcPathType"].isString()&&!InstallRet[i]["srcPathType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][srcPathType] is not string");
- return false;
- }
- CSimpleStringA srcPathType = InstallRet[i]["srcPathType"].asString().c_str();
- if(cmdType=="Copy"){
- //复制指令时,不为空
- if(srcPathType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][srcPathType] is null");
- return false;
- }
- }
- if(!InstallRet[i]["srcPath"].isString()&&!InstallRet[i]["srcPath"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][srcPath] is not string");
- return false;
- }
- CSimpleStringA srcPath = InstallRet[i]["srcPath"].asString().c_str();
- if(cmdType=="Copy"){
- //复制指令时,不为空
- if(srcPath.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][srcPath] is null");
- return false;
- }
- }
- if(!InstallRet[i]["dstPathType"].isString()&&!InstallRet[i]["dstPathType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][dstPathType] is not string");
- return false;
- }
- CSimpleStringA dstPathType = InstallRet[i]["dstPathType"].asString().c_str();
- if(cmdType=="Copy"||cmdType=="Delete"||cmdType=="Run"){
- if(dstPathType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][dstPathType] is null");
- return false;
- }
- }
- if(!InstallRet[i]["dstPath"].isString()&&!InstallRet[i]["dstPath"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][dstPath] is not string");
- return false;
- }
- CSimpleStringA dstPath = InstallRet[i]["dstPath"].asString().c_str();
- if(cmdType=="Delete"||cmdType=="Run"){
- if(dstPath.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][dstPath] is null");
- return false;
- }
- }
- CUpgradeTaskFSM::CInstallStep* iStep= new CUpgradeTaskFSM::CInstallStep();
- iStep->stepSeq = stepSeq;
- iStep->cmdType = cmdType;
- iStep->cmdFail = cmdFail;
- iStep->srcPathType = srcPathType;
- iStep->srcPath = srcPath;
- iStep->dstPathType =dstPathType;
- iStep->dstPath =dstPath;
- m_fsm->m_currentTask.install_step.push(iStep);//加入队尾
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d",InstallRet.size());
- return true;
- }
- };
- //预查询新任务
- struct QueryNewPreTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit QueryNewPreTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- //LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- //查询新任务
- bool isSendSucc=false;////查询是否成功标志
- if(QueryNewPreTaskImpl(client)){
- isSendSucc = true;
- }else{
- isSendSucc = false;
- }
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryNewPreTaskEvent(isSendSucc));//返回处理结果
- }
- bool QueryNewPreTaskImpl(IHttpFunc* client){
- HttpStruct::QueryNewTaskReq qTempReq;
- HttpStruct::QueryNewTaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewPreTask get CSystemStaticInfo fail");
- return false;
- }
- //机器版本
- CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
- //框架版本
- CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
- //适配器版本
- CSimpleStringA strDepVersion = m_fsm->m_currentDepVersion;
- // OS版本
- #ifdef RVC_OS_WIN
- OSVERSIONINFO osvi;
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osvi);
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber);
- #else
- DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
- struct utsname kernel_info;
- int ret = uname(&kernel_info);
- if (ret == 0) {
- int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
- }
- else {
- Dbg("get linux kernel version fail: %s", strerror(errno));
- }
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
- #endif
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["machine_type"] = info.strMachineType.GetData();
- rootReq["software_version"] = strInstallVersion.GetData();
- rootReq["os_version"] = strOSVersion.GetData();
- rootReq["machine_version"] = strMachineVersion.GetData();
- rootReq["dep_version"] = strDepVersion.GetData();//适配器版本
- //预查询判断加入查询何种任务。
- if (m_fsm->isTerminalInstall()) {
- rootReq["task_type"] = "I";//安装任务
- }
- else {
- rootReq["task_type"] = "U";//升级任务
- }
- #ifdef RVC_OS_WIN
- rootReq["system_type"] = "W";//表示是windows类型的机器
- #else
- rootReq["system_type"] = "L";//表示是uos类型的机器
- #endif
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.queryPreTaskUrl;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- PROCESS_LINK_CONTEXT("LR0402506QueryNewPreTask")
- if(!client->Post(qTempReq, qTempRet, &nextLink)){
- if (qTempRet.m_sysCode == 6) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5651")("终端查询任务域名解析失败");
- }else if(qTempRet.m_sysCode == 28){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5652")("终端查询任务连接总行服务超时");
- }else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5653")("终端查询任务失败:%s", qTempRet.m_errMsg.c_str());
- }
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false)){
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- //解析任务,可能不存在任务
- if(rootRet["data"]["task_id"].asString()!=""){
- m_fsm->m_strPreTaskId = rootRet["data"]["task_id"].asString().c_str();
- int need_hash = rootRet["data"]["need_hash"].asInt();
- if(need_hash==0){
- m_fsm->m_bNeedHash = false;
- }else{
- m_fsm->m_bNeedHash = true;
- }
- return true;//查询成功
- }else{
- //无任务
- m_fsm->m_strPreTaskId = "";
- m_fsm->m_bNeedHash =false;
- return true;//查询成功
- }
- }else{
- 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());
- return false;//查询失败
- }
- }else{
- 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());
- return false;//查询失败
- }
- }
- };
- //继续查询新任务
- struct QueryNewContinueTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit QueryNewContinueTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- //查询新任务
- int retParm=QueryNewContinueTaskImpl(client);
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryNewContinueTaskEvent(retParm));//返回处理结果
- }
- // 0:重试 1:成功 2:跳出
- int QueryNewContinueTaskImpl(IHttpFunc* client){
- HttpStruct::QueryNewTaskReq qTempReq;
- HttpStruct::QueryNewTaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask get CSystemStaticInfo fail");
- return 0;//查询失败,继续查询
- }
- //机器版本
- CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
- //框架版本
- CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
- //适配器版本
- CSimpleStringA strDepVersion = m_fsm->m_currentDepVersion;
-
- // OS版本
- #ifdef RVC_OS_WIN
- OSVERSIONINFO osvi;
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osvi);
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber);
- #else
- DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
- struct utsname kernel_info;
- int ret = uname(&kernel_info);
- if (ret == 0) {
- int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
- }
- else {
- Dbg("get linux kernel version fail: %s", strerror(errno));
- }
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
- #endif
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["task_id"] = m_fsm->m_strPreTaskId.GetData();
- rootReq["machine_type"] = info.strMachineType.GetData();
- rootReq["software_version"] = strInstallVersion.GetData();
- rootReq["os_version"] = strOSVersion.GetData();
- rootReq["machine_version"] = strMachineVersion.GetData();
- rootReq["dep_version"] = strDepVersion.GetData();//适配器版本
- #ifdef RVC_OS_WIN
- rootReq["system_type"] = "W";//表示是windows类型的机器
- #else
- rootReq["system_type"] = "L";//表示是uos类型的机器
- #endif
- if(m_fsm->m_bNeedHash&&m_fsm->isSendHash){
- //是否发送hash码并且发送成功了
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask with hash");
- rootReq["list_hash"] = m_fsm->m_fileSM3ListHash.GetData();
- }else{
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask with no hash");
- rootReq["list_hash"] = "";
- }
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.queryContinueTaskUrl;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- PROCESS_LINK_CONTEXT("LR0402506QueryNewContinueTask")
- if(!client->Post(qTempReq, qTempRet, &nextLink)){
- 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());
- return 0;//查询失败,继续查询
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return 0;//查询失败,继续查询
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- //解析任务,可能不存在任务,task_id为空,则表示无此任务。
- if(rootRet["data"]["task_id"].asString()!=""){
- //task_status 0-无效 1-有效 2-对比不通过 3-hash内容为空
- int task_status = rootRet["data"]["task_status"].asInt();
- if(task_status ==1){
- if (rootRet["data"].isMember("task_type")) {
- m_fsm->m_currentTask.task_type = rootRet["data"]["task_type"].asString().c_str();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask query task_type=%s", m_fsm->m_currentTask.task_type.GetData());
- }
- else {
- m_fsm->m_currentTask.task_type = "U";//兼容旧服务端程序,无字段值时默认是升级模式
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask query task_type is not exist , use default value task_type = U");
- }
- if (m_fsm->m_currentTask.task_type.Compare("U") == 0) {
- //pack_status 0-准备中 1-已就绪
- int status = rootRet["data"]["pack_status"].asInt();
- if (status == 1) {
- if (!ParamCheck(rootRet)) {
- 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());
- return 0;//查询失败 升级任务参数效验失败,告警码不同
- }
- else {
- m_fsm->m_currentTask.upgradeTaskId = rootRet["data"]["task_id"].asString().c_str();
- m_fsm->m_currentTask.pack_name = rootRet["data"]["pack_name"].asString().c_str();
- m_fsm->m_currentTask.file_path = rootRet["data"]["file_path"].asString().c_str();
- m_fsm->m_currentTask.download_url = rootRet["data"]["download_url"].asString().c_str();
- m_fsm->m_currentTask.pack_hash = rootRet["data"]["pack_hash"].asString().c_str();
- m_fsm->m_currentTask.pack_length = (long)rootRet["data"]["pack_length"].asInt();
- m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
- m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
- m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
- //解析step json
- if (!ParseInstallStep(rootRet)) {
- m_fsm->ClearInstallStep();
- 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());
- return 0;//查询失败 解析安装步骤失败,告警码不同
- }
- m_fsm->m_currentTask.createTaskVersion = m_fsm->m_currentVersion.ToString();//新策略,查询到包后,用当前版本值赋值
- 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());
- return 1;//查询成功
- }
- }
- else {
- //任务未准备好
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask query pack is not create ,please next query,status=%d", status);
- m_fsm->m_currentTask.upgradeTaskId = "";
- return 0;//查询成功,继续查询
- }
- }
- else if (m_fsm->m_currentTask.task_type.Compare("R") == 0) {
- //回退任务
- if (!rollbackParamCheck(rootRet)) {
- 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());
- return 0;//查询失败 升级任务参数效验失败,告警码不同
- }
- else {
- m_fsm->m_currentTask.upgradeTaskId = rootRet["data"]["task_id"].asString().c_str();
- m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
- m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
- m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
- m_fsm->m_currentTask.createTaskVersion = m_fsm->m_currentVersion.ToString();
- 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());
- return 1;//查询成功
- }
- }
- else {
- 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());
- return 0;//查询失败,taskType 不支持处理,告警码不同
- }
- }else{
- //任务状态无效,对比不通过,hash内容为空
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask query fail ,task_status=%d",task_status).GetData());
- return 2;//查询成功,但任务不再,跳出来
- }
- }else{
- //返回任务为空
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask return [task id] is null").GetData());
- return 2;//查询成功,但任务不再,跳出来
- }
- }else{
- 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());
- return 0;//查询失败,继续查询,告警码不同
- }
- }else{
- 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());
- return 0;//查询失败,继续查询
- }
- }
- bool ParamCheck(Json::Value rootRet){
- CSimpleStringA upgradeTaskIdStr = rootRet["data"]["task_id"].asString().c_str();
- if(upgradeTaskIdStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [task_id] is null");
- return false;
- }
- CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
- if(packNameStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [pack_name] is null");
- return false;
- }
- CSimpleStringA filePathStr = rootRet["data"]["file_path"].asString().c_str();
- if(filePathStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [file_path] is null");
- return false;
- }
- CSimpleStringA downloadUrlStr = rootRet["data"]["download_url"].asString().c_str();
- if(downloadUrlStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [download_url] is null");
- return false;
- }
- CSimpleStringA packHashStr = rootRet["data"]["pack_hash"].asString().c_str();
- if(packHashStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [pack_hash] is null");
- return false;
- }
- long packLengthStr = (long)rootRet["data"]["pack_length"].asInt();
-
- int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
- if(rebootTypeInt!=1 && rebootTypeInt!=2 && rebootTypeInt!=0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [reboot_type] is invalid ,reboot_type=%d",rebootTypeInt);
- return false;
- }
- //CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
- //if(!packVersionStr.IsNullOrEmpty()){
- // int rebootType = rootRet["data"]["reboot_type"].asInt();
- // if(rebootType == 1 || rebootType == 2){
- // return true;
- // }else{
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask paramCheck [pack_version] is not null ,[reboot_type] is not equal 1 or 2");
- // return false;
- // }
- //}
- return true;
- }
- bool rollbackParamCheck(Json::Value rootRet) {
- CSimpleStringA upgradeTaskIdStr = rootRet["data"]["task_id"].asString().c_str();
- if(upgradeTaskIdStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [task_id] is null");
- return false;
- }
- int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
- if(rebootTypeInt!=1 && rebootTypeInt!=2){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [reboot_type] is invalid ,reboot_type=%d",rebootTypeInt);
- return false;
- }
- CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
- if (packVersionStr.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [pack_version] is null");
- return false;
- }
- return true;
- }
- bool ParseInstallStep(Json::Value rootRet){
- //清理以前的遗留的安装步骤
- m_fsm->ClearInstallStep();
- string cmdstr = rootRet["data"]["cmd"].asString();
- if(cmdstr.empty()){
- return true;//为空则直接不解析
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cmdstr =%s",cmdstr.c_str());
- Json::Reader reader;
- Json::Value InstallRet;
- if (!reader.parse(cmdstr, InstallRet, false))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask parse cmd fail,cmdstr=%s",cmdstr.c_str()).GetData());
- return false;//解析失败
- }
- for(int i=0;i<InstallRet.size();i++){
- if(!InstallRet[i]["seq"].isInt()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][seq] is not int");
- return false;
- }
- int stepSeq = InstallRet[i]["seq"].asInt();
-
- if(!InstallRet[i]["cmdType"].isString()&&!InstallRet[i]["cmdType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][cmdType] is not string");
- return false;
- }
- CSimpleStringA cmdType = InstallRet[i]["cmdType"].asString().c_str();
- if(cmdType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][cmdType] is null");
- return false;
- }
-
- if(!InstallRet[i]["cmdFail"].isInt()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][cmdFail] is not int");
- return false;
- }
- int cmdFail = InstallRet[i]["cmdFail"].asInt();
-
- if(!InstallRet[i]["srcPathType"].isString()&&!InstallRet[i]["srcPathType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][srcPathType] is not string");
- return false;
- }
- CSimpleStringA srcPathType = InstallRet[i]["srcPathType"].asString().c_str();
- if(cmdType=="Copy"){
- //复制指令时,不为空
- if(srcPathType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][srcPathType] is null");
- return false;
- }
- }
-
- if(!InstallRet[i]["srcPath"].isString()&&!InstallRet[i]["srcPath"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][srcPath] is not string");
- return false;
- }
- CSimpleStringA srcPath = InstallRet[i]["srcPath"].asString().c_str();
- if(cmdType=="Copy"){
- //复制指令时,不为空
- if(srcPath.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][srcPath] is null");
- return false;
- }
- }
-
- if(!InstallRet[i]["dstPathType"].isString()&&!InstallRet[i]["dstPathType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][dstPathType] is not string");
- return false;
- }
- CSimpleStringA dstPathType = InstallRet[i]["dstPathType"].asString().c_str();
- if(cmdType=="Copy"||cmdType=="Delete"||cmdType=="Run"){
- if(dstPathType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][dstPathType] is null");
- return false;
- }
- }
-
- if(!InstallRet[i]["dstPath"].isString()&&!InstallRet[i]["dstPath"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][dstPath] is not string");
- return false;
- }
- CSimpleStringA dstPath = InstallRet[i]["dstPath"].asString().c_str();
- if(cmdType=="Delete"||cmdType=="Run"){
- if(dstPath.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][dstPath] is null");
- return false;
- }
- }
-
- CUpgradeTaskFSM::CInstallStep* iStep= new CUpgradeTaskFSM::CInstallStep();
- iStep->stepSeq = stepSeq;
- iStep->cmdType = cmdType;
- iStep->cmdFail = cmdFail;
- iStep->srcPathType = srcPathType;
- iStep->srcPath = srcPath;
- iStep->dstPathType =dstPathType;
- iStep->dstPath =dstPath;
- m_fsm->m_currentTask.install_step.push(iStep);//加入队尾
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d",InstallRet.size());
- return true;
- }
- };
- //查询任务状态
- struct QueryTaskStatus : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit QueryTaskStatus(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- //LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- //查询新任务
- bool isSendSucc=false;////查询是否成功标志
- bool isValid=false;//任务是否有效
- if(QueryTaskStatusImpl(client,isValid)){
- isSendSucc = true;
- }else{
- isSendSucc = false;
- }
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryTaskStatusEvent(isSendSucc,isValid));//返回处理结果
- }
- bool QueryTaskStatusImpl(IHttpFunc* client,bool &isValid){
- HttpStruct::QueryCurrTaskReq qTempReq;
- HttpStruct::QueryCurrTaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryTaskStatus get CSystemStaticInfo fail");
- return false;
- }
-
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.queryTaskStatus;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- PROCESS_LINK_CONTEXT("LR0402506QueryTaskStatus")
- if(!client->Post(qTempReq, qTempRet, &nextLink)){
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- isValid =rootRet["data"].asBool();
- return true;//查询成功
- }else{
- return false;//查询失败
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryTaskStatus [success] is false");
- return false;//查询失败
- }
- }
- };
- //下载升级包
- struct DownloadPackTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit DownloadPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //下载升级包
- if(m_fsm->m_currentTask.pack_name.IsNullOrEmpty()||m_fsm->m_currentTask.pack_hash.IsNullOrEmpty()){
- string errMsg = CSimpleStringA::Format("DownloadPackTask fail,pack_name or pack_hash is null,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData()).GetData();
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.c_str());
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskFailEvent(errMsg));//下载失败,返回结果,这种情况下无法继续下载
- return;
- }
- CSimpleStringA dPackName = m_fsm->m_currentTask.pack_name;
- CSimpleStringA dPakchash = m_fsm->m_currentTask.pack_hash;
- long lpacklen = m_fsm->m_currentTask.pack_length;
-
- //判断是否已经下载完成
- CSimpleStringA strPath;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetPath("Downloads", strPath);
- if(Error_Succeed != rc){
- 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());
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(false));//返回失败结果
- return;
- }
- CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strPath.GetData(), dPackName.GetData());
- if(m_fsm->IsPackDownloaded(strZipFile.GetData(),dPakchash.GetData(),lpacklen)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("download pack [%s] sm3[%s] is exist ,do not download.", strZipFile.GetData(),dPakchash.GetData());
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(true));//下载完成,返回成功结果
- return;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("download pack [%s] sm3[%s] is not exist ,prepare download.", strZipFile.GetData(),dPakchash.GetData());
- }
- //提前判断是否任务取消
- if(m_fsm->m_bTaskCancel){
- m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//取消下载任务,返回结果
- return;
- }
- if(m_fsm->m_bDownloadIdle){
- m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//下载中断,返回结果
- return;
- }
- //接着下载未完成的升级包
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- bool isDownloadSucc=false;//是否下载成功
- CSimpleStringA errMsg ;//下载失败错误信息
- int ret = DownloadPack(client,strZipFile.GetData(),dPakchash,errMsg);
- if(ret==0){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(false));//返回通讯失败结果
- }else if(ret ==1){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(true));//返回成功结果
- }else if(ret ==2){
- m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//下载中断,返回结果
- }else if(ret ==3){
- m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//取消下载任务,返回结果
- }else if(ret ==4){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskFailEvent(errMsg.GetData()));//下载失败,任务中止
- }
- client->Destory();
- }
- //返回值 0:下载通讯失败 1:下载成功 2:下载中断 3:任务取消 4:下载失败
- int DownloadPack(IHttpFunc* client,const char* dPackPath,const char* dPackHash,CSimpleStringA &errMsg){
- bool isDownloadSucc = false;
- CSimpleStringA dPackPathTemp = CSimpleStringA::Format("%s%s",dPackPath,".tmp");//默认临时文件是.tmp后缀
- long dPackTempLen = 0;
- if(ExistsFileA(dPackPathTemp)){
- if(!m_fsm->GetFileLength(dPackPathTemp.GetData(),dPackTempLen)){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("%s get download temp pack fileLen is fail", dPackPathTemp.GetData()).GetData());
- errMsg = "get download temp pack fileLen is fail";
- return 4;//下载失败,计算临时文件长度失败
- }
- }
- byte* content = new byte[m_fsm->m_newEachDownloadLen];
- memset(content, 0, m_fsm->m_newEachDownloadLen);
- bool isContinue = true;
- while(isContinue){
- if(m_fsm->m_bTaskCancel){
- //任务取消
- delete[] content;
- return 3;
- }
- if(m_fsm->m_bDownloadIdle){
- //状态中断
- delete[] content;
- return 2;
- }
- HttpStruct::DownloadPackTaskRet resp;
- resp.bfinish= false;//默认是未下载完
- resp.sm3 = "";//默认是空串
- if(DownloadPackTaskImpl(client,dPackTempLen,content,resp)){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("download succ, %d , begin write %d",(int)resp.bfinish,dPackTempLen);
- //成功通讯
- if(!m_fsm->DownloadFileWrite(content,resp.content_length,dPackPathTemp)){
- 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());
- errMsg = "DownloadFileWrite write temp file fail";
- delete[] content;
- return 4;//下载失败,写文件失败
- }else{
- m_fsm->DownloadProgress(dPackTempLen+resp.content_length,resp.origin_file_length);//广播下载进度
- }
- if(resp.bfinish){
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("最后一次下载");
- //最后一次
- CSimpleStringA strMD5Val;
- ErrorCodeEnum rc = m_fsm->SM3FileToStr(dPackPathTemp, strMD5Val,false);
- if (Error_Succeed != rc)
- {
- 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());
- errMsg = "get download temp pack sm3 fail";
- delete[] content;
- return 4;//下载失败,算hash失败
- }
- //TODO: CrossPlaform 不区分大小写比较文件hash /** 为什么有平台差异?? [Gifur@2025821]*/
- #ifdef RVC_OS_WIN
- if(stricmp(strMD5Val.GetData(),resp.sm3.c_str())==0){
- #else
- if(strcmp(strMD5Val.GetData(),resp.sm3.c_str())==0){
- #endif
- //移动文件到正式目录
- if(ExistsFileA(dPackPath)){
- if(remove(dPackPath)==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete download old pack succ ", dPackPath);
- if(rename(dPackPathTemp.GetData(),dPackPath)!=0){
- errMsg = CSimpleStringA::Format("exist old file,remove temp file fail, error=%d", (int)GetLastError()).GetData();
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
- delete[] content;
- return 4;//下载失败,移动文件失败
- }else{
- delete[] content;
- return 1;//成功返回
- }
- }else{
- errMsg = CSimpleStringA::Format("delete download old pack fail ,error:%d", (int)GetLastError()).GetData();
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
- delete[] content;
- return 4;//下载失败,删除旧文件失败
- }
- }else{
- if(rename(dPackPathTemp.GetData(),dPackPath)!=0){
- errMsg = CSimpleStringA::Format("not exist old file,remove temp file fail, error=%d", (int)GetLastError()).GetData();
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
- delete[] content;
- return 4;//移动文件失败
- }else{
- delete[] content;
- return 1;//成功返回
- }
- }
- }else{
- errMsg = CSimpleStringA::Format("download file sm3 is not equal,local file [%s],resp [%s]",strMD5Val.GetData(),resp.sm3.c_str()).GetData();
- 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());
- //删除临时文件,重新下载
- if(remove(dPackPathTemp.GetData())==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete download temp pack succ ,%s", dPackPathTemp.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete download temp pack fail ,%s error:%d", dPackPathTemp.GetData(), GetLastError());
- }
- delete[] content;
- return 4;//下载失败,hash不对
- }
- }else{
- if(resp.content_length==0){
- errMsg = "DownloadFile server content_length = 0 ,bfinish = false ,DownloadFile server return param fail";
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"DownloadFile server content_length = 0 ,bfinish = false ,DownloadFile server return param fail");
- delete[] content;
- return 4;//传回零字节,但是又未结束,下载失败,等待一段时间下载
- }
- //继续下一次续传
- dPackTempLen =dPackTempLen+resp.content_length;
- memset(content, 0, m_fsm->m_newEachDownloadLen);
- isContinue = true;
- }
- }else{
- delete[] content;
- return 0;//下载通讯失败,等待一段时间下载
- }
- }
- }
- bool DownloadPackTaskImpl(IHttpFunc* client,long downloaded_len,byte* respContent,HttpStruct::DownloadPackTaskRet &resp){
- //注意传入参数和传出参数进行转码
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadPackTask get CSystemStaticInfo fail");
- return false;//失败
- }
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["pack_name"] = m_fsm->m_currentTask.pack_name.GetData();
- rootReq["downloaded_length"] = downloaded_len;
- rootReq["limit_length"] = m_fsm->m_newEachDownloadLen;
- rootReq["file_path"] = m_fsm->m_currentTask.file_path.GetData();
- string jsonReq = writer.write(rootReq);
- CSimpleStringA downloadUrl = m_fsm->m_currentTask.download_url;
- #if defined(RVC_OS_WIN) /** TODO 跟文涛确认UOS下是否需要调用 [Gifur@2025725]*/
- //转码
- SP::Module::Util::ConvertGBK2Utf8(jsonReq);
- #endif //RVC_OS_WIN
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("jsonStr is %s",jsonReq.c_str());
- }
- long httpCode =0;
- unordered_map<string, string> responseHeaders;
- int time_out = DOWNLOAD_TIMEOUT;
- fileContentArray content;
- content.copyPtr = respContent;
- content.maxLen = m_fsm->m_newEachDownloadLen;
- int retlen = 0;
- content.curLen = &retlen;
- PROCESS_LINK_CONTEXT("LR0402506DownloadFile")
- if(!client->DownloadFileBlock(downloadUrl.GetData(),jsonReq.c_str(), content,httpCode,responseHeaders,time_out, &nextLink)){
- if (retlen > m_fsm->m_newEachDownloadLen) {
- CSimpleStringA errMsg = CSimpleStringA::Format("retlen is over limit_length ,retlen= %d", retlen).GetData();
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL, CSimpleStringA::Format("DownloadPackTask http req fail, %s, url=%s", errMsg.GetData(), downloadUrl.GetData()).GetData());
- }
- else {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL, CSimpleStringA::Format("DownloadPackTask http req fail,url=%s", downloadUrl.GetData()).GetData());
- }
- return false;//失败
- }
- //判断httpCode
- if(httpCode!=200){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("DownloadPackTask http req fail, url=%s, retHttpCode=%d",downloadUrl.GetData(),httpCode).GetData());
- return false;//失败
- }
- //解析head值
- unordered_map<string, string>::const_iterator iter = responseHeaders.find("Result");
- if(iter==responseHeaders.end()){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"resp head result is null");
- return false;//无params 失败
- }else{
- string respStr = iter->second;
- #if defined(RVC_OS_WIN)
- //转码:
- SP::Module::Util::ConvertUtf82GBK(respStr);
- #endif //RVC_OS_WIN
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet Result=%s",respStr.c_str());
- }
- //解析json值
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(respStr, rootRet, false))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"DownloadPackTask head params parse resp is fail");
- return false;//解析失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- resp.content_length = (long)rootRet["content_length"].asInt();
- resp.origin_file_length = (long)rootRet["origin_file_length"].asInt();
- resp.bfinish = rootRet["finish"].asBool();//是否传送完毕
- resp.sm3 = rootRet["sm3"].asString();//包hash码
- int retlen = *(content.curLen);
- if (resp.content_length != retlen) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadPackTask download len not equal, retlen = %d,content_length=%d", retlen, resp.content_length);
- }
- return true;//查询成功
- }else{
- CSimpleStringA msg = rootRet["message"].asString().c_str();
- if(msg.IsNullOrEmpty()){
- msg = "";
- }
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("DownloadPackTask [success] is false, err=%s",msg.GetData()).GetData());
- return false;//查询失败
- }
- }
- }
- };
- //停止播放广告和提示音
- struct StopMediaPlayTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit StopMediaPlayTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //判断是否需要停止广播和提示音
- if(!m_fsm->m_currentTask.stop_media_play){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(true));//返回处理结果
- }
- else if(m_fsm->isTerminalInstall()){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(true));//返回处理结果
- }
- else {
- //停止广告、提示音播放
- // 终端置为升级状态。1:升级状态,0:非升级状态。处于升级状态时调用播放接口不生效
- //ErrorCodeEnum rc = ((CUpgradeMgrEntity*)m_fsm->GetEntityBase())->NewStopMediaPlay();
- //if(rc==Error_Succeed){
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("StopMediaPlayTask stop media play succ");
- //}else{
- // DbgWithLink(LOG_LEVEL_WARN,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setResultCode("RTA5674")("StopMediaPlayTask stop media play fail");
- // //m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(false));//返回处理结果
- //}
- // 终端置为升级状态。1:升级状态,0:非升级状态。处于升级状态时调用播放接口不生效
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->SetSysVar("UpdateState", "1", false);
- if(rc==Error_Succeed){
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("StopMediaPlayTask set UpdateState to 1 succ");
- }else{
- DbgWithLink(LOG_LEVEL_WARN,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__).setResultCode("RTA5674")("StopMediaPlayTask set UpdateState fail");
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(false));//返回处理结果
- return;
- }
- //停止广告、提示音播放
- rc = ((CUpgradeMgrEntity*)m_fsm->GetEntityBase())->NewStopMediaPlay();
- if (rc == Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("StopMediaPlayTask stop media play succ");
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("StopMediaPlayTask stop media play fail");
- //m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(false));//返回处理结果
- }
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(true));//返回处理结果
- }
- }
- };
- //解压安装包
- struct UnzipPackTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit UnzipPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //解压安装包
- bool isUnzipSucc;//是否解压成功
- if(m_fsm->UnzipPack(m_fsm->m_currentTask.pack_name.GetData())==Error_Succeed){
- isUnzipSucc = true;
- }else{
- isUnzipSucc = false;
- }
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::UnzipPackTaskEvent(isUnzipSucc));//返回处理结果
- }
- };
- //升级包安装
- struct InstallPackTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit InstallPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //升级包安装
- bool isInstallSucc=false;//是否安装成功
- int failStatus=0;//安装失败状态:0:失败,1:成功,-1:未知
- string packName = m_fsm->m_currentTask.pack_name.GetData();
- CSimpleStringA errMsg ="";
- if (!m_fsm->m_TempDepUpgradeFlag) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("======begin ExecInstall======");
- failStatus = m_fsm->ExecInstall(errMsg);
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("======begin dep ExecInstall======");
- failStatus = m_fsm->ExecDepInstall(errMsg);
- }
- if(failStatus == 1){
- //安装成功,执行防火墙设置
- if (!m_fsm->m_stopSetFirewall) {
- m_fsm->SetNewVersionPathToFirewall();
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("======end ExecInstall:succ======");
- isInstallSucc =true;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("======end ExecInstall:fail======");
- isInstallSucc =false;
- }
- //清理临时解压包
- if(Error_Succeed==m_fsm->DeleteUnzipDir()){
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DeleteUnzipDir succ");
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DeleteUnzipDir fail");
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("安装完成:failStatus=%d",failStatus);
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::InstallPackTaskEvent(isInstallSucc,errMsg,failStatus));//返回处理结果
- }
- };
- //回退版本检查
- struct RollBackCheckTask : public ITaskSp {
- CUpgradeTaskFSM* m_fsm;
- explicit RollBackCheckTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process() {
- LOG_FUNCTION();
- //回退版本检查
- string failReason = "";
- CSimpleStringA strErrMsg = "";
- //判定是适配器or应用回退
- CSimpleStringA verDirName = m_fsm->m_currentTask.pack_version.GetData();
- if(m_fsm->judgeRollbackTaskClass(verDirName,failReason,strErrMsg)==Error_Succeed)
- {
- if (!m_fsm->m_TempDepUpgradeFlag) {
- //升级回退
- if (m_fsm->RollBackVersionCheck(failReason, strErrMsg) == Error_Succeed) {
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(true, "", ""));
- }
- else {
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(false, strErrMsg, failReason));
- }
- }
- else {
- //适配器回退
- if (m_fsm->RollBackDepVersionCheck(failReason, strErrMsg) == Error_Succeed) {
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(true, "", ""));
- }
- else {
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(false, strErrMsg, failReason));
- }
- }
- }else{
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(false, strErrMsg, failReason));
- }
- }
- };
- }
- //完成
- // 创建新版本目录,拷贝当前版本bin、cfg、dep、mod、imdep、res
- ErrorCodeEnum CUpgradeTaskFSM::CreateNewVersion(CVersion NewSoftwareVersion,CSimpleStringA &strErrInfo)
- {
- // 创建安装包日志文件
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version fail , get RootVer path is fail");
- strErrInfo = CSimpleStringA::Format("Create new version fail , get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strCurVerPath;
- rc = m_pEntity->GetFunction()->GetPath("Base",strCurVerPath);//获取当前version路径
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version fail , get Base path is fail");
- strErrInfo = CSimpleStringA::Format("Create new version fail , get Base path is fail");
- return Error_Bug;
- }
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), NewSoftwareVersion.ToString().GetData());
- //auto &v = cfg->install_ini->install_version;//获取当前版本
- //CVersion v;//获取当前版本
- CVersion curVersion(m_currentVersion.GetMajor(), m_currentVersion.GetMinor(), m_currentVersion.GetRevision(), m_currentVersion.GetBuild());
- if (curVersion == NewSoftwareVersion)
- {
- 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());
- strErrInfo = CSimpleStringA::Format("new ver [%s] equals current ver [%s]", NewSoftwareVersion.ToString().GetData(), curVersion.ToString().GetData());
- return Error_Bug;
- }
- if (ExistsDirA(strNewVerPath.GetData()))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new version dir [%s] already exist, delete it", strNewVerPath.GetData());
- if(!RemoveDirRecursiveA(strNewVerPath.GetData())){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version fail, delete already exist new version is fail:%d", GetLastError());
- strErrInfo = CSimpleStringA::Format("Create new version fail, delete already exist new version is fail:%d", (int)GetLastError());
- return Error_Bug;
- }
- }
- if (!CreateDirA(strNewVerPath.GetData(), TRUE))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version dir fail: %d", GetLastError());
- strErrInfo = CSimpleStringA::Format("create new version dir fail: %d", (int)GetLastError());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create new version dir succ, dir = %s",strNewVerPath.GetData());
- //增加错误信息字段,回传给上层应用
- CSimpleStringA strErrMsg ="";
- CSimpleStringA strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "bin", strCurVerPath.GetData());
- CSimpleStringA strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "bin", strNewVerPath.GetData());
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy bin dir fail");
- strErrInfo = CSimpleStringA::Format("copy bin dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy bin dir succ");
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "cfg", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "cfg", strNewVerPath.GetData());
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy cfg dir fail");
- strErrInfo = CSimpleStringA::Format("copy cfg dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy cfg dir succ");
- //strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strCurVerPath.GetData());
- //strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strNewVerPath.GetData());
- //if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- //{
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
- // strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
- // return Error_Unexpect;
- //}
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "mod", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "mod", strNewVerPath.GetData());
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy mod dir fail");
- strErrInfo = CSimpleStringA::Format("copy mod dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy mod dir succ");
-
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strNewVerPath.GetData());
- // 检测dep目录是否存在
- if (ExistsDirA(strSource))
- {
- if (!RecursiveCopyDir(strSource, strDest, strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
- strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("dep dir is not exist,ignore copy");
- }
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "res", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "res", strNewVerPath.GetData());
- // 检测res目录是否存在
- if (ExistsDirA(strSource))
- {
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy res dir fail");
- strErrInfo = CSimpleStringA::Format("copy res dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy res dir succ");
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("res dir is not exist,ignore copy");
- }
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "imdep", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "imdep", strNewVerPath.GetData());
- // 检测imdep目录是否存在
- if (ExistsDirA(strSource))
- {
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy imdep dir fail");
- strErrInfo = CSimpleStringA::Format("copy imdep dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy imdep dir succ");
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("imdep dir is not exist,ignore copy");
- }
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::ClearUpgradeFailVersion(CVersion NewSoftwareVersion)
- {
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion fail , get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), NewSoftwareVersion.ToString().GetData());
- if (ExistsDirA(strNewVerPath.GetData()))
- {
- if(!RemoveDirRecursiveA(strNewVerPath.GetData())){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), (int)GetLastError());
- return Error_Bug;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion succ, delete temp Version [%s] ", strNewVerPath.GetData());
- return Error_Succeed;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion succ, delete temp Version [%s] is not exsit ", strNewVerPath.GetData());
- return Error_Succeed;
- }
- }
- // result.log 文件内容: result=0&msg=install ok
- bool CUpgradeTaskFSM::GetSysUpgradeResult(const char *pszResultLog, CSimpleStringA &eErrorCode, CSimpleStringA &strErrMsg)
- {
- // 设置初始值
- //eErrorCode = Error_Succeed;
- strErrMsg = "";
- if (!ExistsFileA(pszResultLog))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult result log [%s] not exist", pszResultLog);
- strErrMsg = "result.log not exist";
- eErrorCode = "0";
- return true;//???有些外部程序不一定会产生日志文件,故默认不产生文件,认为是成功
- }
- FILE *pResultLog = fopen(pszResultLog, "r");
- if (pResultLog == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult open result log [%s] fail", pszResultLog);
- strErrMsg = "open result.log fail";
- return false;
- }
- char szTmp[4096] = {};
- int nRead = fread_s(szTmp, sizeof(szTmp), 1, sizeof(szTmp), pResultLog);
- CSimpleStringA strResult = szTmp;
- fclose(pResultLog);
- pResultLog = NULL;
- auto arr = strResult.Split('&');
- if(arr.GetCount()!=2){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult read result log format fail,[%s]", strResult.GetData());
- strErrMsg = "read result.log format fail,eg result=0&msg=install ok";
- return false;
- }
- for (int i = 0; i < arr.GetCount(); i++)
- {
- auto arr2 = arr[i].Split('=');
- if (arr2.GetCount() == 2)
- {
- if (stricmp(arr2[0], "result") == 0)
- eErrorCode = arr2[1];
- else if (stricmp(arr2[0], "msg") == 0)
- strErrMsg = arr2[1];
- }
- }
- return true;
- }
- int CUpgradeTaskFSM::ExecInstall(CSimpleStringA &strErrMsg)
- {
- //判断是否需要生成新版本
- if(!m_currentTask.pack_version.IsNullOrEmpty()){
- CSimpleStringA strUpgradeVersion = m_currentTask.pack_version;
- CVersion latterVersion;//要更新到的版本号
- CVersion curVer = m_currentVersion;//当前版本号
- // 指定版本
- DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
- int n = sscanf(strUpgradeVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
- if (n != 4)
- {
- strErrMsg = CSimpleStringA::Format("指定升级版本号无效(%s)", strUpgradeVersion.GetData());
- LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_INSTALL_VERSION_FAIL, CSimpleStringA::Format("specified software version is invalid: [%s]", strUpgradeVersion.GetData()).GetData());
- return 0;
- }else{
- latterVersion = CVersion(dwMajor, dwMinor, dwRevision, dwBuild);
- }
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("latterVersion :%s",latterVersion.ToString().GetData());
- if(curVer.ToString()==strUpgradeVersion){
- //版本号相同,
- strErrMsg = CSimpleStringA::Format("指定升级版本号与当前版本相同,无效(配置:%s, 当前:%s)", strUpgradeVersion.GetData(),curVer.ToString().GetData());
- return 0;
- //}else if(m_currentVersion.ToString().Compare(strUpgradeVersion)==1){
- //字符串比较版本号大小改为整形数字对比
- }else if(dwMajor < curVer.GetMajor()
- || (dwMajor == curVer.GetMajor() && dwMinor < curVer.GetMinor())
- || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision < curVer.GetRevision())
- || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision == curVer.GetRevision() && dwBuild < curVer.GetBuild())){
- //升级版本小于当前版本
- strErrMsg = CSimpleStringA::Format("指定升级版本号无效(配置:%s,解析:%s,当前:%s)", strUpgradeVersion.GetData(),latterVersion.ToString().GetData(),curVer.ToString().GetData());
- return 0;
- }
- //判断是否需要创建新版本
-
- CSimpleStringA strErrInfo = "";
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateNewVersion,version[%s],pack[%s]",strUpgradeVersion.GetData(),m_currentTask.pack_name.GetData());
- ErrorCodeEnum rc = CreateNewVersion(latterVersion,strErrInfo);
- if (rc != Error_Succeed)
- {
- strErrMsg = CSimpleStringA::Format("CreateNewVersion fail:%s",strErrInfo.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewVersion,version[%s] fail:%s",strUpgradeVersion.GetData(),strErrInfo.GetData());
- //清理临时版本文件夹
- ClearUpgradeFailVersion(latterVersion);
- return 0;
- }else{
- m_currentTask.NewVersion = strUpgradeVersion;//赋值升级版本号给内存变量
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewVersion,version[%s] succ , pack[%s]",strUpgradeVersion.GetData(), m_currentTask.pack_name.GetData());
- }
- }
- //循环执行安装命令
- int iRet=1;//默认是成功
- if(!m_currentTask.install_step.empty()){
-
- int iCount = m_currentTask.install_step.size();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d",iCount);
- for (int j = 0; j < iCount; j++){
- CInstallStep* tmp = m_currentTask.install_step.front();
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====begin cmd=[%s]=====",tmp->cmdType.GetData());
- //开始处理具体命令
- if(tmp->cmdType=="Delete"){
- bool ret = ExecDeleteCmd(strErrMsg,tmp);
- if(!ret){
- //报错才判断
- if(tmp->cmdFail == 0 ){
- iRet = 0;
- break;//出错直接退出
- }else if(tmp->cmdFail == 1 ){
- //继续
- }else{
- iRet = 0;
- break;//其他值也退出
- }
- }
- }else if(tmp->cmdType=="Copy"){
- bool ret = ExecCpoyCmd(strErrMsg,tmp);
- if(!ret){
- //报错才判断
- if(tmp->cmdFail == 0){
- iRet = 0;
- break;//出错直接退出
- }else if(tmp->cmdFail == 1){
- //继续
- }else{
- iRet = 0;
- break;//其他值也退出
- }
- }
- }else if(tmp->cmdType=="Run"){
- int retInt = ExecRunCmd(strErrMsg,tmp);
- if(retInt==0||retInt==-1){
- //报错才判断
- if(tmp->cmdFail == 0 ){
- iRet = retInt;//会有0,-1值
- break;//出错直接退出,并返回体系外结果
- }else if(tmp->cmdFail == 1 ){
- //继续
- }else{
- iRet = 0;
- break;//其他值也退出
- }
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cmd=[%s] is invalid",tmp->cmdType.GetData());
- iRet = 0;
- break;//命令无效直接退出
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====end cmd=[%s]=====",tmp->cmdType.GetData());
- m_currentTask.install_step.pop();//去除元素
- delete tmp;//删除内存
- }
- }
- return iRet;//返回处理结果
- }
- int CUpgradeTaskFSM::ExecRunCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
- {
- CSimpleStringA destPath ;//目的路径
- if(ins->dstPathType=="0"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(1,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }else if(ins->dstPathType=="1"){
- destPath = ins->dstPath;//绝对路径
- }else if(ins->dstPathType=="2"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(2,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }else if(ins->dstPathType=="3"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(3,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }else if(ins->dstPathType=="4"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(4,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级包相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 4 is fail");
- return false;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPathType is invalid %s",ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPathType is invalid %s",ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPath is %s",destPath.GetData());
- // ToRun=install.bat
- if (ExistsFileA(destPath.GetData()))
- {
- ostuile_void_ptr store = osutil_sure_redirect_32sys_in_wow64();
- string sysPathStr = destPath.GetData();
- CSimpleStringA err ="";
- int ret = system_on(sysPathStr,true,err);
- osutil_reset_redirect_32sys_in_wow64(&store);
- if(ret!=0){
- //程序执行异常,结果未知
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown ,err=%s", err.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ,err=%s", err.GetData());
- return -1;//未知结果返回
- }else{
- //进一步看返回结果文件判断是否成功
- CSimpleStringA strUnzipPath = GetFileDirectory(destPath.GetData());
- CSimpleStringA strResultLog = strUnzipPath + SPLIT_SLASH_STR + "result.log";//结果文件
- CSimpleStringA eErrorCode = "";
- //获取结果文件
- if (!GetSysUpgradeResult(strResultLog, eErrorCode, strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, get result from result.log fail, %s", strErrMsg.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail ,get result from result.log fail, %s", strErrMsg.GetData());
- return 0;//失败
- }
- if (eErrorCode == "0")
- {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is succ,[%s] ", destPath.GetData());
- return 1;//成功
- }else{
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
- return 0;//失败
- }
- }
- }
- else
- {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, run file [%s] is not Exist",destPath.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, run file [%s] is not Exist",destPath.GetData());
- return 0;//失败
- }
- }
- bool CUpgradeTaskFSM::ExecDeleteCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
- {
- //只删除同一层目录下的文件和文件夹
- CSimpleStringA destPath ;//目的路径+通配符
- if(ins->dstPathType=="0"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(1,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }else if(ins->dstPathType=="1"){
- destPath = ins->dstPath;//绝对路径
- }else if(ins->dstPathType=="2"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(2,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
-
- }else if(ins->dstPathType=="3"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(3,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPathType is invalid %s",ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPathType is invalid %s",ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPath is %s",destPath.GetData());
- if(destPath.IndexOf("*")>0){
- CSimpleStringA strFileFilter = _GetFileName(destPath);
- CSimpleStringA strDestDir = destPath.SubString(0, destPath.GetLength()-strFileFilter.GetLength()-1);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match filter name [%s] in dir [%s]", strFileFilter.GetData(), strDestDir.GetData());
- // 删除所有匹配文件
- bool bRet = true;
- auto arr = fileutil_get_sub_files(strDestDir.GetData());
- if (arr != NULL)
- {
- for (int i = 0; i < arr->nelts; ++i)
- {
- char *file = ARRAY_IDX(arr, i, char*);
- if (IsFileMatch(strFileFilter, _GetFileName(file)))
- {
- if(RemoveFileA(file)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", file);
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", file);
- strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", file);
- bRet = false;
- break;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match file: [%s]", file);
- }
-
- }
- toolkit_array_free2(arr);
- if(!bRet){
- return bRet;
- }
- }
- // 删除所有匹配子目录
- auto subdirs = fileutil_get_sub_dirs(strDestDir.GetData());
- if (subdirs != NULL)
- {
- for (int i = 0; i < subdirs->nelts; ++i)
- {
- const char *dir = ARRAY_IDX(subdirs, i, char*);
- if (IsFileMatch(strFileFilter, _GetFileName(dir)))
- {
- if(RemoveDirRecursive(dir)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", dir);
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", dir);
- strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", dir);
- bRet = false;
- break;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match dir: [%s]", dir);
- }
- }
- toolkit_array_free2(subdirs);
- if(!bRet){
- return bRet;
- }
- }
- return bRet;
- }else{
- //直接删除文件
- bool bRet = true;
- if (ExistsFileA(destPath.GetData()))
- {
- if(RemoveFileA(destPath.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", destPath.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", destPath.GetData());
- strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", destPath.GetData());
- bRet = false;
- }
- return bRet;
- }
- else if (ExistsDirA(destPath.GetData()))
- {
- if(RemoveDirRecursiveA(destPath.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", destPath.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", destPath.GetData());
- strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", destPath.GetData());
- bRet = false;
- }
- return bRet;
- }
- else
- {
- //指定文件不再则忽略删除此文件
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file [%s] not exists,ignore delete file", destPath.GetData());
- return bRet;
- }
- }
- }
- bool CUpgradeTaskFSM::ExecCpoyCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
- {
- CSimpleStringA sourcePath ;//路径+通配符
- if(ins->srcPathType=="0"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(1,rootPath)){
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 1 is fail");
- return false;
- }
- }else if(ins->srcPathType=="1"){
- sourcePath = ins->srcPath;//绝对路径
- }else if(ins->srcPathType=="2"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(2,rootPath)){
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//当前版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 2 is fail");
- return false;
- }
- }else if(ins->srcPathType=="3"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(4,rootPath)){
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//升级包相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 4 is fail");
- return false;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd srcPathType is invalid %s",ins->srcPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd srcPathType is invalid %s",ins->srcPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd sourcePath is %s",sourcePath.GetData());
- CSimpleStringA destPath ;//目的路径文件夹
- if(ins->dstPathType=="0"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(1,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }else if(ins->dstPathType=="1"){
- destPath = ins->dstPath;//绝对路径
- }else if(ins->dstPathType=="2"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(2,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }else if(ins->dstPathType=="3"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(3,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- //}else if(ins->dstPathType=="4"){
- // CSimpleStringA rootPath="";
- // if(GetRootTypePath(4,rootPath)){
- // destPath = CSimpleStringA::Format("%s\\%s",rootPath.GetData(),ins->dstPath.GetData());//升级包相对路径
- // }else{
- // strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 4 is fail");
- // return false;
- // }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd dstPathType is invalid %s",ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd dstPathType is invalid %s",ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd destPath is %s",destPath.GetData());
- if(sourcePath.IndexOf("*")>0){
- //循环匹配拷贝
- //找到要扫描的文件夹
- CSimpleStringA strFileDir = GetFileDirectory(sourcePath.GetData());
- //过滤通配条件
- CSimpleStringA strFileFilter = _GetFileName(sourcePath.GetData());
- list<CSimpleStringA> fileList;
- //获取所有根文件夹下的文件相对路径:如mod\test.dll
- RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find fileList =%d",fileList.size());
- if(fileList.size()==0){
- //判断mod文件夹未空则报错
- if(sourcePath.IndexOf("mod")!=-1){
- LogWarn(Severity_Low, Error_Exception, WARN_TASK_COPY_FILE_ZERO,CSimpleStringA::Format("ExecCpoyCmd sourcePath is [%s] file is 0",sourcePath.GetData()));
- }
- }
- for(auto it = fileList.begin(); it != fileList.end(); it++)
- {
- if (IsFileMatch(strFileFilter, _GetFileName((const char*)(*it))))
- {
- CSimpleStringA strSrcName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", GetFileDirectory(sourcePath.GetData()).GetData(), (const char*)(*it));//源文件路径
- CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(),(const char*)(*it));//目标文件路径
- //匹配成功,开始拷贝文件
- CSimpleStringA errMsg = "";
- ErrorCodeEnum rc = CopyFileOperate(strSrcName.GetData(),strDestName.GetData(),3,errMsg);
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] to [%s] %s", strSrcName.GetData(),strDestName.GetData(), rc == Error_Succeed ? "succeed" : "fail");
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail: %s",strSrcName.GetData(),errMsg.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail: %s",strSrcName.GetData(),errMsg.GetData());
- return false;//报错
- }
- }
- }
-
- }else{
- //直接拷贝文件:考虑有些文件因智能对比不一定下发,故如果文件不存在,则默认忽略此策略
- CSimpleStringA errMsg = "";
- CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), _GetFileName(sourcePath.GetData()));
- if(ExistsFileA(sourcePath.GetData())){
- ErrorCodeEnum rc = CopyFileOperate(sourcePath.GetData(),strDestName.GetData(),3,errMsg);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:%s",sourcePath.GetData(),errMsg.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail:%s",sourcePath.GetData(),errMsg.GetData());
- return false;//报错
- }
- }else{
- if(ins->srcPathType=="3"){
- //升级包因智能升级不一定有指定的文件存在
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("拷贝指定的文件[%s]不存在,因智能升级对比过滤,故忽略此文件拷贝",sourcePath.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:file to copy not exist",sourcePath.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail:file to copy not exist",sourcePath.GetData());
- return false;//报错
- }
-
- }
- }
- return true;
- }
- bool CUpgradeTaskFSM::GetRootTypePath(int rootType,CSimpleStringA &Path)
- {
- CSimpleStringA tempPath;
- if (rootType == 1) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Root", tempPath);//例如:C:\Run /opt/Run
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- string runPathStr = tempPath.GetData();
- int pos = runPathStr.find_last_of(SPLIT_SLASH);
- Path = runPathStr.substr(0, pos).c_str();
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is error");
- return false;
- }
- }
- else if (rootType == 2) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Base", tempPath);//例如:C:\Run\version\4.8.1.1 /opt/Run/version/4.8.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- Path = tempPath;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currVer path is error");
- return false;
- }
- }
- else if (rootType == 3) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", tempPath);//例如:C:\Run\version\4.9.1.1 /opt/Run/version/4.9.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradeVer path is error");
- return false;
- }
- }
- else if (rootType == 4) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Downloads", tempPath);//例如:C:\rvc\Downloads\4.8.1.1 /opt/rvc/Downloads/4.8.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- CSimpleStringA strUnzipDir;
- strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_name.GetData());
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")) {
- Path = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
- }
- else {
- Path = strUnzipDir;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is error");
- return false;
- }
- }
- return true;
- }
- ErrorCodeEnum CUpgradeTaskFSM::CopyFileOperate(const char* srcPath, const char* destPath, int nCopyMode, CSimpleStringA &strErrMsg)
- {
- //源文件是否存在
- if (!ExistsFileA(srcPath))
- {
- strErrMsg = CSimpleStringA::Format("CopyFileOperate file [%s] to copy not exist", srcPath);
- return Error_NotExist;
- }
- //目标文件夹是否存在
- CSimpleStringA strDestDir = GetFileDirectory(destPath);
- if (!ExistsDirA(strDestDir.GetData())){
- if(!CreateDirA(strDestDir.GetData(), TRUE)){
- strErrMsg = CSimpleStringA::Format("CopyFileOperate create strDestDir[%s] fail", strDestDir.GetData());
- return Error_Exception;
- }
- }
- //目标文件是否存在
- BOOL bDestFileExists = ExistsFileA(destPath);
- if (bDestFileExists){
- RemoveFileReadOnlyAttributeA(destPath);
- }
- BOOL bRet = TRUE;
- switch (nCopyMode)
- {
- case 1:
- {
- if (bDestFileExists) {
- if (fileutil_copy_file(destPath, srcPath) == 0) {
- bRet = TRUE;
- }
- else {
- bRet = FALSE;
- }
- }
- else {
- LOG_TRACE("ignore file [%s] copy for dest file not exists", srcPath);
- }
- }
- break;
- case 2:
- {
- if (!bDestFileExists) {
- if (fileutil_copy_file(destPath, srcPath) == 0) {
- bRet = TRUE;
- }
- else {
- bRet = FALSE;
- }
- }
- else
- LOG_TRACE("ignore file [%s] copy for dest file exists", srcPath);
- }
- break;
- case 3:
- if (fileutil_copy_file(destPath, srcPath) == 0) {
- bRet = TRUE;
- }
- else {
- bRet = FALSE;
- }
- break;
- case 4:
- {
- // 不发生拷贝,只进行判断
- if(bDestFileExists)
- LOG_TRACE("file [%s] exist", srcPath);
- else
- LOG_TRACE("file [%s] not exist", srcPath);
- }
- break;
- }
- if (bRet){
- RemoveFileReadOnlyAttributeA(destPath);
- }else{
- strErrMsg = CSimpleStringA::Format("CopyFileOperate copy file fail:%d", GetLastError());
- }
- ErrorCodeEnum rc = bRet ? Error_Succeed : Error_Unexpect;
- return rc;
- }
- ErrorCodeEnum CUpgradeTaskFSM::SetRunSucceed(const char* pPackFile)
- {
- // 拷贝升级包到Upgraded目录
- CSimpleStringA strDownloadPath, strUpgradedPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadPath);
- if(rc!=Error_Succeed){
- return rc;
- }
- rc = m_pEntity->GetFunction()->GetPath("Upgraded", strUpgradedPath);
- if(rc!=Error_Succeed){
- return rc;
- }
- CSimpleStringA strSourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strDownloadPath, pPackFile);
- CSimpleStringA strDestPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strUpgradedPath, pPackFile);
- fileutil_copy_file(strDestPath.GetData(), strSourcePath.GetData());
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::UpgradeToNewVersion()
- {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin UpgradeToNewVersion");
- //获取新版本号
- if(m_currentTask.NewVersion.IsNullOrEmpty()){
- if(m_currentTask.pack_version.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("task NewVersion is empty , no need to write");
- return Error_Succeed;
- }else{
- 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());
- 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());
- return Error_Unexpect;//这种情况有问题,需要清除此任务
- }
- }else{
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpgradeToNewVersion fail , get RootVer path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,"UpgradeToNewVersion: get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.NewVersion.GetData());
- if(!ExistsDirA(strNewVerPath.GetData())){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, strNewVerPath =%s is not exist,fail",strNewVerPath.GetData()).GetData());
- return Error_Unexpect;//这种情况有问题,需要清除此任务
- }
- //修改运行时文件
- //修改active配置
- CSimpleStringA strActiveFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "active.txt", rootVerPath.GetData());
- if(!ExistsFileA(strActiveFile.GetData())){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,"UpgradeToNewVersion fail, active file is not exist");
- return Error_Unexpect;
- }
- //先做active文件备份,后面写入失败再copy回去
- #ifdef RVC_OS_WIN
- bool backupSucc = true;
- CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\back_active.txt", rootVerPath.GetData());
- if(!CopyFileA(strActiveFile.GetData(),strBackupActiveFile.GetData(),FALSE)){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, back up active.txt fail, err=%d",(int)GetLastError()).GetData());
- backupSucc = false;
- }
- FILE* fp = fopen(strActiveFile.GetData(),"wb+");
- if(fp==NULL){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open write active.txt fail, err=%d",(int)GetLastError()).GetData());
- return Error_Unexpect;
- }
- int ret = fwrite(m_currentTask.NewVersion.GetData(),m_currentTask.NewVersion.GetLength(),1,fp);
- if(ret!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, write active.txt fail, err=%d",(int)GetLastError()).GetData());
- fclose(fp);
- if(backupSucc){
- if(CopyFileA(strBackupActiveFile.GetData(),strActiveFile.GetData(),FALSE)){
- RemoveFileA(strBackupActiveFile.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("back_active.txt copy to active.txt is succ");
- }else{
- 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());
- }
- }
- return Error_Unexpect;
- }else{
- fflush(fp);
- int CommitRet = _commit(_fileno(fp));
- if (CommitRet != 0) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, commit write active.txt fail, err=%d", (int)GetLastError()).GetData());
- }
- fclose(fp);
- if (ExistsFileA(strBackupActiveFile.GetData())) {
- RemoveFileA(strBackupActiveFile.GetData());
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("write active.txt succ, version[%s]", m_currentTask.NewVersion.GetData());
- }
- //重新读active文件,看文件内容是什么
- fp = fopen(strActiveFile.GetData(),"rb");
- if(fp==NULL){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open read active.txt fail, err=%d",(int)GetLastError()).GetData());
- return Error_Unexpect;
- }
- char cVer[16] = {0};
- int re = fread(cVer,m_currentTask.NewVersion.GetLength(),1,fp);
- if(re!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, read active.txt fail, err=%d",(int)GetLastError()).GetData());
- }else{
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read rewritten file active.txt, version[%s]", cVer);
- }
- fclose(fp);
- return Error_Succeed;
- #else
- bool backupSucc = true;
- CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s/back_active.txt", rootVerPath.GetData());
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("strBackupActiveFile=%s", strBackupActiveFile.GetData());
- if (fileutil_copy_file( strBackupActiveFile.GetData(),strActiveFile.GetData())!=0) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, back up active.txt fail, err=%d", errno).GetData());
- backupSucc = false;
- }
- FILE* fp = fopen(strActiveFile.GetData(),"wb+");
- if(fp==NULL){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, open write active.txt fail, err=%d", errno).GetData());
- return Error_Unexpect;
- }
- int ret = fwrite(m_currentTask.NewVersion.GetData(),m_currentTask.NewVersion.GetLength(),1,fp);
- if(ret!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, write active.txt fail, err=%d", errno).GetData());
- fclose(fp);
- if (backupSucc) {
- if (fileutil_copy_file(strActiveFile.GetData(), strBackupActiveFile.GetData())==0) {
- RemoveFileA(strBackupActiveFile.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("back_active.txt copy to active.txt is succ");
- }else{
- 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());
- }
- }
- return Error_Unexpect;
- }else{
- fflush(fp);
- int CommitRet = fsync(fileno(fp));
- if (CommitRet != 0) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, commit write active.txt fail, err=%d", errno).GetData());
- }
- fclose(fp);
- if (ExistsFileA(strBackupActiveFile.GetData())) {
- RemoveFileA(strBackupActiveFile.GetData());
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("write active.txt succ, version[%s]", m_currentTask.NewVersion.GetData());
- }
- //重新读active文件,看文件内容是什么
- fp = fopen(strActiveFile.GetData(),"rb");
- if(fp==NULL){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open read active.txt fail, err=%d", errno).GetData());
- return Error_Unexpect;
- }
- char cVer[16] = {0};
- int re = fread(cVer,m_currentTask.NewVersion.GetLength(),1,fp);
- if(re!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, read active.txt fail, err=%d", errno).GetData());
- }else{
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read rewritten file active.txt, version[%s]", cVer);
- }
- fclose(fp);
- return Error_Succeed;
- #endif
- }
-
- }
- ErrorCodeEnum CUpgradeTaskFSM::RollBackToHistoryVersion(CVersion historyVersion)
- {
- // 判断目标版本是否小于当前版本
- CVersion v=m_currentVersion;//当前版本
- CVersion curVersion(v.GetMajor(), v.GetMinor(), v.GetRevision(), v.GetBuild());
- if (curVersion <= historyVersion)
- {
- 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());
- return Error_Param;
- }
- // 检查对应文件夹是否存在
- CSimpleStringA strHisVersion = historyVersion.ToString();
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
- if(rc!=Error_Succeed){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryVersion fail , get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strHisVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), strHisVersion.GetData());
- if (!ExistsDirA(strHisVerPath.GetData()))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryVersion fail, history version dir [%s] not exists", strHisVerPath.GetData()).GetData());
- return Error_NotExist;
- }
- //删除当时的运行缓存值
- // 修改active.txt文件,可能存在失败
- CSimpleStringA strActiveFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "active.txt", rootVerPath.GetData());
- if(!ExistsFileA(strActiveFile.GetData())){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryVersion fail, active file is not exist");
- return Error_Unexpect;
- }
- //先做active文件备份,后面写入失败再copy回去
- #ifdef RVC_OS_WIN
- bool backupSucc = true;
- CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\Rollback_active.txt", rootVerPath.GetData());
- if(!CopyFileA(strActiveFile.GetData(),strBackupActiveFile.GetData(),FALSE)){
- 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());
- backupSucc = false;
- }
- FILE* fp = fopen(strActiveFile.GetData(),"wb+");
- if(fp==NULL){
- 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());
- return Error_Unexpect;
- }
- int ret = fwrite(strHisVersion.GetData(),strHisVersion.GetLength(),1,fp);
- if(ret!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, write active.txt fail,err=%d", (int)GetLastError()).GetData());
- fclose(fp);
- if(backupSucc){
- if(CopyFileA(strBackupActiveFile.GetData(),strActiveFile.GetData(),FALSE)){
- RemoveFileA(strBackupActiveFile.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Rollback_active.txt copy to active.txt is succ");
- }else{
- 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());
- }
- }
- return Error_Unexpect;
- }else{
- fflush(fp);
- int CommitRet = _commit(_fileno(fp));
- if (CommitRet != 0) {
- 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());
- }
- fclose(fp);
- if (ExistsFileA(strBackupActiveFile.GetData())) {
- RemoveFileA(strBackupActiveFile.GetData());
- }
- }
- //重新读active文件,看文件内容是什么
- fp = fopen(strActiveFile.GetData(),"rb");
- if(fp==NULL){
- 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());
- return Error_Unexpect;
- }
- char cVer[16] = {0};
- int re = fread(cVer,strHisVersion.GetLength(),1,fp);
- if(re!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Read active.txt fail,err=%d", (int)GetLastError()).GetData());
- }else{
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read rewritten file active.txt, version[%s]", cVer);
- }
- fclose(fp);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set rollback to history version [%s] succeed", (const char*)strHisVersion);
- return Error_Succeed;
- #else
- bool backupSucc = true;
- CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s/Rollback_active.txt", rootVerPath.GetData());
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("strBackupActiveFile=%s", strBackupActiveFile.GetData());
- if (fileutil_copy_file(strBackupActiveFile.GetData(), strActiveFile.GetData())!=0) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, back up active.txt fail, err=%d", errno).GetData());
- backupSucc = false;
- }
- FILE* fp = fopen(strActiveFile.GetData(),"wb+");
- if(fp==NULL){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open write active.txt fail,err=%d", errno).GetData());
- return Error_Unexpect;
- }
- int ret = fwrite(strHisVersion.GetData(),strHisVersion.GetLength(),1,fp);
- if(ret!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, write active.txt fail,err=%d", errno).GetData());
- fclose(fp);
- if (backupSucc) {
- if (fileutil_copy_file(strActiveFile.GetData(), strBackupActiveFile.GetData())==0) {
- RemoveFileA(strBackupActiveFile.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Rollback_active.txt copy to active.txt is succ");
- }else{
- 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());
- }
- }
- return Error_Unexpect;
- }else{
- fflush(fp);
- int CommitRet = fsync(fileno(fp));
- if (CommitRet != 0) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, commit write active.txt fail, err=%d", errno).GetData());
- }
- fclose(fp);
- if (ExistsFileA(strBackupActiveFile.GetData())) {
- RemoveFileA(strBackupActiveFile.GetData());
- }
- }
- //重新读active文件,看文件内容是什么
- fp = fopen(strActiveFile.GetData(),"rb");
- if(fp==NULL){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open read active.txt fail,err=%d", errno).GetData());
- return Error_Unexpect;
- }
- char cVer[16] = {0};
- int re = fread(cVer,strHisVersion.GetLength(),1,fp);
- if(re!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Read active.txt fail,err=%d", errno).GetData());
- }else{
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read rewritten file active.txt, version[%s]", cVer);
- }
- fclose(fp);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set rollback to history version [%s] succeed", (const char*)strHisVersion);
- return Error_Succeed;
- #endif
- }
- void CUpgradeTaskFSM::RecursiveGetSubFiles(const char *pszDir, const char *pszTrimStart, list<CSimpleStringA>& retList)
- {
- if (!ExistsDirA(pszDir))
- return;
- auto arr = fileutil_get_sub_files(pszDir);
- if (arr != NULL)
- {
- for (int i = 0; i < arr->nelts; ++i)
- {
- char *file = ARRAY_IDX(arr, i, char*);
- #ifdef RVC_OS_WIN
- //不区分大小写
- if (pszTrimStart != NULL && strnicmp(file, pszTrimStart, strlen(pszTrimStart))==0) {
- #else
- //区分大小写
- if (pszTrimStart != NULL && strncmp(file, pszTrimStart, strlen(pszTrimStart)) == 0) {
- #endif
- file += strlen(pszTrimStart);
- if (*file == SPLIT_SLASH)
- file++;
- }
- retList.push_back(file);
- }
- toolkit_array_free2(arr);
- }
- arr = fileutil_get_sub_dirs(pszDir);
- if (arr != NULL)
- {
- for (int i = 0; i < arr->nelts; ++i)
- {
- char *dir = ARRAY_IDX(arr, i, char*);
- RecursiveGetSubFiles(dir, pszTrimStart, retList);
- }
- toolkit_array_free2(arr);
- }
- }
- bool CUpgradeTaskFSM::IsFileMatch(const char *pszFilter, const char *pszFileName)
- {
- const char *p1 = pszFilter;
- const char *p2 = pszFileName;
- if (p1 == NULL)
- return true;
- if (p2 == NULL)
- return false;
- if (*p1 ==NULL && *p2 ==NULL)
- return true;
- else if (*p1 == NULL)
- return false;
- else if (*p2 == NULL)
- {
- // 查找*p1是否全是*
- while(*p1 == '*')
- p1++;
- if (*p1 == NULL)
- return true;
- else
- return false;
- }
- if (*p1 != '*')
- {
- if (tolower(*p1) != tolower(*p2))
- return false;
- else
- return IsFileMatch(p1+1, p2+1);
- }
- else
- {
- while(*++p1 == '*');
- if (*p1 == NULL)
- return true;
- while (*p2)
- {
- while(tolower(*p1) != tolower(*p2) && *++p2);
- if (*p2 == NULL)
- return false;
- if(IsFileMatch(p1+1, p2+1))
- return true;
- p2++;
- }
- return false;
- }
- }
- bool CUpgradeTaskFSM::RecursiveCopyDir(const char *pszSourceDir, const char *pszDestDir,CSimpleStringA &strErrInfo)
- {
- array_header_t *arr;
- if (!ExistsDirA(pszSourceDir))
- {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("source dir [%s] not exists: %d", pszSourceDir, GetLastError());
- strErrInfo = CSimpleStringA::Format("source dir [%s] not exists: %d", pszSourceDir, GetLastError());
- return false;
- }
- if (!ExistsDirA(pszDestDir))
- {
- if (!CreateDirRecursiveA(pszDestDir))
- {
- strErrInfo = CSimpleStringA::Format("create dir [%s] fail: %d", pszDestDir, GetLastError());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("create dir fail: %s", strErrInfo.GetData());
- return false;
- }
- }
- arr = fileutil_get_sub_files_a(pszSourceDir);
- if (arr)
- {
- int i;
- for (i = 0; i < arr->nelts; ++i)
- {
- char szDestFile[256] = { 0 };
- char *file = ARRAY_IDX(arr, i, char*);
- strcpy(szDestFile, pszDestDir);
- if (szDestFile[strlen(szDestFile) - 1] != SPLIT_SLASH)
- strcat(szDestFile, SPLIT_SLASH_STR);
- strcat(szDestFile, strrchr(file, SPLIT_SLASH) + 1);
- if (fileutil_copy_file(szDestFile, file) != 0)
- {
- strErrInfo = CSimpleStringA::Format("copy file [%s] fail: %d", file, GetLastError());
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("copy file fail:%s", strErrInfo.GetData());
- toolkit_array_free2(arr);
- return false;
- }
- }
- toolkit_array_free2(arr);
- }
- arr = fileutil_get_sub_dirs_a(pszSourceDir);
- if (arr)
- {
- int i;
- for (i = 0; i < arr->nelts; ++i)
- {
- char szDestSubDir[256] = { 0 };
- char *dir = ARRAY_IDX(arr, i, char*);
- strcpy(szDestSubDir, pszDestDir);
- if (szDestSubDir[strlen(szDestSubDir) - 1] != SPLIT_SLASH)
- strcat(szDestSubDir, SPLIT_SLASH_STR);
- strcat(szDestSubDir, strrchr(dir, SPLIT_SLASH) + 1);
- if (!RecursiveCopyDir(dir, szDestSubDir,strErrInfo))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("copy dir [%s] fail: %d", dir, GetLastError());
- if (strErrInfo.IsNullOrEmpty()) {
- strErrInfo = CSimpleStringA::Format("copy dir [%s] fail: %d", dir, GetLastError());
- }
- toolkit_array_free2(arr);
- return false;
- }
- }
- toolkit_array_free2(arr);
- }
- return true;
- }
- CSimpleStringA CUpgradeTaskFSM::GetFileDirectory(const char *pszFullPath)
- {
- int i=strlen(pszFullPath)-1;
- for( ; i>0 && pszFullPath[i]!= SPLIT_SLASH; i--)NULL;
- return CSimpleStringA(pszFullPath, i);
- }
- int CUpgradeTaskFSM::system_on(string cmdFilePath, bool isWait,CSimpleStringA &errMsg)
- {
- #ifdef RVC_OS_WIN
- string cmdLine = "cmd /c ";
- cmdLine.append(cmdFilePath.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("exec bat %s",cmdLine.c_str());
- return waitSystem("cmd.exe", cmdLine.c_str(), true, errMsg);
- #else
- //linux直接用system函数即可
- return system(cmdFilePath.c_str());
- #endif
- }
- //返回值是0则正常执行,其他都是非正常未知状态
- int CUpgradeTaskFSM::waitSystem(string cmd, const char * par, bool nShow,CSimpleStringA &errMsg)
- {
- #ifdef RVC_OS_WIN
- SHELLEXECUTEINFOA ShExecInfo = { 0 };
- ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
- ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
- ShExecInfo.hwnd = NULL;
- ShExecInfo.lpVerb = NULL;
- ShExecInfo.lpFile = cmd.c_str(); //调用的程序名
- ShExecInfo.lpParameters = par; //调用程序的命令行参数
- ShExecInfo.lpDirectory = NULL;
- ShExecInfo.nShow = nShow ? SW_MINIMIZE: SW_HIDE; //窗口状态为隐藏
- ShExecInfo.hInstApp = NULL;
- if (!ShellExecuteEx(&ShExecInfo))
- {
- errMsg = CSimpleStringA::Format("shellExecute is fail :%d",GetLastError());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is fail :%s",errMsg.GetData());
- return -1;
- }
- //等到该进程结束,如果5分钟没结束,强行杀死进程
- if (WaitForSingleObject(ShExecInfo.hProcess, 5*60*1000) == WAIT_TIMEOUT)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is time out");
- errMsg = CSimpleStringA::Format("shellExecute is time out");
- if (TerminateProcess(ShExecInfo.hProcess, 0))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminateProcess is succ");
- }else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminateProcess is fail :%d",GetLastError());
- }
- if (CloseHandle(ShExecInfo.hProcess))
- {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is succ");
- }else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is fail");
- }
- return -1;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is succ");
- DWORD exitCode = 0;
- if (!GetExitCodeProcess(ShExecInfo.hProcess, &exitCode))
- {
- errMsg = CSimpleStringA::Format("GetExitCodeProcess is fail:%d",GetLastError());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetExitCodeProcess is fail:%s",errMsg.GetData());
- return -1;
- }
- if (CloseHandle(ShExecInfo.hProcess))
- {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is succ");
- }else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is fail");
- }
- if(exitCode!=0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetExitCodeProcess ret exitCode=%d",(int)exitCode);
- errMsg = CSimpleStringA::Format("GetExitCodeProcess ret exitCode=%d",(int)exitCode);
- }
- return exitCode;
- #else
- return 0;
- #endif
- }
- ErrorCodeEnum CUpgradeTaskFSM::UnzipPack(const char* unZipPackName)
- {
- #ifdef RVC_OS_WIN
- // 设定解压临时目录
- char szOldPath[MAX_PATH] = {};
- GetCurrentDirectoryA(MAX_PATH, szOldPath);
- CSimpleStringA strDownloadsPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,get Downloads Path is fail");
- return Error_Unexpect;
- }
-
- CSimpleStringA strZipFile = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), unZipPackName);
- //升级包是否存在
- if(!ExistsFileA(strZipFile)){
- LogWarn(Severity_Low, Error_NotExist, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
- return Error_NotExist;
- }
- CSimpleStringA strUnzipDir;
- strUnzipDir = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), unZipPackName);
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")){
- strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
- }
- // 解压目录是否存在,则先删除
- if (ExistsDirA(strUnzipDir.GetData()))
- {
- if(!RemoveDirRecursiveA(strUnzipDir.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,delete exist temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
- return Error_Unexpect;
- }
- }
- // 创建临时解压目录
- if(!CreateDirectoryA(strUnzipDir.GetData(), NULL)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,create temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
- return Error_Unexpect;
- }
- //设置当前目录为主目录
- if(!SetCurrentDirectoryA(strUnzipDir.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,SetCurrentDirectoryA dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
- return Error_Unexpect;
- }
- // 解压
- HZIP hz = OpenZip((void*)(const char*)strZipFile,0,ZIP_FILENAME);
- if (hz == 0)
- {
- SetCurrentDirectoryA(szOldPath);
- LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("open zip file [%s] fail", unZipPackName).GetData());
- return Error_Unexpect;
- }
- ZIPENTRY ze;
- ZRESULT zrc = GetZipItemA(hz,-1,&ze);
- if(zrc == ZR_OK){
- int numitems=ze.index;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("zip entry count is %d", ze.index);
- for (int i=0; i<numitems; i++)
- {
- zrc = GetZipItemA(hz,i,&ze);
- if(zrc==ZR_OK){
- //兼容压缩包里面中文名称是utf8编码
- if(!!toolkit_detect_utf8_str2(ze.name)){
- char *pGBK = ConvertUtf8ToGBK((const char*)ze.name);
- zrc = UnzipItem(hz,i,pGBK,0,ZIP_FILENAME);
- if(zrc ==ZR_OK){
- if (pGBK) free(pGBK);
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip [%s] UTF8 item fail,result=0x%X", pGBK,(int)zrc);
- if (pGBK) free(pGBK);
- break;
- }
- }else{
- zrc = UnzipItem(hz,i,ze.name,0,ZIP_FILENAME);
- if(zrc ==ZR_OK){
- //Dbg("unzip [%s] GBK item succeed", ze.name);
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip [%s] GBK item fail,result=0x%X", ze.name,(int)zrc);
- break;
- }
- }
- }else{
- //出错,退出
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip GetZipItemA [%d] item fail,fail=0x%X",i,(int)zrc);
- break;
- }
- }
- CloseZip(hz);
- }else{
- CloseZip(hz);
- }
- // 恢复当前目录
- SetCurrentDirectoryA(szOldPath);
- if(zrc!=ZR_OK){
- return Error_Exception;
- }
- return Error_Succeed;
- #else
- CSimpleStringA strDownloadsPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
- if (rc != Error_Succeed) {
- Dbg("unzipPack is fail,get Downloads Path is fail");
- return Error_Unexpect;
- }
- CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
- //升级包是否存在
- if (!ExistsFileA(strZipFile)) {
- LogWarn(Severity_Low, Error_NotExist, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
- return Error_NotExist;
- }
- CSimpleStringA strUnzipDir;
- strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")) {
- strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
- }
- // 解压目录是否存在,存在先删除
- if (ExistsDirA(strUnzipDir.GetData()))
- {
- if (!RemoveDirRecursiveA(strUnzipDir.GetData())) {
- Dbg("unzipPack is fail,delete exist temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), errno);
- return Error_Unexpect;
- }
- }
- // 创建临时解压目录
- if (!CreateDirA(strUnzipDir.GetData(), false)) {
- // 创建临时解压目录失败
- Dbg("unzipPack is fail,create temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), errno);
- return Error_Unexpect;
- }
- if (changeFileAtt(strZipFile.GetData())!=0) {
- //改变文件属性
- Dbg("unzipPack is fail,changeFileAtt zip [%s] fail,err=%d", strZipFile.GetData(), errno);
- return Error_Unexpect;
- }
- // 解压
- string zipFileStr = strZipFile.GetData();
- string zipTempDir = strUnzipDir.GetData();
- if (UnZipToDir(zipFileStr, zipTempDir) != 0)
- {
- LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("unzip pack [%s] fail", unZipPackName));
- return Error_NotExist;
- }
- return Error_Succeed;
- #endif
- }
- ErrorCodeEnum CUpgradeTaskFSM::DeleteUnzipDir()
- {
- CSimpleStringA strDownloadsPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("DeleteUnzipDir is fail,get Downloads Path is fail");
- return Error_Unexpect;
- }
- //判断解压缩文件夹名是否存在,不存在告警
- if (m_currentTask.pack_name.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("DeleteUnzipDir is fail ,temp unzip dir name is null");
- return Error_Unexpect;
- }
- CSimpleStringA strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), m_currentTask.pack_name.GetData());
-
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")){
- strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
- }
- // 解压目录是否存在,存在则删除
- if (ExistsDirA(strUnzipDir.GetData()))
- {
- if(!RemoveDirRecursiveA(strUnzipDir.GetData())){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), (int)GetLastError());
- return Error_Unexpect;
- }else{
- return Error_Succeed;
- }
- }
- return Error_Succeed;
- }
- void CUpgradeTaskFSM::SendUpgradeTaskProgress(CTaskProcess &process, CSimpleStringA logCodeStr, CSimpleStringA rtaStr)
- {
- Json::Value root;
- Json::FastWriter fw;//写入对象
- if(!process.strPackName.IsNullOrEmpty()){
- root["strPackName"]=process.strPackName.GetData();
- }else{
- root["strPackName"]="";
- }
-
- if(process.installVersion.IsNullOrEmpty()){
- root["installVersion"]="0.0.0.0";
- }else{
- root["installVersion"]=process.installVersion.GetData();
- }
- //string currentBuildStr = CSimpleStringA::Format("%d.%d.%d",process.CurrentVersion.GetMajor(),process.CurrentVersion.GetMinor(),process.CurrentVersion.GetRevision()).GetData();
- root["CurrentVersion"]=process.CurrentVersion.GetData();
- root["CurrentBuild"]= process.CurrentVersion.GetData();
- root["upgradeTimeStr"]=CSmallDateTime::GetNow().ToTimeString().GetData();
- if(!process.cInstallState.IsNullOrEmpty()){
- root["cInstallState"]=process.cInstallState.GetData();
- }else{
- root["cInstallState"]="";
- }
- if(!process.strInstallComment.IsNullOrEmpty()){
- CSimpleStringA comment = "task:";
- comment.Append(process.strInstallComment.GetData());
- root["strInstallComment"]=comment.GetData();
- }else{
- root["strInstallComment"]="";
- }
- string upgradeStr = fw.write(root);
- if (!upgradeStr.empty()) {
- LogWarn(Severity_Low, Error_Succeed, LOG_WRAN_UPGRADE_PROGRESS, upgradeStr.c_str());
- if (rtaStr.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(logCodeStr).setAPI("SendUpgradeTaskProgress")(upgradeStr.c_str());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(logCodeStr).setResultCode(rtaStr).setAPI("SendUpgradeTaskProgress")(upgradeStr.c_str());
- }
- }else{
- LogWarn(Severity_Middle,Error_Unexpect,ERR_WRAN_UPGRADE_PROGRESS,"获取升级过程信息错误");
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::GetRunConfigStrValue(const char *pszSection, const char *pszKey, CSimpleStringA &strValue)
- {
- CSmartPointer<IConfigInfo> pConfig;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_Run, pConfig);
- if (rc != Error_Succeed){
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode(RTAERR_CONFIG_OPEN_FAILED)("GetRunConfigStrValue get run config fail ,err=%d", (int)rc);
- return rc;
- }
- return pConfig->ReadConfigValue(pszSection, pszKey, strValue);
- }
- ErrorCodeEnum CUpgradeTaskFSM::SetRunConfigStrValue(const char *pszSection, const char *pszKey, const char *pszValue)
- {
- CSmartPointer<IConfigInfo> pConfig;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_Run, pConfig);
- if (rc != Error_Succeed){
- return rc;
- }
- return pConfig->WriteConfigValue(pszSection, pszKey, pszValue);
- }
- bool CUpgradeTaskFSM::ClearCurrTaskInfo()
- {
- if(SetRunConfigStrValue("upgradeTask","UpgradeTaskId","")!=Error_Succeed){
- return false;
- }
- if(SetRunConfigStrValue("upgradeTask","CreateTaskVersion","")!=Error_Succeed){
- return false;
- }
- if(SetRunConfigStrValue("upgradeTask","PackName","")!=Error_Succeed){
- return false;
- }
- if(SetRunConfigStrValue("upgradeTask","PendingState","")!=Error_Succeed){
- return false;
- }
- if(SetRunConfigStrValue("upgradeTask","NewVersion","")!=Error_Succeed){
- return false;
- }
- if (SetRunConfigStrValue("upgradeTask", "TaskType", "") != Error_Succeed) {
- return false;
- }
- if (SetRunConfigStrValue("upgradeTask", "depNewVersion", "") != Error_Succeed) {
- return false;
- }
- //试着删除可能临时下载的升级包文件
- CSimpleStringA strPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strPath);
- if(Error_Succeed != rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearCurrTaskInfo get Downloads path fail,upgradeTaskId=%s",m_currentTask.upgradeTaskId.GetData());
- return false;
- }
- CSimpleStringA tempPackPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s%s", strPath.GetData(), m_currentTask.pack_name.GetData(),".tmp");
- if(ExistsFileA(tempPackPath.GetData())){
- if(!RemoveFileA(tempPackPath.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearCurrTaskInfo delete tempPack fail,packPath=%s",tempPackPath.GetData());
- return false;
- }
- }
- //清空内存变量
- m_currentTask.upgradeTaskId = "";
- m_currentTask.createTaskVersion = "";
- m_currentTask.pack_name = "";
- m_currentTask.cPendingState = "";
- m_currentTask.NewVersion="";
- m_currentTask.task_type = "";
- m_currentTask.depNewVersion = "";
- m_currentTask.pack_version = "";
- m_currentTask.stop_media_play =false;
- m_currentTask.reboot_type = 0;
- m_currentTask.file_path="";
- m_currentTask.download_url = "";
- m_currentTask.pack_hash = "";
- m_currentTask.pack_length = 0;
- ClearInstallStep();
- return true;
- }
- bool CUpgradeTaskFSM::ClearInstallStep()
- {
- //清理安装步骤
- int iCount = m_currentTask.install_step.size();
- for (int j = 0; j < iCount; j++){
- CInstallStep* tmp = m_currentTask.install_step.front();
- m_currentTask.install_step.pop();
- delete tmp;//删除对象
- }
- return true;
- }
- ErrorCodeEnum CUpgradeTaskFSM::LoadPersistTaskInfo()
- {
- // 从运行配置中读出上次未处理完的任务
- // 上次未安装结束
- CTaskInfo taskInfo = {};
- CSimpleStringA strValue;
- ErrorCodeEnum rc = GetRunConfigStrValue("upgradeTask", "UpgradeTaskId", strValue);
- if(rc!=Error_Succeed){
- 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);
- return rc;
- }
- taskInfo.upgradeTaskId = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "CreateTaskVersion", strValue);
- if(rc!=Error_Succeed){
- 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);
- return rc;
- }
- taskInfo.createTaskVersion = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "PackName", strValue);
- if(rc!=Error_Succeed){
- 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);
- return rc;
- }
- taskInfo.pack_name = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "PendingState", strValue);
- if(rc!=Error_Succeed){
- 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);
- return rc;
- }
- taskInfo.cPendingState = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "NewVersion", strValue);
- if(rc!=Error_Succeed){
- 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);
- return rc;
- }
- taskInfo.NewVersion = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "TaskType", strValue);
- if (rc != Error_Succeed) {
- 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);
- return rc;
- }
- taskInfo.task_type = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "depNewVersion", strValue);
- if (rc != Error_Succeed) {
- 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);
- return rc;
- }
- taskInfo.depNewVersion = strValue;
- //初始化其他变量
- //CSimpleStringA pack_version; //升级包指定的版本号
- //CSimpleStringA to_copy; //拷贝文件列表
- //CSimpleStringA to_run; //体系外运行脚本文件名称
- //bool reboot_type; //重启类型
- //CSimpleStringA download_url; //升级包下载地址
- //CSimpleStringA pack_hash; //升级包hash值
- //long pack_length; //升级包长度
- taskInfo.pack_version = "";
- taskInfo.reboot_type = 0;
- taskInfo.file_path = "";
- taskInfo.download_url = "";
- taskInfo.pack_hash = "";
- taskInfo.pack_length = 0;
- taskInfo.stop_media_play = true;
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, UpgradeTaskId=%s", taskInfo.upgradeTaskId.GetData());
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, CreateTaskVersion=%s",taskInfo.createTaskVersion.GetData());
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, PackName=%s",taskInfo.pack_name.GetData());
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, PendingState=%s",taskInfo.cPendingState.GetData());
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, NewVersion=%s",taskInfo.NewVersion.GetData());
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, TaskType=%s", taskInfo.task_type.GetData());
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, depNewVersion=%s", taskInfo.depNewVersion.GetData());
- if (!taskInfo.upgradeTaskId.IsNullOrEmpty()) {
- 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]",
- taskInfo.upgradeTaskId.GetData(), taskInfo.task_type.GetData(), taskInfo.cPendingState.GetData(),
- taskInfo.NewVersion.GetData(), taskInfo.depNewVersion.GetData(), taskInfo.createTaskVersion.GetData(), taskInfo.pack_name.GetData());
- }
- else {
- 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]",
- taskInfo.upgradeTaskId.GetData(), taskInfo.task_type.GetData(), taskInfo.cPendingState.GetData(),
- taskInfo.NewVersion.GetData(), taskInfo.depNewVersion.GetData(), taskInfo.createTaskVersion.GetData(), taskInfo.pack_name.GetData());
- }
- m_currentTask = taskInfo;
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::loadCenterCfgInfo()
- {
- //访问http地址的读取
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
- if (rc == Error_Succeed){
- m_centerUrl.queryPreTaskUrl = QUERY_PRE_TASK_URL;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read queryPreTaskUrl=%s", m_centerUrl.queryPreTaskUrl.c_str());
- m_centerUrl.queryContinueTaskUrl = QUERY_CONTINUE_TASK_URL;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read queryContinueTaskUrl=%s", m_centerUrl.queryContinueTaskUrl.c_str());
- m_centerUrl.updateTaskUrl = UPDATE_TASK_URL;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read updateTaskUrl=%s", m_centerUrl.updateTaskUrl.c_str());
- m_centerUrl.queryCurrTaskUrl = QUERY_CURR_TASK_URL;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read queryCurrTaskUrl=%s", m_centerUrl.queryCurrTaskUrl.c_str());
- m_centerUrl.queryNewTaskUrl = QUERY_NEW_TASK_URL;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read queryNewTaskUrl=%s", m_centerUrl.queryNewTaskUrl.c_str());
- m_centerUrl.queryTaskStatus = QUERY_TASK_STATUS_URL;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read queryTaskStatus=%s", m_centerUrl.queryTaskStatus.c_str());
- m_centerUrl.sendSM3TaskUrl = SEND_SM3_TASK_URL;
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read sendSM3TaskUrl=%s", m_centerUrl.sendSM3TaskUrl.c_str());
- CSimpleStringA str="";
- //加载后端服务访问地址
- //rc = spConfig->ReadConfigValue("UpgradeManager", "QueryPreTaskUrl", str);
- //if(rc==Error_Succeed){
- // m_centerUrl.queryPreTaskUrl = str;
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryPreTaskUrl=%s",str.GetData());
- //}else{
- // LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryPreTaskUrl error");
- // return rc;
- //}
- //rc = spConfig->ReadConfigValue("UpgradeManager", "QueryContinueTaskUrl", str);
- //if(rc==Error_Succeed){
- // m_centerUrl.queryContinueTaskUrl = str;
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryContinueTaskUrl=%s",str.GetData());
- //}else{
- // LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryContinueTaskUrl error");
- // return rc;
- //}
- //rc = spConfig->ReadConfigValue("UpgradeManager", "UpdateTaskUrl", str);
- //if(rc==Error_Succeed){
- // m_centerUrl.updateTaskUrl = str;
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini UpdateTaskUrl=%s",str.GetData());
- //}else{
- // LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini UpdateTaskUrl error");
- // return rc;
- //}
- //rc = spConfig->ReadConfigValue("UpgradeManager", "QueryCurrTaskUrl", str);
- //if(rc==Error_Succeed){
- // m_centerUrl.queryCurrTaskUrl = str;
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryCurrTaskUrl=%s",str.GetData());
- //}else{
- // LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryCurrTaskUrl error");
- // return rc;
- //}
- //rc = spConfig->ReadConfigValue("UpgradeManager", "QueryNewTaskUrl", str);
- //if(rc==Error_Succeed){
- // m_centerUrl.queryNewTaskUrl = str;
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryNewTaskUrl=%s",str.GetData());
- //}else{
- // LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryNewTaskUrl error");
- // return rc;
- //}
- //rc = spConfig->ReadConfigValue("UpgradeManager", "QueryTaskStatus", str);
- //if(rc==Error_Succeed){
- // m_centerUrl.queryTaskStatus = str;
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryTaskStatus=%s",str.GetData());
- //}else{
- // LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryTaskStatus error");
- // return rc;
- //}
- //rc = spConfig->ReadConfigValue("UpgradeManager", "SendSM3TaskUrl", str);
- //if(rc==Error_Succeed){
- // m_centerUrl.sendSM3TaskUrl = str;
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini SendSM3TaskUrl=%s",str.GetData());
- //}else{
- // LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini SendSM3TaskUrl error");
- // return rc;
- //}
- //新的下载分段切片长度值(单位K)
- rc = spConfig->ReadConfigValue("UpgradeManager", "NewEachDownloadLen", str);
- if(rc==Error_Succeed){
- if(str.IsNullOrEmpty()){
- m_newEachDownloadLen = DOWNLOAD_CONTENT_EACH_LEN;
- }else{
- if(atoi(str.GetData())>16){
- m_newEachDownloadLen = atoi(str.GetData())*1024;
- }else{
- m_newEachDownloadLen = 16*1024;//设置默认最小值
- }
-
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("init read CenterSetting.ini NewEachDownloadLen=%d K", m_newEachDownloadLen);
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini NewEachDownloadLen error");
- return rc;
- }
- //加载是否打印http通讯日志
- int printlogInt =0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "PrintLog", printlogInt);
- if(rc==Error_Succeed){
- if(printlogInt==0){
- m_PrintHttpLog = false;
- }else{
- m_PrintHttpLog = true;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("init read CenterSetting.ini PrintLog=%d",printlogInt);
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini PrintLog error");
- return rc;
- }
- int startFlagInt =0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "StartFlag", startFlagInt);
- if(rc==Error_Succeed){
- if(startFlagInt==0){
- m_startFlag = false;
- }else{
- m_startFlag = true;
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("init read CenterSetting.ini StartFlag=%d",startFlagInt);
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini StartFlag error");
- return rc;
- }
- int stopSetFirewallInt = 0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "stopSetFirewall", stopSetFirewallInt);
- if (rc == Error_Succeed) {
- if (stopSetFirewallInt == 0) {
- m_stopSetFirewall = false;
- }
- else {
- m_stopSetFirewall = true;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read CenterSetting.ini stopSetFirewall=%d", stopSetFirewallInt);
- }
- else {
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini stopSetFirewall error");
- return rc;
- }
- int queryNewTaskInterval = 0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "queryNewTaskInterval", queryNewTaskInterval);
- if (rc == Error_Succeed) {
- if (queryNewTaskInterval != 0) {
- if (queryNewTaskInterval < 10) {
- m_queryNewTaskInterval = 10;
- }
- else {
- m_queryNewTaskInterval = queryNewTaskInterval;
- }
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read CenterSetting.ini queryNewTaskInterval=%d", m_queryNewTaskInterval);
- }
- else {
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini queryNewTaskInterval error");
- return rc;
- }
- int installStopCopyDep = 0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "installStopCopyDep", installStopCopyDep);
- if (rc == Error_Succeed) {
- if (installStopCopyDep == 1) {
- m_installStopCopyDep = true;//配置1时停止拷贝
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("init read CenterSetting.ini installStopCopyDep=%d", m_installStopCopyDep);
- }
- else {
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini installStopCopyDep error");
- return rc;
- }
- //加载扫描hash配置文件列表
- rc = spConfig->ReadConfigValue("UpgradeManager", "relativeDir", str);
- if(rc==Error_Succeed){
- m_hashScanSet.relativeDir = str;
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("init read CenterSetting.ini relativeDir=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini relativeDir error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "absoluteDir", str);
- if(rc==Error_Succeed){
- m_hashScanSet.absoluteDir = str;
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("init read CenterSetting.ini absoluteDir=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini absoluteDir error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "currVerDir", str);
- if(rc==Error_Succeed){
- m_hashScanSet.currVerDir = str;
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("init read CenterSetting.ini currVerDir=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini currVerDir error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "blackFile", str);
- if(rc==Error_Succeed){
- m_hashScanSet.blackFile = str;
- CAutoArray<CSimpleStringA> arr = str.Split('|');
- for(int i=0; i< arr.GetCount(); i++)
- {
- m_FileBlacklist.push_back(arr[i]);
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("init read CenterSetting.ini blackFile=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini blackFile error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "blackDir", str);
- if(rc==Error_Succeed){
- m_hashScanSet.blackDir = str;
- CAutoArray<CSimpleStringA> arr = str.Split('|');
- for(int i=0; i< arr.GetCount(); i++)
- {
- m_DirBlacklist.push_back(arr[i]);
- }
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("init read CenterSetting.ini blackDir=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini blackDir error");
- return rc;
- }
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini error");
- return rc;
- }
- return Error_Succeed;
- }
- //TODO: CrossPlaform 如果是获取文件大小,建议直接采用 fileutil中的 ReadFileSize [Gifur@2025730]
- bool CUpgradeTaskFSM::GetFileLength(const char* filePath,long &fileLen)
- {
- FILE* file = fopen(filePath, "rb");
- if (file!=NULL)
- {
- #ifdef RVC_OS_WIN
- fileLen = filelength(fileno(file));
- fclose(file);
- return true;
- #else
- if (fseek(file, 0, SEEK_END)!=0) {
- Dbg("GetFileLength fseek is error,%s",strerror(errno));
- fclose(file);
- fileLen = 0;
- return false;
- }
- fileLen = ftell(file); ///求出当前文件指针距离文件开始的字节数
- if (fileLen == -1) {
- Dbg("GetFileLength ftell is error,%s", strerror(errno));
- fclose(file);
- fileLen = 0;
- return false;
- }
- else {
- fclose(file);
- return true;
- }
- #endif
- } else{
- fileLen = 0;
- return false;
- }
-
- return true;
- }
- ErrorCodeEnum CUpgradeTaskFSM::GetSM3List(CSimpleStringA &strSM3List)
- {
- if (!m_fileSM3List.IsNullOrEmpty())
- {
- strSM3List = m_fileSM3List;
- return Error_Succeed;
- }
- m_fileSM3Map.clear();//生成文件hash列表前先清空
-
- //根据配置项开始扫描文件和计算hash
- ErrorCodeEnum rc = Error_Succeed ;
- if(!m_hashScanSet.absoluteDir.IsNullOrEmpty()){
- //绝对路径扫描
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("GetSM3List scan absoluteDir=%s",m_hashScanSet.absoluteDir.GetData());
- rc = ScanSM3ByType(1,m_hashScanSet.absoluteDir);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan absoluteDir is fail");
- return rc;
- }
- }
- if(!m_hashScanSet.relativeDir.IsNullOrEmpty()){
- //相对路径扫描
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("GetSM3List scan relativeDir=%s",m_hashScanSet.relativeDir.GetData());
- ScanSM3ByType(2,m_hashScanSet.relativeDir);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan relativeDir is fail");
- return rc;
- }
- }
- if(!m_hashScanSet.currVerDir.IsNullOrEmpty()){
- //当前版本扫描
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("GetSM3List scan currVerDir=%s",m_hashScanSet.currVerDir.GetData());
- ScanSM3ByType(3,m_hashScanSet.currVerDir);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan currVerDir is fail");
- return rc;
- }
- }
- if(m_iBlackFileCount>50){
- LogWarn(Severity_Low, rc, WARN_BLACK_FILE_SUM, CSimpleStringA::Format("get MD5List black file count=%d",m_iBlackFileCount));
- }
- m_iBlackFileCount=0;
- for(auto it=m_fileSM3Map.begin(); it!=m_fileSM3Map.end(); it++)
- {
- strSM3List += it->first;
- strSM3List += ",";
- strSM3List += it->second;
- strSM3List += ";";
- }
- m_fileSM3List = strSM3List;
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::ScanSM3ByType(int type,CSimpleStringA pathFilter)
- {
- if(!pathFilter.IsNullOrEmpty()){
- CSimpleStringA rootPath;//根路径
- CSimpleStringA replacePath;//替换路径
- CSimpleStringA currPath;//当前版本路径
- CSimpleStringA tempPath ="";
- ErrorCodeEnum Error =m_pEntity->GetFunction()->GetPath("Root",tempPath);//例如:C:\Run /opt/Run
- if(Error_Succeed == Error){
- if(!tempPath.IsNullOrEmpty()){
- string runPathStr = tempPath.GetData();
- int pos = runPathStr.find_last_of(SPLIT_SLASH);
- rootPath = runPathStr.substr(0,pos).c_str();
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get Root path is null");
- return Error_Null;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get Root path is error");
- return Error;
- }
- CSimpleStringA tempCurrPath = "";
- Error =m_pEntity->GetFunction()->GetPath("Base",tempCurrPath);//例如:C:\Run\version\4.8.1.1 /opt/Run/version/4.8.1.1
- if(Error_Succeed == Error){
- if(!tempCurrPath.IsNullOrEmpty()){
- currPath = tempCurrPath;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get currVer path is null");
- return Error_Null;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get currVer path is error");
- return Error;
- }
- //路径扫描
- CAutoArray<CSimpleStringA> copyList = pathFilter.Split('|');
- for(int i=0; i<copyList.GetCount(); i++)
- {
- CSimpleStringA file = copyList[i];
- #ifdef RVC_OS_WIN
- #else
- //UOS把路径改为反斜杠
- string replaceStr = file.GetData();
- std::replace(replaceStr.begin(), replaceStr.end(), '\\', '/');
- file = replaceStr.c_str();
- #endif
- if(file.IsNullOrEmpty()){
- continue;
- }else{
- //构造扫描的绝对路径
- CSimpleStringA scanFilter = "";
- CSimpleStringA replaceDir = "";
- if(type==1){
- //绝对路径
- scanFilter = file;
- replaceDir = GetFileDirectory(file.GetData());
- }else if(type==2){
- //相对路径
- scanFilter = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),file.GetData());
- replaceDir = GetFileDirectory(file.GetData());
- }else if(type==3){
- //当前版本路径:特殊处理下替换路径为Run\version\4.8.1.1
- scanFilter = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",currPath.GetData(),file.GetData());
- CSimpleStringA temp = scanFilter.SubString(rootPath.GetLength()+1,scanFilter.GetLength()-(rootPath.GetLength()+1));
- replaceDir = GetFileDirectory(temp.GetData());
- }
- //替换路径前缀
- ErrorCodeEnum ret = NewSM3Folder(scanFilter,replaceDir);
- if(ret!=Error_Succeed){
- return ret;
- }
- }
- }
- }
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::NewSM3Folder(CSimpleStringA scanFilter,CSimpleStringA replaceDir)
- {
- if(scanFilter.IsNullOrEmpty()){
- return Error_Succeed;
- }
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("scan file scanFilter is %s",scanFilter.GetData());
- //通配符
- if(scanFilter.IndexOf("*")>0){
- //找到要扫描的文件夹
- CSimpleStringA strFileDir = GetFileDirectory(scanFilter.GetData());
- //过滤通配条件
- CSimpleStringA strFileFilter = _GetFileName(scanFilter.GetData());
- list<CSimpleStringA> fileList;
- //获取所有根文件夹下的文件相对路径:如mod\test.dll
- RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
- for(auto it = fileList.begin(); it != fileList.end(); it++)
- {
-
- CSimpleStringA tempFile = *it;
- if (IsFileMatch(strFileFilter, _GetFileName(tempFile.GetData())))
- {
- CSimpleStringA tempFullName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",strFileDir.GetData(),tempFile.GetData());
- CSimpleStringA tempFileName = _GetFileName(tempFile.GetData());
- CSimpleStringA tempFileDir = GetFileDirectory(tempFile.GetData());
- //整个黑名单文件过滤
- bool isBlackFile = false;
- list<CSimpleStringA>::iterator itorFile = m_FileBlacklist.begin();
- while(itorFile!=m_FileBlacklist.end())
- {
- CSimpleStringA fileBlack = *itorFile;
- //if(tempFileName.IsEndWith(fileBlack.GetData(),true)){
- // isBlackFile=true;
- // break;
- //}
- if(IsFileMatch(fileBlack.GetData(),tempFileName.GetData())){
- isBlackFile=true;
- break;
- }
- itorFile++;
- }
- if(isBlackFile){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackFile Filter don't add to md5 list, file = [%s]", tempFullName.GetData());
- m_iBlackFileCount++;
- continue;
- }
- //整个黑名单文件夹过滤
- bool isBlackDir = false;
- list<CSimpleStringA>::iterator itorDir = m_DirBlacklist.begin();
- while(itorDir!=m_DirBlacklist.end())
- {
- CSimpleStringA dirBlack = *itorDir;
- if(tempFileDir.IndexOf(dirBlack.GetData())>0){
- isBlackDir=true;
- break;
- }
- itorDir++;
- }
- if(isBlackDir){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackDir Filter don't add to md5 list, dir = [%s]", tempFullName.GetData());
- continue;
- }
- //计算hash值,加入到hash列表
- CSimpleStringA strMD5Val;
- ErrorCodeEnum rErrcode = SM3FileToStr(tempFullName, strMD5Val,false);
- if (Error_Succeed != rErrcode)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("%s get sm3 fail ,error:%d", tempFullName.GetData(), (int)rErrcode);
- return rErrcode;
- }
- CSimpleStringA relativePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",replaceDir.GetData(),tempFile.GetData());
- //Dbg("scan file succ [%s]",relativePath.GetData());
- m_fileSM3Map[relativePath] = strMD5Val;
- Sleep(100);//时间片
- }
- }
- }else{
- if(ExistsFileA(scanFilter.GetData())){
- //整个黑名单文件过滤
- bool isBlackFile = false;
- CSimpleStringA tempFileName = _GetFileName(scanFilter.GetData());//文件名称
- CSimpleStringA tempFileDir = GetFileDirectory(scanFilter.GetData());//文件夹名称
- list<CSimpleStringA>::iterator itorFile = m_FileBlacklist.begin();
- while(itorFile!=m_FileBlacklist.end())
- {
- CSimpleStringA fileBlack = *itorFile;
- //if(scanFilter.IsEndWith(fileBlack.GetData(),true)){
- // isBlackFile=true;
- // break;
- //}
- if(IsFileMatch(fileBlack.GetData(),tempFileName.GetData())){
- isBlackFile=true;
- break;
- }
- itorFile++;
- }
- if(isBlackFile){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackFile Filter don't add to md5 list, file = [%s]", scanFilter.GetData());
- m_iBlackFileCount++;
- }
- //整个黑名单文件夹过滤
- bool isBlackDir = false;
- list<CSimpleStringA>::iterator itorDir = m_DirBlacklist.begin();
- while(itorDir!=m_DirBlacklist.end())
- {
- CSimpleStringA dirBlack = *itorDir;
- if(tempFileDir.IndexOf(dirBlack.GetData())>0){
- isBlackDir=true;
- break;
- }
- itorDir++;
- }
- if(isBlackDir){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackDir Filter don't add to md5 list, dir = [%s]", scanFilter.GetData());
- }
- if(!isBlackDir&&!isBlackFile){
- //加入hash列表
- CSimpleStringA strMD5Val;
- ErrorCodeEnum rErrcode = SM3FileToStr(scanFilter, strMD5Val,false);
- if (Error_Succeed != rErrcode)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("%s get sm3 fail ,error:%d", scanFilter.GetData(), (int)rErrcode);
- return rErrcode;
- }
- CSimpleStringA tempFileName = _GetFileName(scanFilter.GetData());
- CSimpleStringA relativePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",replaceDir.GetData(),tempFileName.GetData());
- //Dbg("scan file succ [%s]",relativePath.GetData());
- #ifdef RVC_OS_WIN
- #else
- Sleep(100);//加入时间碎片
- #endif
- m_fileSM3Map[relativePath] = strMD5Val;
- }
- }
- }
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::RollBackVersionCheck(string& failReason, CSimpleStringA& strErrMsg)
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin RollBackVersionCheck");
- //获取新版本号
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer", rootVerPath);//获取version根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RollBackVersionCheck fail , get RootVer path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "RollBackVersionCheck: get RootVer path is fail");
- failReason = "C";
- strErrMsg = "RollBackVersionCheck fail , get RootVer path is fail";
- return Error_Bug;
- }
- CSimpleStringA strRollbackVersion = m_currentTask.pack_version;
- CVersion curVer = m_currentVersion;//当前版本号
- // 指定版本
- DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
- int n = sscanf(strRollbackVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
- if (n != 4)
- {
- strErrMsg = CSimpleStringA::Format("指定回退版本号无效(%s)", strRollbackVersion.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("specified Rollback version is invalid: [%s]", strRollbackVersion.GetData()).GetData());
- failReason = "C";
- strErrMsg = CSimpleStringA::Format("specified Rollback version is invalid: [%s]", strRollbackVersion.GetData());
- return Error_Bug;
- }
- else {
- m_currentTask.NewVersion = strRollbackVersion;//赋值回退版本号给内存变量
- }
-
- if (curVer.ToString() == strRollbackVersion) {
- //版本号相同,
- strErrMsg = CSimpleStringA::Format("指定回退版本号与当前版本相同,无效(配置:%s, 当前:%s)", strRollbackVersion.GetData(), curVer.ToString().GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- else if (dwMajor > curVer.GetMajor()
- || (dwMajor == curVer.GetMajor() && dwMinor > curVer.GetMinor())
- || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision > curVer.GetRevision())
- || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision == curVer.GetRevision() && dwBuild > curVer.GetBuild())) {
- //升级版本大于当前版本
- strErrMsg = CSimpleStringA::Format("指定回退版本号大于当前版本号(配置:%s,当前:%s)", strRollbackVersion.GetData(), curVer.ToString().GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- //回退版本是否存在
- CSimpleStringA strRollbackVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.NewVersion.GetData());
- if (!ExistsDirA(strRollbackVerPath.GetData())) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("RollBackVersionCheck fail, strRollbackVerPath =%s is not exist,fail", strRollbackVerPath.GetData()).GetData());
- strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", strRollbackVersion.GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- return Error_Succeed;
- }
- void CUpgradeTaskFSM::judgeTaskClass()
- {
- m_TempDepUpgradeFlag = false;//每次安装前初始化。
- //临时方案判定是适配器升级还是应用升级
- if (isTerminalInstall()) {
- //安装时判断
- if (m_currentTask.pack_name.IndexOf("adapter") != -1) {
- m_TempDepUpgradeFlag = true;
- }
- }
- else {
- //非安装时判断:判断只有一条拷贝dep路径的策略
- if (!m_currentTask.install_step.empty()) {
- int iCount = m_currentTask.install_step.size();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d", iCount);
- if (iCount == 1) {
- CInstallStep* tmp = m_currentTask.install_step.front();
- if (tmp->cmdType == "Copy") {
- if (tmp->srcPathType == "3") {
- CSimpleStringA depStr = "";
- depStr.Append(SPLIT_SLASH_STR).Append("dep").Append(SPLIT_SLASH_STR); //win :\dep\ uos: /dep/
- if (tmp->srcPath.IndexOf(depStr.GetData()) != -1) {
- m_TempDepUpgradeFlag = true;
- }
- }
- }
- }
- }
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::judgeRollbackTaskClass(CSimpleStringA verDirName, string& failReason, CSimpleStringA& strErrMsg)
- {
- //搜索终端应用目录,适配器应用目录,
- CSimpleStringA depPathStr(true);
- CSimpleStringA verPathStr(true);
- ErrorCodeEnum Err = GetEntityBase()->GetFunction()->GetPath("DepBase", depPathStr);
- if (Err != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("judgeRollbackTaskClass fail , get DepBase path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "judgeRollbackTaskClass: get DepBase path is fail");
- failReason = "C";
- strErrMsg = "judgeRollbackTaskClass fail , get DepBase path is fail";
- return Error_Bug;
- }
- Err = m_pEntity->GetFunction()->GetPath("RootVer", verPathStr);
- if (Err != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("judgeRollbackTaskClass fail , get RootVer path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "judgeRollbackTaskClass: get RootVer path is fail");
- failReason = "C";
- strErrMsg = "judgeRollbackTaskClass fail , get RootVer path is fail";
- return Error_Bug;
- }
- CSimpleStringA strDestDir = "";
- if (DirIsExist(verPathStr.GetData(), verDirName.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("app version dir find is ok,dir=%s", verDirName.GetData());
- m_TempDepUpgradeFlag = false;//应用版本
- return Error_Succeed;
- }
- else if (DirIsExist(depPathStr.GetData(), verDirName.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("dep version dir find is ok, dir=%s", verDirName.GetData());
- m_TempDepUpgradeFlag = true;//适配器版本
- return Error_Succeed;
- }
- else {
- CSimpleStringA errStr = CSimpleStringA::Format("judgeRollbackTaskClass fail, RollbackVerRootPath =[%s|%s] not find version dir [%s],fail", verPathStr.GetData(), depPathStr.GetData(), verDirName.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, errStr.GetData());
- strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", verDirName.GetData());
- failReason = "X";
- return Error_Unexpect;//不存在
- }
- }
- bool CUpgradeTaskFSM::DirIsExist(const char* scanPath, const char* dirName)
- {
- CSimpleStringA strDestDir = "";
- if (dirName == NULL||scanPath==NULL) {
- return false;
- }
- auto subdirs = fileutil_get_sub_dirs(scanPath);
- if (subdirs != NULL)
- {
- bool isMatch = false;
- for (int i = 0; i < subdirs->nelts; ++i)
- {
- const char* dir = ARRAY_IDX(subdirs, i, char*);
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("dir=%s,dirName=%s", dir, dirName);
- CSimpleStringA dirNameStr = dirName;
- if (dirNameStr.Compare(_GetFileName(dir))==0) {
- isMatch = true;
- break;
- }
- }
- toolkit_array_free2(subdirs);
- return isMatch;
- }
- else {
- return false;
- }
- }
- int CUpgradeTaskFSM::ExecDepInstall(CSimpleStringA& strErrMsg)
- {
- if (!isTerminalInstall()) {
- //升级
- if (!m_currentTask.pack_version.IsNullOrEmpty()) {
- CSimpleStringA strUpgradeDepVersion = m_currentTask.pack_version;
- CSimpleStringA latterDepVersion;//要更新到的版本号
- CSimpleStringA curVer = m_currentDepVersion;//当前版本号
- // 指定版本
- latterDepVersion = strUpgradeDepVersion.GetData();
- if (curVer == strUpgradeDepVersion) {
- //版本号相同
- strErrMsg = CSimpleStringA::Format("指定升级适配器版本号与当前版本相同,无效(配置:%s, 当前:%s)", strUpgradeDepVersion.GetData(), curVer.GetData());
- return 0;
- }
- CSimpleStringA strErrInfo = "";
- //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateNewDepVersion,version[%s],pack[%s]", strUpgradeDepVersion.GetData(), m_currentTask.pack_name.GetData());
- ErrorCodeEnum rc = CreateNewDepVersion(latterDepVersion, strErrInfo);
- if (rc != Error_Succeed)
- {
- strErrMsg = CSimpleStringA::Format("CreateNewDepVersion fail:%s", strErrInfo.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewDepVersion,version[%s] fail:%s", strUpgradeDepVersion.GetData(), strErrInfo.GetData());
- //清理临时版本文件夹
- ClearUpgradeFailDepVersion(latterDepVersion);
- return 0;
- }
- else {
- m_currentTask.depNewVersion = strUpgradeDepVersion;//赋值升级适配器版本号给内存变量
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewDepVersion,version[%s] succ , pack[%s]", strUpgradeDepVersion.GetData(), m_currentTask.pack_name.GetData());
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDepInstall fail ,pack_version is null");
- strErrMsg = CSimpleStringA::Format("ExecDepInstall fail ,pack_version is null");
- return 0;
- }
- }
- else {
- //新安装,无值则填写默认初始版本号
- if (m_currentTask.pack_version.IsNullOrEmpty()) {
- m_currentTask.pack_version = "0.0.0.1";//新安装,默认初始适配器版本
- m_currentTask.depNewVersion = "0.0.0.1";
- }
- else {
- m_currentTask.depNewVersion = m_currentTask.pack_version.GetData();
- }
- if (m_installStopCopyDep) {
- //不需要拷贝dep公共库
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("installStopCopyDep is %d , No need to copy common Dep dir", m_installStopCopyDep);
- }
- else {
- //兼容拷贝dep公共库
- CSimpleStringA strErrInfo = "";
- //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateInstallDepVersion,version[%s],pack[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.pack_name.GetData());
- ErrorCodeEnum rc = CreateInstallDepVersion(m_currentTask.depNewVersion, strErrInfo);
- if (rc != Error_Succeed)
- {
- strErrMsg = CSimpleStringA::Format("CreateInstallDepVersion fail:%s", strErrInfo.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateInstallDepVersion,version[%s] fail:%s", m_currentTask.depNewVersion.GetData(), strErrInfo.GetData());
- //清理临时版本文件夹
- ClearUpgradeFailDepVersion(m_currentTask.depNewVersion);
- return 0;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateInstallDepVersion,version[%s] succ , pack[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.pack_name.GetData());
- }
- }
- }
- //循环执行安装命令
- int iRet = 1;//默认是成功
- if (!m_currentTask.install_step.empty()) {
- int iCount = m_currentTask.install_step.size();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install Dep cmd size = %d", iCount);
- for (int j = 0; j < iCount; j++) {
- CInstallStep* tmp = m_currentTask.install_step.front();
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====begin Dep cmd=[%s]=====", tmp->cmdType.GetData());
- //开始处理具体命令
- if (tmp->cmdType == "Delete") {
- bool ret = ExecDepDeleteCmd(strErrMsg, tmp);
- if (!ret) {
- //报错才判断
- if (tmp->cmdFail == 0) {
- iRet = 0;
- break;//出错直接退出
- }
- else if (tmp->cmdFail == 1) {
- //继续
- }
- else {
- iRet = 0;
- break;//其他值也退出
- }
- }
- }
- else if (tmp->cmdType == "Copy") {
- bool ret = ExecDepCpoyCmd(strErrMsg, tmp);
- if (!ret) {
- //报错才判断
- if (tmp->cmdFail == 0) {
- iRet = 0;
- break;//出错直接退出
- }
- else if (tmp->cmdFail == 1) {
- //继续
- }
- else {
- iRet = 0;
- break;//其他值也退出
- }
- }
- }
- else if (tmp->cmdType == "Run") {
- int retInt = ExecDepRunCmd(strErrMsg, tmp);
- if (retInt == 0 || retInt == -1) {
- //报错才判断
- if (tmp->cmdFail == 0) {
- iRet = retInt;//会有0,-1值
- break;//出错直接退出,并返回体系外结果
- }
- else if (tmp->cmdFail == 1) {
- //继续
- }
- else {
- iRet = 0;
- break;//其他值也退出
- }
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cmd=[%s] is invalid", tmp->cmdType.GetData());
- iRet = 0;
- break;//命令无效直接退出
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====end Dep cmd=[%s]=====", tmp->cmdType.GetData());
- m_currentTask.install_step.pop();//去除元素
- delete tmp;//删除内存
- }
- }
- return iRet;//返回处理结果
- }
- ErrorCodeEnum CUpgradeTaskFSM::CreateNewDepVersion(CSimpleStringA NewSoftwareVersion, CSimpleStringA& strErrInfo)
- {
- // 创建新适配器版本
- CSimpleStringA rootDepPath;
- ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("DepBase", rootDepPath);//适配器根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail , get DepBase path is fail");
- strErrInfo = CSimpleStringA::Format("Create new dep version fail , get DepBase path is fail");
- return Error_Bug;
- }
- CSimpleStringA strCurDepPath;
- rc = m_pEntity->GetFunction()->GetPath("Dep", strCurDepPath);//获取当前适配器根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail , get Dep path is fail");
- strErrInfo = CSimpleStringA::Format("Create new dep version fail , get Dep path is fail");
- return Error_Bug;
- }
- //新路径
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootDepPath.GetData(), NewSoftwareVersion.GetData());
- if (m_currentDepVersion == NewSoftwareVersion)
- {
- 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());
- strErrInfo = CSimpleStringA::Format("new ver [%s] equals current ver [%s]", NewSoftwareVersion.GetData(), m_currentDepVersion.GetData());
- return Error_Bug;
- }
- if (ExistsDirA(strNewVerPath.GetData()))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new version dir [%s] already exist, delete it", strNewVerPath.GetData());
- if (!RemoveDirRecursiveA(strNewVerPath.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail, delete already exist new dep version is fail:%d", GetLastError());
- strErrInfo = CSimpleStringA::Format("Create new dep version fail, delete already exist new dep version is fail:%d", (int)GetLastError());
- return Error_Bug;
- }
- }
- if (!CreateDirA(strNewVerPath.GetData(), TRUE))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version dir fail: %d", GetLastError());
- strErrInfo = CSimpleStringA::Format("create new dep version dir fail: %d", (int)GetLastError());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create new dep version dir succ, dir = %s", strNewVerPath.GetData());
- //增加错误信息字段,回传给上层应用
- CSimpleStringA strErrMsg = "";
- CSimpleStringA strSource = CSimpleStringA::Format("%s", strCurDepPath.GetData());
- CSimpleStringA strDest = CSimpleStringA::Format("%s", strNewVerPath.GetData());
- if (!RecursiveCopyDir(strSource, strDest, strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
- strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::CreateInstallDepVersion(CSimpleStringA NewSoftwareVersion, CSimpleStringA& strErrInfo)
- {
- LOG_FUNCTION();
- CSimpleStringA strCurVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Base", strCurVerPath);//获取当前应用version路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new Install dep version fail , get Base path is fail");
- strErrInfo = CSimpleStringA::Format("Create new Install dep version fail , get Base path is fail");
- return Error_Bug;
- }
-
- CSimpleStringA strCurrDepPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strCurVerPath.GetData());
- if (ExistsDirA(strCurrDepPath.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new install common dep dir is exist, begin copy dir = %s", strCurrDepPath.GetData());
- //存在则拷贝公共库dep文件
- CSimpleStringA tempPath;
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\ /opt/Run/dep/
- if (Error_Succeed == Error) {
- CSimpleStringA strNewDepPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), NewSoftwareVersion.GetData());
- CSimpleStringA strErrMsg = "";
- if (!RecursiveCopyDir(strCurrDepPath.GetData(), strNewDepPath.GetData(), strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
- strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
- return Error_Succeed;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new Install dep version fail ,get DepBase path is fail");
- strErrInfo = CSimpleStringA::Format("Create new Install dep version fail , get DepBase path is fail");
- return Error_Bug;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new install common dep dir is not exist, default return true,dir=%s", strCurrDepPath.GetData());
- return Error_Succeed;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::ClearUpgradeFailDepVersion(CSimpleStringA NewSoftwareVersion)
- {
- CSimpleStringA rootDepPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootDepPath);//适配器根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion fail , get DepBase path is fail");
- return Error_Bug;
- }
- //新路径
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootDepPath.GetData(), NewSoftwareVersion.GetData());
- if (ExistsDirA(strNewVerPath.GetData()))
- {
- if (!RemoveDirRecursiveA(strNewVerPath.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), (int)GetLastError());
- return Error_Bug;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion succ, delete temp Version [%s] ", strNewVerPath.GetData());
- return Error_Succeed;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion succ, delete temp Version [%s] is not exist ", strNewVerPath.GetData());
- return Error_Succeed;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::UpgradeDepToNewVersion()
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin UpgradeToDepNewVersion");
- //获取新版本号
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- 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());
- 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());
- return Error_Unexpect;//这种情况有问题,需要清除此任务
- }
- else {
- ErrorCodeEnum ec = Error_Exception;
- if (isTerminalInstall()) {
- //安装需要刷新适配器路径到框架。
- ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(m_currentTask.depNewVersion, true);
- }
- else {
- ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(m_currentTask.depNewVersion, false);
- }
- if (ec != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpgradeDepToNewVersion fail, RewriteDepVersion version %s return %s", m_currentTask.depNewVersion.GetData(),SpStrError(ec));
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion: get RootVer path is fail", m_currentTask.depNewVersion.GetData(), SpStrError(ec)));
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("write dep active.txt succ, version[%s]", m_currentTask.depNewVersion.GetData());
- }
- return ec;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SwitchUpgradeDepNow()
- {
- //根据重启策略类型去重启
- //重启策略类型(0:不启动 1:重启框架 2:重启系统)
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin SwitchUpgradeDepNow");
- if (m_currentTask.reboot_type == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("reboot_type = 0 , no need Switch restart, taskID=[%s] ", m_currentTask.upgradeTaskId.GetData());
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- else if (m_currentTask.reboot_type == 1) {
- if (m_currentTask.task_type.Compare("U") == 0) {
- //适配器版本升级
- LogEvent(Severity_Middle, Event_DeviceAdapterUpgrade_Framework_Restart,
- CSimpleStringA::Format("upgrade to new dep version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else if (m_currentTask.task_type.Compare("R") == 0) {
- //适配器版本回退
- LogEvent(Severity_Middle, Event_DeviceAdapterRollBack_Framework_Restart,
- CSimpleStringA::Format("rollback to old dep version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- }
- else if (m_currentTask.reboot_type == 2) {
- if (m_currentTask.task_type.Compare("U") == 0) {
- LogEvent(Severity_Middle, Event_DeviceAdapterUpgrade_OS_Restart,
- CSimpleStringA::Format("upgrade to new dep version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else {
- LogEvent(Severity_Middle, Event_DeviceAdapterRollBack_OS_Restart,
- CSimpleStringA::Format("rollback to old dep version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- }
- else {
- 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());
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- // 强制刷新日志
- m_pEntity->GetFunction()->FlushLogFile();
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::RollBackDepVersionCheck(string& failReason, CSimpleStringA& strErrMsg)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin RollBackDepVersionCheck");
- //获取新版本号
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootVerPath);//获取version根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RollBackDepVersionCheck fail , get DepBase path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "RollBackDepVersionCheck: get DepBase path is fail");
- failReason = "C";
- strErrMsg = "RollBackDepVersionCheck fail , get DepBase path is fail";
- return Error_Bug;
- }
- CSimpleStringA strRollbackVersion = m_currentTask.pack_version;
- CSimpleStringA curDepVer = m_currentDepVersion;//当前版本号
- // 指定版本
- m_currentTask.depNewVersion = strRollbackVersion;//赋值适配器回退版本号给内存变量
- if (curDepVer == strRollbackVersion) {
- //版本号相同,
- strErrMsg = CSimpleStringA::Format("指定回退版本号与当前版本相同,无效(配置:%s, 当前:%s)", strRollbackVersion.GetData(), curDepVer.GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- //回退版本是否存在
- CSimpleStringA strRollbackVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.depNewVersion.GetData());
- if (!ExistsDirA(strRollbackVerPath.GetData())) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("RollBackVersionCheck fail, strRollbackVerPath =%s is not exist,fail", strRollbackVerPath.GetData()).GetData());
- strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", strRollbackVersion.GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::RollBackToHistoryDepVersion(CSimpleStringA historyDepVersion)
- {
- //判断是否为空
- if (historyDepVersion.IsNullOrEmpty())
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryDepVersion fail , historyDepVersion is null");
- return Error_Param;
- }
- // 判断目标版本是否等于当前版本
- if (historyDepVersion == m_currentDepVersion) {
- 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());
- return Error_Param;
- }
- // 检查对应文件夹是否存在
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootVerPath);//获取version根路径
- if (rc != Error_Succeed) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryDepVersion fail , get DepBase path is fail");
- return Error_Bug;
- }
- CSimpleStringA strHisVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), historyDepVersion.GetData());
- if (!ExistsDirA(strHisVerPath.GetData()))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryDepVersion fail, history version dir [%s] not exists", strHisVerPath.GetData()).GetData());
- return Error_NotExist;
- }
- ErrorCodeEnum ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(historyDepVersion, false);
- if (ec != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackToHistoryDepVersion fail, RewriteDepVersion version %s return %s", strHisVerPath.GetData(), SpStrError(ec));
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryDepVersion fail, RewriteDepVersion version %s return %s", strHisVerPath.GetData(), SpStrError(ec)));
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set rollback to history dep version [%s] succeed", historyDepVersion.GetData());
- }
- return ec;
- }
- int CUpgradeTaskFSM::ExecDepRunCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
- {
- CSimpleStringA destPath;//目的路径
- if (ins->dstPathType == "0") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(1, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "1") {
- destPath = ins->dstPath;//绝对路径
- }
- else if (ins->dstPathType == "2") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(2, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "3") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(3, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "4") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(4, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级包相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 4 is fail");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPathType is invalid %s", ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPathType is invalid %s", ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPath is %s", destPath.GetData());
- // ToRun=install.bat
- if (ExistsFileA(destPath.GetData()))
- {
- ostuile_void_ptr store = osutil_sure_redirect_32sys_in_wow64();
- string sysPathStr = destPath.GetData();
- CSimpleStringA err = "";
- int ret = system_on(sysPathStr, true, err);
- osutil_reset_redirect_32sys_in_wow64(&store);
- if (ret != 0) {
- //程序执行异常,结果未知
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown ,err=%s", err.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ,err=%s", err.GetData());
- return -1;//未知结果返回
- }
- else {
- //进一步看返回结果文件判断是否成功
- CSimpleStringA strUnzipPath = GetFileDirectory(destPath.GetData());
- CSimpleStringA strResultLog = strUnzipPath + SPLIT_SLASH_STR + "result.log";//结果文件
- CSimpleStringA eErrorCode = "";
- //获取结果文件
- if (!GetSysUpgradeResult(strResultLog, eErrorCode, strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, get result from result.log fail, %s", strErrMsg.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail ,get result from result.log fail, %s", strErrMsg.GetData());
- return 0;//失败
- }
- if (eErrorCode == "0")
- {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is succ,[%s] ", destPath.GetData());
- return 1;//成功
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
- return 0;//失败
- }
- }
- }
- else
- {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, run file [%s] is not Exist", destPath.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, run file [%s] is not Exist", destPath.GetData());
- return 0;//失败
- }
- }
- bool CUpgradeTaskFSM::ExecDepDeleteCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
- {
- //只删除同一层目录下的文件和文件夹
- CSimpleStringA destPath;//目的路径+通配符
- if (ins->dstPathType == "0") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(1, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "1") {
- destPath = ins->dstPath;//绝对路径
- }
- else if (ins->dstPathType == "2") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(2, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "3") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(3, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPathType is invalid %s", ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPathType is invalid %s", ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPath is %s", destPath.GetData());
- if (destPath.IndexOf("*") > 0) {
- CSimpleStringA strFileFilter = _GetFileName(destPath);
- CSimpleStringA strDestDir = destPath.SubString(0, destPath.GetLength() - strFileFilter.GetLength() - 1);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match filter name [%s] in dir [%s]", strFileFilter.GetData(), strDestDir.GetData());
- // 删除所有匹配文件
- bool bRet = true;
- auto arr = fileutil_get_sub_files(strDestDir.GetData());
- if (arr != NULL)
- {
- for (int i = 0; i < arr->nelts; ++i)
- {
- char* file = ARRAY_IDX(arr, i, char*);
- if (IsFileMatch(strFileFilter, _GetFileName(file)))
- {
- if (RemoveFileA(file)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", file);
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", file);
- strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", file);
- bRet = false;
- break;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match file: [%s]", file);
- }
- }
- toolkit_array_free2(arr);
- if (!bRet) {
- return bRet;
- }
- }
- // 删除所有匹配子目录
- auto subdirs = fileutil_get_sub_dirs(strDestDir.GetData());
- if (subdirs != NULL)
- {
- for (int i = 0; i < subdirs->nelts; ++i)
- {
- const char* dir = ARRAY_IDX(subdirs, i, char*);
- if (IsFileMatch(strFileFilter, _GetFileName(dir)))
- {
- if (RemoveDirRecursive(dir)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", dir);
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", dir);
- strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", dir);
- bRet = false;
- break;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match dir: [%s]", dir);
- }
- }
- toolkit_array_free2(subdirs);
- if (!bRet) {
- return bRet;
- }
- }
- return bRet;
- }
- else {
- //直接删除文件
- bool bRet = true;
- if (ExistsFileA(destPath.GetData()))
- {
- if (RemoveFileA(destPath.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", destPath.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", destPath.GetData());
- strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", destPath.GetData());
- bRet = false;
- }
- return bRet;
- }
- else if (ExistsDirA(destPath.GetData()))
- {
- if (RemoveDirRecursiveA(destPath.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", destPath.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", destPath.GetData());
- strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", destPath.GetData());
- bRet = false;
- }
- return bRet;
- }
- else
- {
- //指定文件不再则忽略删除此文件
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file [%s] not exists,ignore delete file", destPath.GetData());
- return bRet;
- }
- }
- }
- bool CUpgradeTaskFSM::ExecDepCpoyCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
- {
- CSimpleStringA sourcePath;//路径+通配符
- if (ins->srcPathType == "0") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(1, rootPath)) {
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 1 is fail");
- return false;
- }
- }
- else if (ins->srcPathType == "1") {
- sourcePath = ins->srcPath;//绝对路径
- }
- else if (ins->srcPathType == "2") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(2, rootPath)) {
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//当前版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 2 is fail");
- return false;
- }
- }
- else if (ins->srcPathType == "3") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(4, rootPath)) {
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//升级包相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 4 is fail");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd srcPathType is invalid %s", ins->srcPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd srcPathType is invalid %s", ins->srcPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd sourcePath is %s", sourcePath.GetData());
- CSimpleStringA destPath;//目的路径文件夹
- if (ins->dstPathType == "0") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(1, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "1") {
- destPath = ins->dstPath;//绝对路径
- }
- else if (ins->dstPathType == "2") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(2, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "3") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(3, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd dstPathType is invalid %s", ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd dstPathType is invalid %s", ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd destPath is %s", destPath.GetData());
- if (sourcePath.IndexOf("*") > 0) {
- //循环匹配拷贝
- //找到要扫描的文件夹
- CSimpleStringA strFileDir = GetFileDirectory(sourcePath.GetData());
- //过滤通配条件
- CSimpleStringA strFileFilter = _GetFileName(sourcePath.GetData());
- list<CSimpleStringA> fileList;
- //获取所有根文件夹下的文件相对路径:如mod\test.dll
- RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find fileList =%d", fileList.size());
-
- for (auto it = fileList.begin(); it != fileList.end(); it++)
- {
- if (IsFileMatch(strFileFilter, _GetFileName((const char*)(*it))))
- {
- CSimpleStringA strSrcName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", GetFileDirectory(sourcePath.GetData()).GetData(), (const char*)(*it));//源文件路径
- CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), (const char*)(*it));//目标文件路径
- //匹配成功,开始拷贝文件
- CSimpleStringA errMsg = "";
- ErrorCodeEnum rc = CopyFileOperate(strSrcName.GetData(), strDestName.GetData(), 3, errMsg);
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] to [%s] %s", strSrcName.GetData(),strDestName.GetData(), rc == Error_Succeed ? "succeed" : "fail");
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail: %s", strSrcName.GetData(), errMsg.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail: %s", strSrcName.GetData(), errMsg.GetData());
- return false;//报错
- }
- }
- }
- }
- else {
- //直接拷贝文件:考虑有些文件因智能对比不一定下发,故如果文件不存在,则默认忽略此策略
- CSimpleStringA errMsg = "";
- CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), _GetFileName(sourcePath.GetData()));
- if (ExistsFileA(sourcePath.GetData())) {
- ErrorCodeEnum rc = CopyFileOperate(sourcePath.GetData(), strDestName.GetData(), 3, errMsg);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:%s", sourcePath.GetData(), errMsg.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail:%s", sourcePath.GetData(), errMsg.GetData());
- return false;//报错
- }
- }
- else {
- if (ins->srcPathType == "3") {
- //升级包因智能升级不一定有指定的文件存在
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("拷贝指定的文件[%s]不存在,因智能升级对比过滤,故忽略此文件拷贝", sourcePath.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:file to copy not exist", sourcePath.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail:file to copy not exist", sourcePath.GetData());
- return false;//报错
- }
- }
- }
- return true;
- }
- bool CUpgradeTaskFSM::GetDepRootTypePath(int rootType, CSimpleStringA& Path)
- {
- //适配器
- CSimpleStringA tempPath;
- if (isTerminalInstall() && (rootType == 2 || rootType == 3)) {
- //当是安装状态时,此路径取pack_version值,如果为空,默认用0.0.0.1 版本号
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\4.9.1.1 /opt/Run/dep/4.9.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- if (!m_currentTask.pack_version.IsNullOrEmpty()) {
- Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
- }
- else {
- Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), "0.0.0.1");
- }
- return true;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is error");
- return false;
- }
- }
- if (rootType == 1) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Root", tempPath);//例如:C:\Run /opt/Run
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- string runPathStr = tempPath.GetData();
- int pos = runPathStr.find_last_of(SPLIT_SLASH);
- Path = runPathStr.substr(0, pos).c_str();
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is error");
- return false;
- }
- }
- else if (rootType == 2) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Dep", tempPath);//例如:C:\Run\dep\4.8.1.1 /opt/Run/dep/4.8.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- Path = tempPath;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is error");
- return false;
- }
- }
- else if (rootType == 3) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\4.9.1.1 /opt/Run/dep/4.9.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradeVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradeVer path is error");
- return false;
- }
- }
- else if (rootType == 4) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Downloads", tempPath);//例如:C:\rvc\Downloads\4.8.1.1 /opt/rvc/Downloads/4.8.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- CSimpleStringA strUnzipDir;
- strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_name.GetData());
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")) {
- Path = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
- }
- else {
- Path = strUnzipDir;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is error");
- return false;
- }
- }
- return true;
- }
- CSimpleStringA CUpgradeTaskFSM::getAlarmCurrVersion()
- {
- //一期因无法从策略获取适配器升级还是应用升级,默认返回当前应用版本数据,待二期再做区分
- return m_currentVersion.ToString();
- }
- ErrorCodeEnum CUpgradeTaskFSM::SetNewVersionPathToFirewall()
- {
- if (m_TempDepUpgradeFlag) {
- return Error_Succeed;//适配器升级,不设置
- }
- if (isTerminalInstall()) {
- return Error_Succeed;//安装新设备,不设置
- }
- if (!m_currentTask.NewVersion.IsNullOrEmpty()) {
- //升级应用版本
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer", rootVerPath);//获取version根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SetNewVersionPathToFirewall fail , get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.NewVersion.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SetNewVersionPathToFirewall path = %s", strNewVerPath.GetData());
- return m_pEntity->GetFunction()->SetNewPathToFirewall(strNewVerPath);
- }
- else {
- return Error_Succeed;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SM3FileToStr(CSimpleStringA strFilePath, CSimpleStringA &strSM3,bool isSub)
- {
- if(strFilePath.IsNullOrEmpty()){
- return Error_Null;
- }
- int nlen = strlen(strFilePath.GetData());
- char* pchar = new char[nlen+1];
- strcpy(pchar,strFilePath.GetData());
- BYTE md5[32]={0};
- try
- {
- if(SM3File(pchar,md5)){
- delete[] pchar;
- //获取16进制的字符串
- if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 to hex str fail,file=%s",strFilePath.GetData());
- return Error_Unexpect;
- }
- return Error_Succeed;
- }else{
- delete[] pchar;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt fail ,file=%s",strFilePath.GetData());
- return Error_Unexpect;
- }
- }
- catch (...)
- {
- delete[] pchar;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt exception ,file=%s",strFilePath.GetData());
- return Error_Exception;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SM3DataToStr(CSimpleStringA strData, CSimpleStringA &strSM3,bool isSub)
- {
- if(strData.IsNullOrEmpty()){
- return Error_Null;
- }
- BYTE md5[32]={0};
- try
- {
- if(SM3Hash((BYTE*)strData.GetData(),strlen(strData.GetData()),md5)){
- //获取16进制的字符串
- if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 to hex str fail");
- return Error_Unexpect;
- }
- return Error_Succeed;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt fail");
- return Error_Unexpect;
- }
- }
- catch (...)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt exception");
- return Error_Exception;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SM3_Str(CSimpleStringA &strSM3,BYTE * SM3Byte,bool isSub)
- {
- if(SM3Byte == NULL){
- return Error_Exception;
- }
- int SM3_len=64;
- if(isSub){
- SM3_len=32;
- }
- int i;
- char* file_SM3 = (char*)malloc((SM3_len + 1) * sizeof(char));
- if(file_SM3 == NULL)
- {
- fprintf(stderr, "SM3 malloc failed.\n");
- return Error_Exception;
- }
- memset(file_SM3, 0, (SM3_len + 1));
- if(SM3_len == 32)
- {
- for(i=0; i<16; i++)
- { //SM3截取中间16位字节,8-24位字节数,小写
- sprintf(&file_SM3[i*2], "%02x", SM3Byte[i+8]);
- }
- }
- else if(SM3_len == 64)
- {
- for(i=0; i<32; i++)
- {
- sprintf(&file_SM3[i*2], "%02x", SM3Byte[i]);
- }
- }
- strSM3=file_SM3;
- free(file_SM3);
- return Error_Succeed;
- }
- bool CUpgradeTaskFSM::IsPackDownloaded(const char *packPath,const char* packHash,long packLen)
- {
- if(!ExistsFileA(packPath)){
- return false;//文件不存在,下载
- }
- //计算hash值
- CSimpleStringA strMD5Val;
- ErrorCodeEnum rc = SM3FileToStr(packPath, strMD5Val,false);
- if (Error_Succeed != rc)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s get download pack sm3 fail ,error:%d", packPath, (int)rc);
- return false;//获取hash码失败,下载
- }
- //不区分大小写比较文件hash
- #ifdef RVC_OS_WIN
- if(stricmp(strMD5Val.GetData(),packHash)==0){
- #else
- if(strcmp(strMD5Val.GetData(),packHash)==0){
- #endif
- return true;//相同,不下载
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s sm3[%s] is no equal upgrade sm3[%s], retry download.", packPath, strMD5Val.GetData(), packHash);
- return false;//不相同,下载
- }
- }
- bool CUpgradeTaskFSM::DownloadFileWrite(byte* content,long contentLen,const char* filePath)
- {
- if(contentLen==0){
- return true;
- }
- FILE* tempFp = fopen(filePath,"ab");
- if(tempFp==NULL){
- DbgWithLink(LOG_LEVEL_WARN,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite open file fail");
- return false;
- }
- int ret = fwrite(content,(size_t)contentLen,1,tempFp);
- if (ret != 1) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite write file fail,ret = %d,errno = %d", ret, (int)GetLastError());
- fclose(tempFp);
- return false;
- }
- else {
- fflush(tempFp);
- #ifdef RVC_OS_WIN
- int CommitRet = _commit(_fileno(tempFp));
- #else
- int CommitRet = fsync(fileno(tempFp));
- #endif
- if (CommitRet != 0) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite write file commit fail,errno = %d", (int)GetLastError());
- }
- fclose(tempFp);
- return true;
- }
- }
- bool CUpgradeTaskFSM::CheckIfCanSwitchNow()
- {
- //对于终端初始化安装时,直接通过。
- if (isTerminalInstall()) {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow terminal new install,return true");
- return true;
- }
- //非重启操作,则直接可以进行切换,不用等待时机
- if(m_currentTask.reboot_type == 0){
- return true;
- }
- CSimpleStringA strCustomerHandle;
- CSimpleStringA strCallState;
- // 无交互N、客户关注A、客户在控制终端C、柜员协助T、柜员代操作G
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetSysVar("CustomerHandle", strCustomerHandle);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get CustomerHandle value is fail ,err=%d",(int)rc);
- return false;
- }
- // 离线O、尝试连线柜员C、免提通话H、连线失败F、断线B
- rc = m_pEntity->GetFunction()->GetSysVar("CallState", strCallState);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get CallState value is fail ,err=%d",(int)rc);
- return false;
- }
- // M 首页
- CSimpleStringA csUIState;
- rc = m_pEntity->GetFunction()->GetSysVar("UIState", csUIState);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get strUIState value is fail ,err=%d", (int)rc);
- return false;
- }
- #ifdef RVC_OS_WIN
- SYSTEMTIME st = {};
- GetLocalTime(&st);
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("hour is %d",(int)st.wHour);
- bool bOffworkTime = st.wHour < 8 || st.wHour >= 20;
- 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);
- #else
- time_t nowTime = time(NULL);
- tm nowTimeTm = { 0 };
- localtime_r(&nowTime, &nowTimeTm);
- //Dbg("hour is %d", (int)nowTimeTm.tm_hour);
- bool bOffworkTime = nowTimeTm.tm_hour < 8 || nowTimeTm.tm_hour >= 20;
- 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);
- #endif
- // 或者下班时间且非连线状态 @20151202
- // 客户关注状态A,不允许切换 by zl 20191113
- if (strCustomerHandle[0] == 'N' || (bOffworkTime && (strCallState[0] == 'O') && (csUIState.Compare("M") == 0))) {
- return true;
- }
- else {
- // 防止感知一直误报有人状态,加入以下特例:如果是一天当中首次从切换状态直接跳转过来的升级切换,并且当前是首页则进行切换
- if (!bOffworkTime) {
- CSimpleStringA strUIState;
- // M 首页
- rc = m_pEntity->GetFunction()->GetSysVar("UIState", strUIState);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get strUIState value is fail ,err=%d", (int)rc);
- return false;
- }
- #ifdef RVC_OS_WIN
- CSimpleStringA nowStr = CSimpleStringA::Format("%d-%d-%d", st.wYear, st.wMonth, st.wDay).GetData();
- #else
- CSimpleStringA nowStr = CSimpleStringA::Format("%d-%d-%d", nowTimeTm.tm_year+1900, nowTimeTm.tm_mon+1, nowTimeTm.tm_mday).GetData();
- #endif
- //读取强制切换的日期
- CSimpleStringA ForceSwitchDateStr = "";
- ErrorCodeEnum rc = GetRunConfigStrValue("upgradeTask", "ForceSwitchDate", ForceSwitchDateStr);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow read from run config, read [upgradeTask][ForceSwitchDate] fail ,err=%d", (int)rc);
- return false;
- }
- //首页并且切换状态直接进入
- if (strUIState.Compare("M") == 0 && m_bSwitchFlag) {
- //当天是否切换过
- if (ForceSwitchDateStr.Compare(nowStr.GetData()) == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow is not ForceSwitch, ForceSwitchDate[%s]", ForceSwitchDateStr.GetData());
- return false;
- }
- else {
- //直接切换,并写入强制切换日期
- if (SetRunConfigStrValue("upgradeTask", "ForceSwitchDate", nowStr.GetData()) != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow write run config, write [upgradeTask][ForceSwitchDate] fail[%s],err=%d", nowStr.GetData(), (int)rc);
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow ForceSwitch, ForceSwitchDate[%s]", nowStr.GetData());
- return true;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow is not ForceSwitch, UIState=%s,m_bSwitchFlag=%d", strUIState.GetData(),(int)m_bSwitchFlag);
- return false;
- }
- }
- else {
- return false;
- }
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SwitchUpgradeNow()
- {
- //默认轻量包不重启系统和框架,体系外系统不重启系统,系统升级重启框架
- //根据重启策略类型去重启
- //重启策略类型(0:不启动 1:重启框架 2:重启系统)
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin SwitchUpgradeNow");
- if (m_currentTask.reboot_type == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("reboot_type = 0 , no need Switch restart, taskID=[%s] ", m_currentTask.upgradeTaskId.GetData());
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- else if (m_currentTask.reboot_type == 1) {
- if (m_currentTask.NewVersion.IsNullOrEmpty()) {
- //非版本升级
- LogEvent(Severity_Middle, Event_Req_Framework_No_Upgrade_Restart,
- CSimpleStringA::Format("upgrade to new version [%s] succeed, request to no upgrade restart framework , taskID=[%s]", m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else {
- if (m_currentTask.task_type.Compare("U") == 0) {
- //版本升级,健康有后续回退处理
- LogEvent(Severity_Middle, Event_Req_Framework_Restart,
- CSimpleStringA::Format("upgrade to new version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else if (m_currentTask.task_type.Compare("R") == 0) {
- //版本回退,健康无后续回滚处理
- LogEvent(Severity_Middle, Event_Req_Framework_Rollback_Restart,
- CSimpleStringA::Format("rollback to old version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- }
- }
- else if (m_currentTask.reboot_type == 2) {
- if (m_currentTask.NewVersion.IsNullOrEmpty()) {
- //非版本升级
- LogEvent(Severity_Middle, Event_Req_OS_Restart,
- CSimpleStringA::Format("SysPackInstall upgrade to new version [%s] succeed, request to restart OS, taskID=[%s]", m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else {
- if (m_currentTask.task_type.Compare("U") == 0) {
- LogEvent(Severity_Middle, Event_Req_OS_Upgrade_Restart,
- CSimpleStringA::Format("upgrade to new version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else {
- LogEvent(Severity_Middle, Event_Req_OS_Restart,
- CSimpleStringA::Format("rollback to old version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- }
- }
- else {
- 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());
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- // 强制刷新日志
- m_pEntity->GetFunction()->FlushLogFile();
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::DownloadProgress(long tempFileLen,long fileSumLen)
- {
- UpgradeDownloadProgress dProgress;
- dProgress.currentFile = m_currentTask.pack_name;
- dProgress.fileNum = 1;
- dProgress.progress=0;
- if(fileSumLen!=0){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("tempFileLen =%d , fileSumLen =%d",tempFileLen,fileSumLen);
- dProgress.progress = (int)(tempFileLen/(fileSumLen/100));
- if(dProgress.progress ==10||dProgress.progress ==20||dProgress.progress ==30||dProgress.progress ==40||dProgress.progress ==50
- ||dProgress.progress ==60||dProgress.progress ==70||dProgress.progress ==80||dProgress.progress ==90)
- {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("download progress is %d ,tempFileLen =%d , fileSumLen =%d",dProgress.progress,tempFileLen,fileSumLen);
- }
- //Dbg("download file [%s] progress is %d",dProgress.currentFile.GetData(),dProgress.progress);
- ErrorCodeEnum retError = SpSendBroadcast(GetEntityBase()->GetFunction(), SP_MSG_OF(UpgradeDownloadProgress), SP_MSG_SIG_OF(UpgradeDownloadProgress), dProgress);
- return retError;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("download file progress is fail,fileSumLen=0");
- return Error_Exception;
- }
-
- }
- char CUpgradeTaskFSM::GetInstallState(int nState)
- {
- if (nState == s4)
- return 'U';
- else if (nState == s5)
- return 'I';
- else if (nState == s6)
- return 'S';
- else
- return 'N';
- }
- ErrorCodeEnum CUpgradeTaskFSM::GetUpgradeState(bool &bInstalling, CSimpleStringA &strPackFile, CSimpleStringA &strExecID, char &cInstallState, bool &bSysInstall, bool &bLightPack, CSimpleStringA &strNewVersion)
- {
- bInstalling = !m_currentTask.upgradeTaskId.IsNullOrEmpty();
- if (bInstalling)
- {
- strPackFile = m_currentTask.pack_name;
- strExecID = m_currentTask.upgradeTaskId;
- cInstallState = GetInstallState(m_iState);
- bSysInstall = false;
- bLightPack = false;
- //if(!m_currentTask.to_run.IsNullOrEmpty()){
- // bSysInstall = true;
- //}else{
- // bSysInstall = false;
- //}
- //if(m_currentTask.pack_version.IsNullOrEmpty()){
- // bLightPack = true;
- //}else{
- // bLightPack = false;
- //}
- strNewVersion = m_currentTask.NewVersion;
- }
- return Error_Succeed;
- }
- void CUpgradeTaskFSM::HttpsLogCallBack(const char* logtxt)
- {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("http dbg: %s",logtxt);
- }
- bool CUpgradeTaskFSM::isWork()
- {
- //兜底方案是判断集中配置一个参数,去除其他变量的判断,但是容易出现任务状态更新不准的情况。
- if(m_startFlag){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade startFlag is true");
- return true;
- }
- //判断是否在设备安装状态,不受一般升级影响
- if (isTerminalInstall()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("isTerminalInstall get TerminalStage=N, is New Terminal Install");
- return true;
- }
- else {
- //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("isTerminalInstall get TerminalStage is not N");
- }
-
- //判断升级实体是否工作
- //1.当有版本升级任务时,判断是否处于Guardian升级回退过程,如果已经升级成功或者回退成功,则开始工作,否则等待中
- //2.当无任务或者非版本升级任务时,判断TerminalStage这个变量,非X状态,当A状态并且进入首页,则开始工作
-
- //升级任务
- if((!m_currentTask.NewVersion.IsNullOrEmpty())&&(m_currentTask.cPendingState=="T"||m_currentTask.cPendingState=="C"||m_currentTask.cPendingState=="X")){
- CSimpleStringA strRunCfg,strStartTime;
- if (m_pEntity->GetFunction()->GetPath("RunCfg",strRunCfg) == Error_Succeed){
- strStartTime = strRunCfg + SPLIT_SLASH_STR + "starttime.dat";
- if(!ExistsFileA(strStartTime.GetData())){
- return true;//完成升级过程,通过
- }else{
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("upgrade process is not end ,file %s is exist", strStartTime.GetData());
- return false;//继续等待
- }
- }else{
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("upgrade process is not end ,get runinfo path is error");
- return false;//失败,继续等待
- }
- }
- //适配器任务
- if ((!m_currentTask.depNewVersion.IsNullOrEmpty()) && (m_currentTask.cPendingState == "T" || m_currentTask.cPendingState == "C" || m_currentTask.cPendingState == "X")) {
- return true;//适配器无升级监护
- }
- //非升级任务和无任务
- CSimpleStringA strValue;
- if(m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed){
- if(strValue.Compare("X")==0){
- m_queryIsWorkCount++;
- if (m_queryIsWorkCount >= QUERY_IS_WORK_WARN_LIMIT) {
- m_queryIsWorkCount = 0;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("TerminalStage = X ,continue wait");
- }
- else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("TerminalStage = X ,continue wait");
- }
- return false;//状态是x继续等待
- }
- if(strValue.Compare("A")==0){
- if(((CUpgradeMgrEntity*)m_pEntity)->m_bStartUp){
- return true;//通过
- }else{
- m_queryIsWorkCount++;
- if (m_queryIsWorkCount >= QUERY_IS_WORK_WARN_LIMIT) {
- m_queryIsWorkCount = 0;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("TerminalStage = A ,but UIState is not M , continue wait");
- }
- else {
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("TerminalStage = A ,but UIState is not M , continue wait");
- }
- return false;//准入过,但未进入首页,继续等待
- }
- }
- return true;//剩余其他状态都可以通过
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("get TerminalStage is error , continue wait");
- return false;//失败,继续等待
- }
- }
- bool CUpgradeTaskFSM::isAuthSucc() {
- CSimpleStringA strValue;
- if (m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed) {
- if (strValue.Compare("A") == 0) {
- return true;
- }
- else {
- return false;
- }
- }
- else {
- return false;
- }
- }
- bool CUpgradeTaskFSM::isTerminalInstall() {
- CSimpleStringA strValue;
- if (m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed) {
- if (strValue.Compare("N") == 0) {
- //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("isTerminalInstall get TerminalStage=N, is New Terminal Install");
- return true; //表示安装模式
- }else{
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("isTerminalInstall get TerminalStage is error , default return fasle");
- return false;//默认认为在升级状态
- }
- }
- void CUpgradeTaskFSM::upgradeSuccStateBroadCast() {
- UpgradeStateEvent stateEvent;
- stateEvent.strPackName = m_currentTask.pack_name.GetData();
- stateEvent.strExecID = m_currentTask.upgradeTaskId.GetData();
- stateEvent.cInstallState = 'A';//表示成功状态
- stateEvent.bSysInstall = false;
- stateEvent.bLightPack = false;
- stateEvent.strNewVersion = m_currentTask.NewVersion;
- SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
- }
- #ifdef RVC_OS_WIN
- #else
- int CUpgradeTaskFSM::changeFileAtt(const char* path)
- {
- struct stat attr_of_del;
- if (lstat(path, &attr_of_del) == 0)
- {
- //修改为775属性
- mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
- if (chmod(path, f_attrib) != 0)
- {
- Dbg("set file attribute is fail,errno=%d, file=%s", errno, path);
- return -1;
- }
- return 0;
- }
- else {
- Dbg("get file attribute is fail,errno=%d, file=%s", errno, path);
- return -1;
- }
- }
- #endif
- void CUpgradeTaskFSM::OnStateTrans(int iSrcState, int iDstState)
- {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
- if (iSrcState >= s4 && iDstState <= s3)
- {
- // 发送状态广播(通知业务界面清除状态)
- UpgradeStateEvent stateEvent;
- stateEvent.strPackName = "";
- stateEvent.strExecID = "";
- stateEvent.cInstallState = 'N';
- stateEvent.bSysInstall = false;
- stateEvent.bLightPack = false;
- stateEvent.strNewVersion = "";
- SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
- }
- else if (iDstState >= s4)
- {
- //assert(HasRunningUpdate());
- //SetRunConfigStrValue("Install", "Pack", m_strIntallingPack);
- //if (iDstState == s3)
- // SetRunConfigStrValue("Install", "PendingState", "U");
- //else if (iDstState == s4)
- // SetRunConfigStrValue("Install", "PendingState", "I");
- //else if (iDstState == s5)
- // SetRunConfigStrValue("Install", "PendingState", "C");
- //else if (iDstState == s6)
- // SetRunConfigStrValue("Install", "PendingState", "S");
- // 发送状态广播
- UpgradeStateEvent stateEvent;
- stateEvent.strPackName = m_currentTask.pack_name.GetData();
- stateEvent.strExecID = m_currentTask.upgradeTaskId.GetData();
- stateEvent.cInstallState = GetInstallState(iDstState);
- stateEvent.bSysInstall = false;
- stateEvent.bLightPack = false;
- stateEvent.strNewVersion = m_currentTask.NewVersion;
- SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
- }
- }
- void CUpgradeTaskFSM::OnSysVarEvent(const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName)
- {
- //监听系统变量状态
- if(strcmp("CallState",pszKey)==0){
- if (pszValue[0] == 'O') {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("m_bDownloadIdle is false ");
- m_bDownloadIdle = false;//可以下载
- } else {
- //DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("m_bDownloadIdle is true");
- m_bDownloadIdle = true;//不能下载
- }
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::OnInit()
- {
- //初始化
- ErrorCodeEnum rc = LoadPersistTaskInfo();//加载运行时文件
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("LoadPersistTaskInfo fail");
- return rc;
- }
- rc = loadCenterCfgInfo();//加载集中配置文件
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("loadCenterCfgInfo fail");
- return rc;
- }
- //加载终端启动的版本号
- CSystemStaticInfo info;
- rc = m_pEntity->GetFunction()->GetSystemStaticInfo(info);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("load GetSystemStaticInfo fail ");
- return rc;
- }else{
- m_currentVersion = info.InstallVersion;//当前版本号赋值
- m_currentDepVersion = info.CurrDepVersion.GetData();//当前适配器版本号,有可能为空
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("App version:%s , Dep version:%s", m_currentVersion.ToString().GetData(),m_currentDepVersion.GetData());
- }
- //注册callstate变量监控
- rc = m_pEntity->GetFunction()->RegistSysVarEvent("CallState", this);
- if(rc!=Error_Succeed){
- LogWarn(Severity_Middle, rc, ERR_WRAN_REGIST_SYS_VAR_FAIL, CSimpleStringA::Format("RegistSysVarEvent CallState is fail,%d",(int)rc).GetData());
- return rc;//自检失败
- }else{
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("RegistSysVarEvent CallState succ");
- }
- AddStateHooker(this);
- ((CUpgradeMgrEntity*)m_pEntity)->testActive();//添加测试active文件是否被占用的方法
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::OnExit()
- {
- m_pEntity->GetFunction()->UnregistSysVarEvent("CallState");
- RemoveStateHooker(this);
- return Error_Succeed;
- }
- void CUpgradeTaskFSM::s1_on_entry()
- {
- //判断是否进入了首页
- CSimpleStringA strValue;
- m_queryIsWorkCount = 0;
- if(isWork()&&((CUpgradeMgrEntity*)m_pEntity)->m_initSucc){
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("====upgrade is start up ====");
- ScheduleTimer(2,1*1000);
- }else{
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("last upgrade progress is not end or is not initSucc,wait 20s ");
- ScheduleTimer(1, 20*1000);//等待一段时间再判断是否进入首页
- }
- }
- void CUpgradeTaskFSM::s1_on_exit()
- {
- CancelTimer(1);//等待进入首页计时器
- CancelTimer(2);//等待hash计算计时器
- }
- unsigned int CUpgradeTaskFSM::s1_on_event(FSMEvent* event)
- {
- if (event->iEvt == EVT_TIMER)
- {
- if(event->param1 == 1){
- CSimpleStringA strValue;
- if(isWork()&&((CUpgradeMgrEntity*)m_pEntity)->m_initSucc){
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("====upgrade is start up ====");
- ScheduleTimer(2,1*1000);
- }else{
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM)("last upgrade progress is not end or is not initSucc,wait 20s ");
- ScheduleTimer(1, 20*1000);//等待一段时间再判断是否进入首页
- }
- }else if(event->param1 ==2){
-
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入s2
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s2_on_entry()
- {
- //判断是否存在残留任务
- if(m_currentTask.upgradeTaskId.IsNullOrEmpty()&&m_currentTask.cPendingState.IsNullOrEmpty()){
- //直接进入查询新任务
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- //处理上个任务
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));
- }
- }
- void CUpgradeTaskFSM::s2_on_exit()
- {
- CancelTimer(1);//更新任务状态计时器
- CancelTimer(2);//查询当前任务计时器
- }
- unsigned int CUpgradeTaskFSM::s2_on_event(FSMEvent* event)
- {
- if (event->iEvt == EVT_TIMER){
- if(event->param1 == 1){
- Task::UpdateTaskStatus* uTask = new Task::UpdateTaskStatus(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(uTask);
- if(Error_Succeed!=rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create UpdateTaskStatus is fail,%d",(int)rc);
- ScheduleTimer(1,60*1000);//继续更新任务状态
- }
- }else if(event->param1 == 2){
- Task::QueryCurrTask* qTask = new Task::QueryCurrTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
- if(Error_Succeed!=rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create QueryCurrTask is fail,%d",(int)rc);
- ScheduleTimer(2,4*60*1000);//继续查询当前任务
- }
- }
- }else if (event->iEvt == Event_DealCurrTask)
- {
- //处理运行时文件异常记录的情况
- if (m_currentTask.task_type.IsNullOrEmpty()) {
- m_currentTask.task_type = "U";//兼容旧版本字段无值的情况,默认是升级模式
- }
- if (m_currentTask.task_type.Compare("U") == 0) {
- if (m_currentTask.upgradeTaskId.IsNullOrEmpty() || m_currentTask.createTaskVersion.IsNullOrEmpty()
- || m_currentTask.cPendingState.IsNullOrEmpty() || m_currentTask.pack_name.IsNullOrEmpty()) {
- //有任务时,则4个字段不能为空,否则任务有问题
- CSimpleStringA errStr = CSimpleStringA::Format("current Task param is null, clear this task, upgradeTaskId=[%s],createTaskVersion=[%s],cPendingState=[%s],PackName=[%s]",
- m_currentTask.upgradeTaskId.GetData(), m_currentTask.createTaskVersion.GetData(), m_currentTask.cPendingState.GetData(), m_currentTask.pack_name.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK, errStr.GetData());
- if (ClearCurrTaskInfo()) {
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
- }
- }
- }
- else if (m_currentTask.task_type.Compare("R") == 0) {
- if (m_currentTask.upgradeTaskId.IsNullOrEmpty() || m_currentTask.createTaskVersion.IsNullOrEmpty()
- || m_currentTask.cPendingState.IsNullOrEmpty()) {
- //有任务时,则3个字段不能为空,否则任务有问题
- CSimpleStringA errStr = CSimpleStringA::Format("current Task param is null, clear this task, upgradeTaskId=[%s],createTaskVersion=[%s],cPendingState=[%s]",
- m_currentTask.upgradeTaskId.GetData(), m_currentTask.createTaskVersion.GetData(), m_currentTask.cPendingState.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK, errStr.GetData());
- if (ClearCurrTaskInfo()) {
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
- }
- }
- }
- else {
- CSimpleStringA errStr = CSimpleStringA::Format("current Task param task_type=[%s], param is Not Supported, clear this task",m_currentTask.task_type.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK, errStr.GetData());
- if (ClearCurrTaskInfo()) {
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
- }
- }
- //任务已到最终状态
- if(m_currentTask.cPendingState=="T"||m_currentTask.cPendingState=="C"||m_currentTask.cPendingState=="X"){
- //取消任务C和切换任务T时,更新任务状态
- Task::UpdateTaskStatus* uTask = new Task::UpdateTaskStatus(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(uTask);
- if(Error_Succeed!=rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create UpdateTaskStatus is fail,%d",(int)rc);
- ScheduleTimer(1,60*1000);//继续更新任务状态
- }
- }else{
- //当前任务
- if(m_currentTask.createTaskVersion!=m_currentVersion.ToString()){
- //比较遗留任务的创建版本号是否和现在版本一致,不一致,则可能出现拷贝别的终端文件或者已经手工改了别的版本引发,这种情况下自动清理此次任务。
- 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());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK,errStr.GetData());
- if(ClearCurrTaskInfo()){
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 2,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
- }
- }else{
- Task::QueryCurrTask* qTask = new Task::QueryCurrTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
- if(Error_Succeed!=rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create QueryCurrTask is fail,%d",(int)rc);
- ScheduleTimer(2,4*60*1000);//继续查询当前任务
- }
- }
- }
- }else if(event->iEvt == Event_EndUpdateTask){
- //更新任务状态返回结果
- UpdateTaskStatusEvent* pEvent = (UpdateTaskStatusEvent*)event;
- if(pEvent->isSucc){
- //告警回滚和升级成功
- if(m_currentTask.cPendingState=="T"){
- if (isTerminalInstall()) {
- //安装情况
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentVersion.ToString();//当前的版本
- up.CurrentVersion = m_currentVersion.ToString();//当前的版本
- }
- else {
- up.installVersion = m_currentDepVersion.GetData();//安装适配器版本
- up.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
- }
- up.cInstallState = "A";
- up.strInstallComment = "启动成功";
- SendUpgradeTaskProgress(up, UpgradeMgr_START_ID);
- upgradeSuccStateBroadCast();//广播告知升级成功
- }
- else {
- //非安装情况
- if (m_currentTask.NewVersion == m_currentVersion.ToString() ||
- m_currentTask.depNewVersion == m_currentDepVersion ||
- (m_currentTask.NewVersion == "" && m_currentTask.depNewVersion == "")) {
- //安装成功
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentVersion.ToString();//当前的版本
- up.CurrentVersion = m_currentVersion.ToString();//当前的版本
- }
- else {
- up.installVersion = m_currentDepVersion.GetData();//安装适配器版本
- up.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
- }
- up.cInstallState = "A";
- up.strInstallComment = "启动成功";
- if (m_currentTask.task_type.Compare("U") == 0) {
- SendUpgradeTaskProgress(up, UpgradeMgr_START_ID);
- }
- else {
- SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_START_ID);
- }
- upgradeSuccStateBroadCast();//广播告知升级成功
- }
- else {
- //回滚
- struct CTaskProcess upRoll;
- upRoll.strPackName = m_currentTask.pack_name;//安装包名
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- upRoll.installVersion = m_currentTask.NewVersion.GetData();//任务升级后的版本号
- upRoll.CurrentVersion = m_currentVersion.ToString();//当前的版本
- }
- else {
- upRoll.installVersion = m_currentTask.depNewVersion.GetData();//安装适配器版本
- upRoll.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
- }
- upRoll.cInstallState = "R";
- upRoll.strInstallComment = "自动倒回";
- if (m_currentTask.task_type.Compare("U") == 0) {
- SendUpgradeTaskProgress(upRoll, UpgradeMgr_START_ID, " RTA5667");
- }
- else {
- SendUpgradeTaskProgress(upRoll, UpgradeMgr_ROLLBACK_START_ID, " RTA5672");
- }
- }
- }
- ErrorCodeEnum rc = SetRunSucceed(m_currentTask.pack_name.GetData());
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetRunSucceed is fail: %d", (int)rc);
- }
-
- }
- //清除运行时文件和内存任务,跳转到S3
- if(ClearCurrTaskInfo()){
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndUpdateTask clear current task is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new UpdateTaskStatusEvent(true));//继续更新任务状态
- }
- }else{
- ScheduleTimer(1,60*1000);//继续更新任务状态
- }
- }else if(event->iEvt == Event_EndQueryCurrTask){
- //查询当前任务返回结果
- QueryCurrTaskEvent* pEvent = (QueryCurrTaskEvent*)event;
- if(pEvent->isSucc){
- if(pEvent->isTask_valid){
- //根据不同任务状态值,进入不同阶段。U:下载阶段,I:安装阶段,回退检查,S切换阶段
- if(m_currentTask.cPendingState=="U"){
- return 4;//下载
- }else if(m_currentTask.cPendingState=="I"){
- if (m_currentTask.task_type.Compare("R") == 0) {
- //因回退不进入S阶段,故加入切换标志。
- m_bSwitchFlag = true;
- }
- return 5;//安装,回退检查
- }else if(m_currentTask.cPendingState=="S"){
- //加入切换标志,用于切换时判断是否是切换进入的流程。
- m_bSwitchFlag = true;
- //是否是升级适配器需要根据运行时字段进行赋值
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- m_TempDepUpgradeFlag = false;
- }
- else {
- m_TempDepUpgradeFlag = true;
- }
- return 6;//切换
- }else{
- //无效状态
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_STATUS_FAIL,CSimpleStringA::Format("invalid pending state : %s",m_currentTask.cPendingState.GetData()).GetData());
- //任务无效,清理任务
- if(ClearCurrTaskInfo()){
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndQueryCurrTask clear current task is fail 2,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new QueryCurrTaskEvent(true,true));//继续清理当前任务
- }
- }
- }else{
- 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());
- //任务无效,清理任务
- if(ClearCurrTaskInfo()){
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndQueryCurrTask clear current task is fail 1,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new QueryCurrTaskEvent(true,false));//继续清理当前任务
- }
- }
- }else{
- ScheduleTimer(2,4*60*1000);//继续查询当前任务
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s3_on_entry()
- {
- //查询新任务:先预查询任务,传送hash,接着查询任务
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("entery S3");
- m_queryNewTaskCount = 0;
- m_strPreTaskId = "";
- m_bNeedHash=0;
- m_fileSM3List="";
- m_fileSM3ListHash="";
- isSendHash=false;
- //预查询任务
- Task::QueryNewPreTask* qTask = new Task::QueryNewPreTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewPreTask fail,wait 4 min retry ,err=%d",(int)rc);
- ScheduleTimer(1, m_queryNewTaskInterval*1000);//等待4分钟后再次查询是否有新任务
- }
- }
- void CUpgradeTaskFSM::s3_on_exit()
- {
- CancelTimer(1);//预查询任务计时器
- CancelTimer(2);//上传hash计时器
- CancelTimer(3);//继续任务计时器
- m_queryNewTaskCount =0;
- m_strPreTaskId = "";
- m_bNeedHash=0;
- m_fileSM3List="";
- m_fileSM3ListHash="";
- isSendHash=false;
- }
- unsigned int CUpgradeTaskFSM::s3_on_event(FSMEvent* event)
- {
- if(event->iEvt == EVT_TIMER){
-
- if(event->param1 == 1){
- //发起预查询任务
- Task::QueryNewPreTask* nTask = new Task::QueryNewPreTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewPreTask fail,wait [%d]s retry ,err=%d", m_queryNewTaskInterval, (int)rc);
- ScheduleTimer(1, m_queryNewTaskInterval *1000);//等待4分钟后再次查询是否有新任务
- }
- }else if(event->param1 == 2){
- //上传hash
- Task::SendSM3Task* SM3Task = new Task::SendSM3Task(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(SM3Task);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create SendSM3Task fail,err=%d",(int)rc);
- ScheduleTimer(2, 60*1000);//等待1分钟过后再次发送
- }
- }else if(event->param1 == 3){
- //继续任务
- Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
- ScheduleTimer(3, m_queryNewTaskInterval *1000);//等待4分钟过后再次发送
- }
- }
- }
- else if(event->iEvt == Event_EndPrePoll){
- QueryNewPreTaskEvent* pEvent = (QueryNewPreTaskEvent*)event;
- if(pEvent->isSucc){
- if(m_strPreTaskId.IsNullOrEmpty()){
- m_queryNewTaskCount++;
- if(m_queryNewTaskCount>=QUERY_NO_TASK_WARN_LIMIT){
- //LogWarn(Severity_Low, Error_Exception, ERR_TASK_QUERY_NO_TASK,"QueryNewPreTask 15 times succ,no new task");
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("QueryNewPreTask 15 times succ,no new task");
- m_queryNewTaskCount=0;
- }
- if (isAuthSucc()) {
- ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次查询是否有新任务
- }
- else {
- ScheduleTimer(1, 30 * 1000);//等待30s后再次查询是否有新任务
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewPreTask succ, task_id=%s, needHash=%d",m_strPreTaskId.GetData(),m_bNeedHash);
- if(m_bNeedHash){
- //预查询成功
- if(isSendHash){
- //之前发送hash成功,直接开始继续任务查询线程
- Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
- ScheduleTimer(3, 60*1000);//再次查询是否有新任务
- }
- }else{
- //之前未发送hash成功,开始计算hash线程
- Task::SendSM3Task* SM3Task = new Task::SendSM3Task(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(SM3Task);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create SendSM3Task fail,err=%d",(int)rc);
- ScheduleTimer(2, 60*1000);//等待一分钟过后再次发送
- }
- }
- }else{
- //不需要hash,直接继续查询新任务
- Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
- ScheduleTimer(3, 60*1000);//等待4分钟后再次查询是否有新任务
- }
- }
- }
- }else{
- //预查询失败
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewPreTask fail,wait 4 min retry");
- if (isAuthSucc()) {
- ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次预查询是否有新任务
- }
- else {
- ScheduleTimer(1, 30 * 1000);//等待30s后再次查询是否有新任务
- }
-
- }
- }
- else if(event->iEvt == Event_EndSendSM3Task){
- Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
- ScheduleTimer(3, 60*1000);//等待4分钟后再次查询是否有新任务
- }
- }
- else if(event->iEvt == Event_EndContinuePoll){
- QueryNewContinueTaskEvent* pEvent = (QueryNewContinueTaskEvent*)event;
- if(pEvent->retParam == 0){
- //查询失败,继续查询
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask fail,wait [%d]s retry",m_queryNewTaskInterval);
- if (isAuthSucc()) {
- ScheduleTimer(3, m_queryNewTaskInterval * 1000);//等待4分钟后再次查询继续新任务
- }
- else {
- ScheduleTimer(3, 30 * 1000);//等待30s后再次查询继续新任务
- }
- }else if(pEvent->retParam == 1){
- //查询成功,跳到下一个状态,写入运行时文件
- bool isWriteOk=false;
- while(true){
- if(SetRunConfigStrValue("upgradeTask","NewVersion","")!=Error_Succeed){
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "depNewVersion", "") != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "CreateTaskVersion", m_currentTask.createTaskVersion.GetData()) != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "UpgradeTaskId", m_currentTask.upgradeTaskId.GetData()) != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "taskType", m_currentTask.task_type.GetData()) != Error_Succeed) {
- break;
- }
- if (m_currentTask.task_type.Compare("U") == 0) {
- if (SetRunConfigStrValue("upgradeTask", "PendingState", "U") != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "PackName", m_currentTask.pack_name.GetData()) != Error_Succeed) {
- break;
- }
- }else if(m_currentTask.task_type.Compare("R") == 0){
- if (SetRunConfigStrValue("upgradeTask", "PendingState", "I") != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "PackName", "") != Error_Succeed) {
- break;
- }
- }
- isWriteOk=true;
- break;
- }
- if(isWriteOk){
- if (m_currentTask.task_type.Compare("U") == 0) {
- //升级下载
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "D";
- up.strInstallComment = "正在下载";
- SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID);
- m_currentTask.cPendingState = "U";//改变内存变量为U
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDownload));//进入S4
- }
- else {
- //回退
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "B";
- up.strInstallComment = "正在回退";
- SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID);
- m_currentTask.cPendingState = "I";//改变内存变量为I
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartInstall));//进入S5
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndPoll write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续创建
- PostEventFIFO(new QueryNewContinueTaskEvent(1));//继续创建任务
- }
- }else{
- //跳出,重新预检查任务
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask fail,jump to PreTask");
- if (isAuthSucc()) {
- ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次预查询是否有新任务
- }
- else {
- ScheduleTimer(1, 30 * 1000);//等待30s后再次预查询是否有新任务
- }
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s4_on_entry()
- {
- //下载升级包
- m_bTaskCancel = false;//默认任务非取消
- m_downloadBreakOffCount = 0;
- if(m_bDownloadIdle){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CallState is not O , download is break off , wait a moment");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//进入不可下载状态
- }else{
- Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
- ScheduleTimer(1, 15*1000);//等待15秒再试
- }
- }
- ScheduleTimer(2, 30*1000);//启动查询任务是否有效
- }
- void CUpgradeTaskFSM::s4_on_exit()
- {
- CancelTimer(1);//正常下载计时器
- CancelTimer(2);//查询任务是否取消计时器
- CancelTimer(3);//外部状态中止下载计时器
- }
- unsigned int CUpgradeTaskFSM::s4_on_event(FSMEvent* event)
- {
-
- if (event->iEvt == EVT_TIMER)
- {
- if(event->param1 == 1){
- Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
- ScheduleTimer(1, 15*1000);//再次下载升级包
- }
- }else if(event->param1 == 2){
- Task::QueryTaskStatus* dTask = new Task::QueryTaskStatus(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create QueryTaskStatus fail,err=%d",(int)rc);
- ScheduleTimer(2, 30*1000);//再次查询任务是否有效
- }
- }else if(event->param1 == 3){
- //无效状态
- if(m_bDownloadIdle){
- if (m_downloadBreakOffCount > 60) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CallState is not O , download is break off , wait a moment");
- m_downloadBreakOffCount = 0;
- }
- else {
- m_downloadBreakOffCount++;
- }
- ScheduleTimer(3,10*1000);//等待下次是否空闲
- }else{
- Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
- ScheduleTimer(3, 10*1000);//等待下次是否空闲
- }
- }
- }
- }else if (event->iEvt == Event_EndQueryTaskStatus){
- QueryTaskStatusEvent* pEvent = (QueryTaskStatusEvent*)event;
- if(pEvent->isSucc){
- if(pEvent->isTask_valid){
- ScheduleTimer(2, 30*1000);//有效,再次查询任务是否有效
- m_bTaskCancel = false;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("query upgradeTask is cancel,set m_bTaskCancel=true");
- m_bTaskCancel = true;//取消下载,结束查询任务是否有效计时器
- }
- }else{
- ScheduleTimer(2, 30*1000);//通讯失败,再次查询任务是否有效
- }
- }else if (event->iEvt == Event_EndDownload){
- DownloadPackTaskEvent* pEvent = (DownloadPackTaskEvent*)event;
- if(pEvent->isSucc){
- if(SetRunConfigStrValue("upgradeTask","PendingState","I")==Error_Succeed){
- //下载成功
- m_currentTask.cPendingState = "I";//改变内存变量为I
- if(m_currentTask.pack_version.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID)("体系外下载成功");
- }else{
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID)("终端版本下载成功");
- }
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartInstall));//进入S5
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndDownload write runinfo is fail,retry in 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new DownloadPackTaskEvent(true));//继续写运行时文件
- }
-
- }else{
- if (m_currentTask.pack_version.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID).setResultCode("RTA5634")("体系外下载失败,通讯报错");
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID).setResultCode("RTA5633")("终端版本下载失败,通讯报错");
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("download pack is fail , wait for 2 min retry download");
- ScheduleTimer(1, 120*1000);//下载失败,等2分钟,再次下载任务
- }
-
- }else if (event->iEvt == Event_Download_Fail){
- DownloadPackTaskFailEvent* pEvent = (DownloadPackTaskFailEvent*)event;
- //写入运行时文件,状态为C
- if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
-
- //告警下载失败
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = pEvent->errMsg.c_str();
- SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID,"RTA5660");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask download is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_Download_Fail write runinfo is fail,retry in 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new DownloadPackTaskFailEvent(pEvent->errMsg));//继续写运行时文件
- }
- }else if (event->iEvt == Event_Download_Idle){
- ScheduleTimer(3,10*1000);//等待下次是否空闲
- }else if (event->iEvt == Event_CancelTask){
- //取消任务,清理任务
- if(ClearCurrTaskInfo()){
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = "任务策略已取消";
- SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID,"RTA5661");
-
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask is cancel,prepare to s3");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry in 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//继续取消任务
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s5_on_entry()
- {
- //停止播放广告和音频
- Task::StopMediaPlayTask* nTask = new Task::StopMediaPlayTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create StopMediaPlayTask fail,err=%d",(int)rc);
- ScheduleTimer(1, 30*1000);//等待30秒再试
- }
- }
- void CUpgradeTaskFSM::s5_on_exit()
- {
- CancelTimer(1);//停止广播和声音计时器
- CancelTimer(2);//解压计时器
- CancelTimer(3);//安装计时器
- CancelTimer(4);//等待跳转切换计时器
- CancelTimer(5);//回退检查计时器
- }
- unsigned int CUpgradeTaskFSM::s5_on_event(FSMEvent* event)
- {
- if(event->iEvt == EVT_TIMER){
- if(event->param1 == 1){
- //再次发起任务查询
- Task::StopMediaPlayTask* nTask = new Task::StopMediaPlayTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create StopMediaPlayTask fail,err=%d",(int)rc);
- ScheduleTimer(1, 30*1000);//等待30秒再停止播放广告和音频
- }
- }else if(event->param1 == 2){
- Task::UnzipPackTask* iTask = new Task::UnzipPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create UnzipPackTask fail,err=%d",(int)rc);
- ScheduleTimer(2, 30*1000);//等待30秒再解压包
- }
- }else if(event->param1 == 3){
- BOOL doInstall = true;
- if(!m_startFlag) //非强制安装
- {
- if (m_currentTask.pack_version.GetLength() == 0) //体系外升级
- {
- CSimpleStringA strState;
- ErrorCodeEnum err = m_pEntity->GetFunction()->GetSysVar("UIState", strState);
- if (err == Error_Succeed && strState != CSimpleStringA("M")) //非主界面不安装
- {
- doInstall = false;
- }
- }
- }
- //对于终端初始化安装时,直接通过。
- if (isTerminalInstall()) {
- doInstall = true;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask terminal new install");
- }
- if (doInstall)
- {
- //解压后判断是什么类型升级
- judgeTaskClass();
- Task::InstallPackTask* iTask = new Task::InstallPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask fail,err=%d", (int)rc);
- ScheduleTimer(3, 30 * 1000);//等待30秒再安装
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 UIState is not M , create InstallPackTask wait for the next time");
- ScheduleTimer(3, 30 * 1000);//等待30秒再安装
- }
- }
- else if (event->param1 == 4) {
- //已安装成功,直接进入切换状态
- DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("s5 create InstallPackTask succ, enter into S6");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
- }
- else if (event->param1 == 5) {
- Task::RollBackCheckTask* iTask = new Task::RollBackCheckTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create RollBackCheckTask fail,err=%d", (int)rc);
- ScheduleTimer(5, 30 * 1000);//等待30秒再次检查
- }
- }
- }
- else if(event->iEvt == Event_EndStopMediaPlayTask){
- StopMediaPlayTaskEvent* pEvent = (StopMediaPlayTaskEvent*)event;
- if(pEvent->isSucc){
- if (m_currentTask.task_type.Compare("U") == 0) {
- //开始解压
- Task::UnzipPackTask* iTask = new Task::UnzipPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create UnzipPackTask fail,err=%d", (int)rc);
- ScheduleTimer(2, 30 * 1000);//等待30秒再解压包
- }
- }
- else if (m_currentTask.task_type.Compare("R") == 0) {
- //回退检查
- Task::RollBackCheckTask* iTask = new Task::RollBackCheckTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create RollBackCheckTask fail,err=%d", (int)rc);
- ScheduleTimer(5, 30 * 1000);//等待30秒再检查
- }
- }
- }else{
- ScheduleTimer(1, 30*1000);//等待30秒再停止播放广告和音频
- }
- }
- else if (event->iEvt == Event_EndUnzipPackTask){
- UnzipPackTaskEvent* pEvent = (UnzipPackTaskEvent*)event;
- if(pEvent->isSucc){
- //开始安装
- BOOL doInstall = true;
- if (!m_startFlag) //非强制安装
- {
- if (m_currentTask.pack_version.GetLength() == 0) //体系外升级
- {
- CSimpleStringA strState;
- ErrorCodeEnum err = m_pEntity->GetFunction()->GetSysVar("UIState", strState);
- if (err == Error_Succeed && strState != CSimpleStringA("M")) //非主界面不安装
- {
- doInstall = false;
- }
- }
- }
- //对于终端初始化安装时,直接通过。
- if (isTerminalInstall()) {
- doInstall = true;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask terminal new install");
- }
- if (doInstall)
- {
- //解压后判断是什么类型升级
- judgeTaskClass();
- Task::InstallPackTask* iTask = new Task::InstallPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask fail,err=%d", (int)rc);
- ScheduleTimer(3, 30 * 1000);//等待30秒再安装
- }
- }
- else{
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 UIState is not M , create InstallPackTask wait for the next time");
- ScheduleTimer(3, 30 * 1000);//等待30秒再安装
- }
- }else{
- if(m_currentTask.stop_media_play){
- //恢复广告和音频播放
- ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
- if(Error_Succeed != rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("unzip fail set UpdateState to 0 fail, err=%d",(int)rc);
- }
- }
- //解压失败,写入运行时文件,状态为C
- if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
-
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = "解压失败";
- SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5662");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("unzip pack is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndUnzipPackTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new UnzipPackTaskEvent(false));//继续写运行时文件
- }
-
- }
- }
- else if (event->iEvt == Event_EndInstallPackTask){
- if(m_currentTask.stop_media_play){
- //恢复广告和音频播放
- ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
- if(Error_Succeed != rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("EndInstallPackTask set UpdateState to 0 fail, err=%d",(int)rc);
- }
- }
- InstallPackTaskEvent* pEvent = (InstallPackTaskEvent*)event;
- if(pEvent->isSucc){
- //安装成功进入切换,设置状态为S和新版本号
- //写入运行时文件
- bool isWriteOk=false;
- while(true){
- if (!m_TempDepUpgradeFlag) {
- if (SetRunConfigStrValue("upgradeTask", "NewVersion", m_currentTask.NewVersion.GetData()) != Error_Succeed) {
- break;
- }
- }
- else {
- if (SetRunConfigStrValue("upgradeTask", "depNewVersion", m_currentTask.depNewVersion.GetData()) != Error_Succeed) {
- break;
- }
- }
- if(SetRunConfigStrValue("upgradeTask","PendingState","S")!=Error_Succeed){
- break;
- }
- isWriteOk=true;
- break;
- }
- if(isWriteOk){
- //告警安装
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if(!m_currentTask.NewVersion.IsNullOrEmpty()){
- up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
- }else if(!m_currentTask.depNewVersion.IsNullOrEmpty()){
- up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
- }else {
- up.installVersion = m_currentVersion.ToString();//当前版本号
- }
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "W";
- up.strInstallComment = "安装成功";
- SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID);
- m_currentTask.cPendingState = "S";//改变内存变量S
- //modify by lwt 修改为非兜底升级时等待一段时间再进入切换状态。
- if (m_startFlag) {
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
- }
- else {
- ScheduleTimer(4, 20 * 1000);//等待20秒再进入切换状态
- }
-
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new InstallPackTaskEvent(true,"",0));//继续写运行时文件
- }
- }else{
- if(pEvent->failStatus==0){
- //安装失败,设置状态为C
- if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
-
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = pEvent->errMsg;//错误信息
- SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5663");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("install pack is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new InstallPackTaskEvent(false,pEvent->errMsg,0));//继续写运行时文件
- }
- }else if(pEvent->failStatus==-1){
- //安装失败,设置状态为X 未知
- if(SetRunConfigStrValue("upgradeTask","PendingState","X")==Error_Succeed){
-
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "X";
- up.strInstallComment = pEvent->errMsg;//错误信息
- SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5664");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("install pack is fail ,prepare to s2");
- m_currentTask.cPendingState = "X";//改变内存变量X
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new InstallPackTaskEvent(false,pEvent->errMsg,-1));//继续写运行时文件
- }
- }
- }
- }
- else if (event->iEvt == Event_EndRollBackCheckTask) {
- if (m_currentTask.stop_media_play) {
- //恢复广告和音频播放
- ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
- if (Error_Succeed != rc) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EndInstallPackTask set UpdateState to 0 fail, err=%d", (int)rc);
- }
- }
- RollBackCheckTaskEvent* pEvent = (RollBackCheckTaskEvent*)event;
- if (pEvent->isSucc) {
- bool isWriteOk = false;
- while (true) {
- if (!m_TempDepUpgradeFlag) {
- if (SetRunConfigStrValue("upgradeTask", "NewVersion", m_currentTask.NewVersion.GetData()) != Error_Succeed) {
- break;
- }
- }
- else {
- if (SetRunConfigStrValue("upgradeTask", "depNewVersion", m_currentTask.depNewVersion.GetData()) != Error_Succeed) {
- break;
- }
- }
- isWriteOk = true;
- break;
- }
- if (isWriteOk) {
- m_currentTask.cPendingState = "S";//改变内存变量S
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查成功");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_EndRollBackCheckTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new RollBackCheckTaskEvent(true, "", ""));//继续写运行时文件
- }
- }
- else {
- //失败
- if (pEvent->failReason.compare("X") != 0) {
- //回退失败,设置状态为C
- if (SetRunConfigStrValue("upgradeTask", "PendingState", "C") == Error_Succeed) {
- //回滚失败取消
- struct CTaskProcess up;
- up.strPackName = "";//安装包名
- up.installVersion = m_currentTask.pack_version;//回退的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = pEvent->errMsg.GetData();//错误信息
- SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID,"RTA5668");
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackCheck is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查失败");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_EndRollBackCheckTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new RollBackCheckTaskEvent(false, pEvent->errMsg, "C"));//继续写运行时文件
- }
- }
- else if (pEvent->failReason.compare("X")==0) {
- //安装失败,设置状态为X 未知
- if (SetRunConfigStrValue("upgradeTask", "PendingState", "X") == Error_Succeed) {
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = "";//安装包名
- up.installVersion = m_currentTask.pack_version;//回退的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "X";
- up.strInstallComment = pEvent->errMsg.GetData();//错误信息
- SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID,"RTA5669");
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackCheck is fail ,prepare to s2");
- m_currentTask.cPendingState = "X";//改变内存变量X
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查失败");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_EndRollBackCheckTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new RollBackCheckTaskEvent(false, pEvent->errMsg, "X"));//继续写运行时文件
- }
- }
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s6_on_entry()
- {
- //进入切换处理流程:不同类型包判断不同
- //时间长,需要判断后台是否取消任务
- if (CheckIfCanSwitchNow())
- {
- ScheduleTimer(2,1000);//进行版本切换操作
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("not applicable time to switch, retry in 20's");
- ScheduleTimer(1, 20*1000);//继续等待
- }
- ScheduleTimer(3, 30*1000);//启动查询任务是否有效
- }
- void CUpgradeTaskFSM::s6_on_exit()
- {
- CancelTimer(1);//判断是否切换时间计时器
- CancelTimer(2);//切换运行时文件写入计时器
- CancelTimer(3);//任务取消计时器
- CancelTimer(4);//切换重启写入active文件计时器
- CancelTimer(5);//active文件写入失败写运行时计时器
- m_bSwitchFlag = false;//切换标志重置。
- }
- unsigned int CUpgradeTaskFSM::s6_on_event(FSMEvent* event)
- {
- if (event->iEvt == EVT_TIMER)
- {
- if(event->param1==1)
- {
- //进入切换处理流程:不同类型包判断不同
- if (CheckIfCanSwitchNow())
- {
- ScheduleTimer(2,1000);//进行版本切换操作
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("not applicable time to switch, retry in 20's");
- ScheduleTimer(1, 20*1000);//继续等待切换时机
- }
- }else if(event->param1==2){
-
- //修改运行时文件状态T
- if(SetRunConfigStrValue("upgradeTask","PendingState","T")==Error_Succeed){
-
- //告警切换
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if (!m_currentTask.NewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
- }else if (!m_currentTask.depNewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
- }else {
- up.installVersion = m_currentVersion.ToString();//当前版本号
- }
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "S";
- up.strInstallComment = "已设为启动版本";
- if (m_currentTask.task_type.Compare("U")==0) {
- SendUpgradeTaskProgress(up,UpgradeMgr_SWTICH_ID);
- }
- else{
- SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_SWTICH_ID);
- }
- m_currentTask.cPendingState = "T";//改变内存变量
- ScheduleTimer(4,5*1000);//等待告警上报,准备修改active文件,进行切换
-
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("switch write runinfo is fail,retry in 10's");
- ScheduleTimer(1, 10*1000);//继续等待下次切换机会再重试
- }
-
- }else if(event->param1==3){
- Task::QueryTaskStatus* dTask = new Task::QueryTaskStatus(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s6 create QueryTaskStatus fail,err=%d",(int)rc);
- ScheduleTimer(3, 30*1000);//再次查询任务是否有效
- }
- }else if(event->param1==4){
- //修改active文件
- if (!m_TempDepUpgradeFlag) {
- if (UpgradeToNewVersion() == Error_Succeed) {
- SwitchUpgradeNow();//切换版本
- }
- else {
- ScheduleTimer(5, 3 * 1000);//UpgradeToNewVersion执行失败后写运行时计时器
- }
- }
- else {
- if (UpgradeDepToNewVersion() == Error_Succeed) {
- SwitchUpgradeDepNow();//适配器切换版本
- }
- else {
- ScheduleTimer(5, 3 * 1000);//UpgradeToDepNewVersion执行失败后写运行时计时器
- }
- }
- }else if(event->param1==5){
-
- if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
- //告警切换失败
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if (!m_currentTask.NewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
- }else if (!m_currentTask.depNewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
- }else {
- up.installVersion = m_currentVersion.ToString();//当前版本号
- }
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = "更新active文件失败";//错误信息
- if (m_currentTask.task_type.Compare("U")==0) {
- SendUpgradeTaskProgress(up,UpgradeMgr_SWTICH_ID,"RTA5665");
- }
- else {
- SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_SWTICH_ID, "RTA5670");
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("UpgradeToNewVersion is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("UpgradeToNewVersion fail, write runinfo is fail,retry in 10's");
- ScheduleTimer(5,10*1000);//继续重试写入运行时
- }
- }
- }else if (event->iEvt == Event_EndQueryTaskStatus){
- QueryTaskStatusEvent* pEvent = (QueryTaskStatusEvent*)event;
- if(pEvent->isSucc){
- if(pEvent->isTask_valid){
- ScheduleTimer(3, 30*1000);//有效,再次查询任务是否有效
- }else{
- //无效,清理任务
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("query upgradeTask is cancel");
- if(ClearCurrTaskInfo()){
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = "任务策略已取消";
- if (m_currentTask.task_type.Compare("U")==0) {
- SendUpgradeTaskProgress(up, UpgradeMgr_SWTICH_ID,"RTA5666");
- }
- else {
- SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_SWTICH_ID, "RTA5671");
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask is cancel,prepare to s3");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry in 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new QueryTaskStatusEvent(true,false));//继续取消任务
- }
- }
- }else{
- ScheduleTimer(3, 30*1000);//通讯失败,再次查询任务是否有效
- }
- }
-
- return 0;
- }
- void CUpgradeTaskFSM::s7_on_entry()
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("enter disable state , wait framework restart or OS restart");
- }
- void CUpgradeTaskFSM::s7_on_exit()
- {
- }
- unsigned int CUpgradeTaskFSM::s7_on_event(FSMEvent* event)
- {
- return 0;
- }
|