UpgradeTaskFSM.cpp 295 KB

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