UpgradeTaskFSM.cpp 290 KB

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