UpgradeTaskFSM.cpp 289 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486
  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 "res", strCurVerPath.GetData());
  1626. strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "res", strNewVerPath.GetData());
  1627. // 检测res目录是否存在
  1628. if (ExistsDirA(strSource))
  1629. {
  1630. if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
  1631. {
  1632. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy res dir fail");
  1633. strErrInfo = CSimpleStringA::Format("copy res dir fail: %s", strErrMsg.GetData());
  1634. return Error_Unexpect;
  1635. }
  1636. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy res dir succ");
  1637. }
  1638. else
  1639. {
  1640. if (!CreateDirA(strDest, TRUE))
  1641. {
  1642. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create res dir fail");
  1643. strErrInfo = "create res dir fail";
  1644. return Error_Unexpect;
  1645. }
  1646. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create res dir succ");
  1647. }
  1648. strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "imdep", strCurVerPath.GetData());
  1649. strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "imdep", strNewVerPath.GetData());
  1650. // 检测imdep目录是否存在
  1651. if (ExistsDirA(strSource))
  1652. {
  1653. if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
  1654. {
  1655. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy imdep dir fail");
  1656. strErrInfo = CSimpleStringA::Format("copy imdep dir fail: %s", strErrMsg.GetData());
  1657. return Error_Unexpect;
  1658. }
  1659. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy imdep dir succ");
  1660. }
  1661. else
  1662. {
  1663. if (!CreateDirA(strDest, TRUE))
  1664. {
  1665. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create imdep dir fail");
  1666. strErrInfo = "create imdep dir fail";
  1667. return Error_Unexpect;
  1668. }
  1669. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create imdep dir succ");
  1670. }
  1671. return Error_Succeed;
  1672. }
  1673. ErrorCodeEnum CUpgradeTaskFSM::ClearUpgradeFailVersion(CVersion NewSoftwareVersion)
  1674. {
  1675. CSimpleStringA rootVerPath;
  1676. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
  1677. if(rc!=Error_Succeed){
  1678. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion fail , get RootVer path is fail");
  1679. return Error_Bug;
  1680. }
  1681. CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), NewSoftwareVersion.ToString().GetData());
  1682. if (ExistsDirA(strNewVerPath.GetData()))
  1683. {
  1684. if(!RemoveDirRecursiveA(strNewVerPath.GetData())){
  1685. #ifdef RVC_OS_WIN
  1686. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion fail, delete temp Version [%s] is fail:%d",strNewVerPath.GetData(),(int)GetLastError());
  1687. #else
  1688. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), errno);
  1689. #endif
  1690. return Error_Bug;
  1691. }else{
  1692. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion succ, delete temp Version [%s] ", strNewVerPath.GetData());
  1693. return Error_Succeed;
  1694. }
  1695. }else{
  1696. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion succ, delete temp Version [%s] is not exsit ", strNewVerPath.GetData());
  1697. return Error_Succeed;
  1698. }
  1699. }
  1700. // result.log 文件内容: result=0&msg=install ok
  1701. bool CUpgradeTaskFSM::GetSysUpgradeResult(const char *pszResultLog, CSimpleStringA &eErrorCode, CSimpleStringA &strErrMsg)
  1702. {
  1703. // 设置初始值
  1704. //eErrorCode = Error_Succeed;
  1705. strErrMsg = "";
  1706. if (!ExistsFileA(pszResultLog))
  1707. {
  1708. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult result log [%s] not exist", pszResultLog);
  1709. strErrMsg = "result.log not exist";
  1710. eErrorCode = "0";
  1711. return true;//???有些外部程序不一定会产生日志文件,故默认不产生文件,认为是成功
  1712. }
  1713. FILE *pResultLog = fopen(pszResultLog, "r");
  1714. if (pResultLog == NULL)
  1715. {
  1716. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult open result log [%s] fail", pszResultLog);
  1717. strErrMsg = "open result.log fail";
  1718. return false;
  1719. }
  1720. char szTmp[4096] = {};
  1721. int nRead = fread_s(szTmp, sizeof(szTmp), 1, sizeof(szTmp), pResultLog);
  1722. CSimpleStringA strResult = szTmp;
  1723. fclose(pResultLog);
  1724. pResultLog = NULL;
  1725. auto arr = strResult.Split('&');
  1726. if(arr.GetCount()!=2){
  1727. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult read result log format fail,[%s]", strResult.GetData());
  1728. strErrMsg = "read result.log format fail,eg result=0&msg=install ok";
  1729. return false;
  1730. }
  1731. for (int i = 0; i < arr.GetCount(); i++)
  1732. {
  1733. auto arr2 = arr[i].Split('=');
  1734. if (arr2.GetCount() == 2)
  1735. {
  1736. #ifdef RVC_OS_WIN
  1737. if (stricmp(arr2[0], "result") == 0)
  1738. eErrorCode = arr2[1];
  1739. else if (stricmp(arr2[0], "msg") == 0)
  1740. strErrMsg = arr2[1];
  1741. #else
  1742. if (strcmp(arr2[0], "result") == 0)
  1743. eErrorCode = arr2[1];
  1744. else if (strcmp(arr2[0], "msg") == 0)
  1745. strErrMsg = arr2[1];
  1746. #endif
  1747. }
  1748. }
  1749. return true;
  1750. }
  1751. int CUpgradeTaskFSM::ExecInstall(CSimpleStringA &strErrMsg)
  1752. {
  1753. //判断是否需要生成新版本
  1754. if(!m_currentTask.pack_version.IsNullOrEmpty()){
  1755. CSimpleStringA strUpgradeVersion = m_currentTask.pack_version;
  1756. CVersion latterVersion;//要更新到的版本号
  1757. CVersion curVer = m_currentVersion;//当前版本号
  1758. // 指定版本
  1759. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  1760. int n = sscanf(strUpgradeVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  1761. if (n != 4)
  1762. {
  1763. strErrMsg = CSimpleStringA::Format("指定升级版本号无效(%s)", strUpgradeVersion.GetData());
  1764. LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_INSTALL_VERSION_FAIL, CSimpleStringA::Format("specified software version is invalid: [%s]", strUpgradeVersion.GetData()).GetData());
  1765. return 0;
  1766. }else{
  1767. latterVersion = CVersion(dwMajor, dwMinor, dwRevision, dwBuild);
  1768. }
  1769. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("latterVersion :%s",latterVersion.ToString().GetData());
  1770. if(curVer.ToString()==strUpgradeVersion){
  1771. //版本号相同,
  1772. strErrMsg = CSimpleStringA::Format("指定升级版本号与当前版本相同,无效(配置:%s, 当前:%s)", strUpgradeVersion.GetData(),curVer.ToString().GetData());
  1773. return 0;
  1774. //}else if(m_currentVersion.ToString().Compare(strUpgradeVersion)==1){
  1775. //字符串比较版本号大小改为整形数字对比
  1776. }else if(dwMajor < curVer.GetMajor()
  1777. || (dwMajor == curVer.GetMajor() && dwMinor < curVer.GetMinor())
  1778. || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision < curVer.GetRevision())
  1779. || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision == curVer.GetRevision() && dwBuild < curVer.GetBuild())){
  1780. //升级版本小于当前版本
  1781. strErrMsg = CSimpleStringA::Format("指定升级版本号无效(配置:%s,解析:%s,当前:%s)", strUpgradeVersion.GetData(),latterVersion.ToString().GetData(),curVer.ToString().GetData());
  1782. return 0;
  1783. }
  1784. //判断是否需要创建新版本
  1785. CSimpleStringA strErrInfo = "";
  1786. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateNewVersion,version[%s],pack[%s]",strUpgradeVersion.GetData(),m_currentTask.pack_name.GetData());
  1787. ErrorCodeEnum rc = CreateNewVersion(latterVersion,strErrInfo);
  1788. if (rc != Error_Succeed)
  1789. {
  1790. strErrMsg = CSimpleStringA::Format("CreateNewVersion fail:%s",strErrInfo.GetData());
  1791. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewVersion,version[%s] fail:%s",strUpgradeVersion.GetData(),strErrInfo.GetData());
  1792. //清理临时版本文件夹
  1793. ClearUpgradeFailVersion(latterVersion);
  1794. return 0;
  1795. }else{
  1796. m_currentTask.NewVersion = strUpgradeVersion;//赋值升级版本号给内存变量
  1797. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewVersion,version[%s] succ",strUpgradeVersion.GetData());
  1798. }
  1799. }
  1800. //循环执行安装命令
  1801. int iRet=1;//默认是成功
  1802. if(!m_currentTask.install_step.empty()){
  1803. int iCount = m_currentTask.install_step.size();
  1804. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d",iCount);
  1805. for (int j = 0; j < iCount; j++){
  1806. CInstallStep* tmp = m_currentTask.install_step.front();
  1807. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====begin cmd=[%s]=====",tmp->cmdType.GetData());
  1808. //开始处理具体命令
  1809. if(tmp->cmdType=="Delete"){
  1810. bool ret = ExecDeleteCmd(strErrMsg,tmp);
  1811. if(!ret){
  1812. //报错才判断
  1813. if(tmp->cmdFail == 0 ){
  1814. iRet = 0;
  1815. break;//出错直接退出
  1816. }else if(tmp->cmdFail == 1 ){
  1817. //继续
  1818. }else{
  1819. iRet = 0;
  1820. break;//其他值也退出
  1821. }
  1822. }
  1823. }else if(tmp->cmdType=="Copy"){
  1824. bool ret = ExecCpoyCmd(strErrMsg,tmp);
  1825. if(!ret){
  1826. //报错才判断
  1827. if(tmp->cmdFail == 0){
  1828. iRet = 0;
  1829. break;//出错直接退出
  1830. }else if(tmp->cmdFail == 1){
  1831. //继续
  1832. }else{
  1833. iRet = 0;
  1834. break;//其他值也退出
  1835. }
  1836. }
  1837. }else if(tmp->cmdType=="Run"){
  1838. int retInt = ExecRunCmd(strErrMsg,tmp);
  1839. if(retInt==0||retInt==-1){
  1840. //报错才判断
  1841. if(tmp->cmdFail == 0 ){
  1842. iRet = retInt;//会有0,-1值
  1843. break;//出错直接退出,并返回体系外结果
  1844. }else if(tmp->cmdFail == 1 ){
  1845. //继续
  1846. }else{
  1847. iRet = 0;
  1848. break;//其他值也退出
  1849. }
  1850. }
  1851. }else{
  1852. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cmd=[%s] is invalid",tmp->cmdType.GetData());
  1853. iRet = 0;
  1854. break;//命令无效直接退出
  1855. }
  1856. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====end cmd=[%s]=====",tmp->cmdType.GetData());
  1857. m_currentTask.install_step.pop();//去除元素
  1858. delete tmp;//删除内存
  1859. }
  1860. }
  1861. return iRet;//返回处理结果
  1862. }
  1863. int CUpgradeTaskFSM::ExecRunCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
  1864. {
  1865. CSimpleStringA destPath ;//目的路径
  1866. if(ins->dstPathType=="0"){
  1867. CSimpleStringA rootPath;
  1868. if(GetRootTypePath(1,rootPath)){
  1869. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
  1870. }else{
  1871. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 1 is fail");
  1872. return false;
  1873. }
  1874. }else if(ins->dstPathType=="1"){
  1875. destPath = ins->dstPath;//绝对路径
  1876. }else if(ins->dstPathType=="2"){
  1877. CSimpleStringA rootPath;
  1878. if(GetRootTypePath(2,rootPath)){
  1879. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
  1880. }else{
  1881. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 2 is fail");
  1882. return false;
  1883. }
  1884. }else if(ins->dstPathType=="3"){
  1885. CSimpleStringA rootPath;
  1886. if(GetRootTypePath(3,rootPath)){
  1887. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
  1888. }else{
  1889. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 3 is fail");
  1890. return false;
  1891. }
  1892. }else if(ins->dstPathType=="4"){
  1893. CSimpleStringA rootPath;
  1894. if(GetRootTypePath(4,rootPath)){
  1895. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级包相对路径
  1896. }else{
  1897. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 4 is fail");
  1898. return false;
  1899. }
  1900. }else{
  1901. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPathType is invalid %s",ins->dstPathType.GetData());
  1902. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPathType is invalid %s",ins->dstPathType.GetData());
  1903. return false;//不支持的路径类型
  1904. }
  1905. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPath is %s",destPath.GetData());
  1906. // ToRun=install.bat
  1907. if (ExistsFileA(destPath.GetData()))
  1908. {
  1909. #ifdef RVC_OS_WIN
  1910. // window模式下 如果是Wow64模式,需屏蔽System32重定向
  1911. PVOID pRedirectOldValue(NULL);
  1912. bool bIsWow64 = IsWow64Process();
  1913. if (bIsWow64)
  1914. {
  1915. if (!Wow64DisableWow64FsRedirection(&pRedirectOldValue)){
  1916. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64DisableWow64FsRedirection fail: %d", GetLastError());
  1917. }else{
  1918. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64DisableWow64FsRedirection succ");
  1919. }
  1920. }
  1921. #endif
  1922. //system(strSourcePath);
  1923. string sysPathStr = destPath.GetData();
  1924. CSimpleStringA err ="";
  1925. int ret = system_on(sysPathStr,true,err);
  1926. #ifdef RVC_OS_WIN
  1927. // 如果是Wow64模式,恢复System32重定向
  1928. if (bIsWow64)
  1929. {
  1930. if (!Wow64RevertWow64FsRedirection(pRedirectOldValue)){
  1931. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64RevertWow64FsRedirection fail: %d", GetLastError());
  1932. }else{
  1933. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64RevertWow64FsRedirection succ");
  1934. }
  1935. }
  1936. #endif
  1937. if(ret!=0){
  1938. //程序执行异常,结果未知
  1939. #ifdef RVC_OS_WIN
  1940. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown ,err=%s",err.GetData());
  1941. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ,err=%s",err.GetData());
  1942. #else
  1943. DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown , ret=%d, err=%s",ret, strerror(errno));
  1944. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ret=%d, err=%s", ret, strerror(errno));
  1945. #endif
  1946. return -1;//未知结果返回
  1947. }else{
  1948. //进一步看返回结果文件判断是否成功
  1949. CSimpleStringA strUnzipPath = GetFileDirectory(destPath.GetData());
  1950. #ifdef RVC_OS_WIN
  1951. CSimpleStringA strResultLog = strUnzipPath + "\\result.log";//结果文件
  1952. #else
  1953. CSimpleStringA strResultLog = strUnzipPath + "/result.log";//结果文件
  1954. #endif
  1955. CSimpleStringA eErrorCode = "";
  1956. //获取结果文件
  1957. if (!GetSysUpgradeResult(strResultLog, eErrorCode, strErrMsg))
  1958. {
  1959. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, get result from result.log fail, %s", strErrMsg.GetData());
  1960. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail ,get result from result.log fail, %s", strErrMsg.GetData());
  1961. return 0;//失败
  1962. }
  1963. if (eErrorCode == "0")
  1964. {
  1965. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is succ,[%s] ", destPath.GetData());
  1966. return 1;//成功
  1967. }else{
  1968. #ifdef RVC_OS_WIN
  1969. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
  1970. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
  1971. #else
  1972. DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
  1973. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
  1974. #endif
  1975. return 0;//失败
  1976. }
  1977. }
  1978. }
  1979. else
  1980. {
  1981. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, run file [%s] is not Exist",destPath.GetData());
  1982. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, run file [%s] is not Exist",destPath.GetData());
  1983. return 0;//失败
  1984. }
  1985. }
  1986. bool CUpgradeTaskFSM::ExecDeleteCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
  1987. {
  1988. //只删除同一层目录下的文件和文件夹
  1989. CSimpleStringA destPath ;//目的路径+通配符
  1990. if(ins->dstPathType=="0"){
  1991. CSimpleStringA rootPath;
  1992. if(GetRootTypePath(1,rootPath)){
  1993. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
  1994. }else{
  1995. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 1 is fail");
  1996. return false;
  1997. }
  1998. }else if(ins->dstPathType=="1"){
  1999. destPath = ins->dstPath;//绝对路径
  2000. }else if(ins->dstPathType=="2"){
  2001. CSimpleStringA rootPath;
  2002. if(GetRootTypePath(2,rootPath)){
  2003. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
  2004. }else{
  2005. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 2 is fail");
  2006. return false;
  2007. }
  2008. }else if(ins->dstPathType=="3"){
  2009. CSimpleStringA rootPath;
  2010. if(GetRootTypePath(3,rootPath)){
  2011. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
  2012. }else{
  2013. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 3 is fail");
  2014. return false;
  2015. }
  2016. }else{
  2017. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPathType is invalid %s",ins->dstPathType.GetData());
  2018. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPathType is invalid %s",ins->dstPathType.GetData());
  2019. return false;//不支持的路径类型
  2020. }
  2021. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPath is %s",destPath.GetData());
  2022. if(destPath.IndexOf("*")>0){
  2023. CSimpleStringA strFileFilter = _GetFileName(destPath);
  2024. CSimpleStringA strDestDir = destPath.SubString(0, destPath.GetLength()-strFileFilter.GetLength()-1);
  2025. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match filter name [%s] in dir [%s]", strFileFilter.GetData(), strDestDir.GetData());
  2026. // 删除所有匹配文件
  2027. bool bRet = true;
  2028. auto arr = fileutil_get_sub_files(strDestDir.GetData());
  2029. if (arr != NULL)
  2030. {
  2031. for (int i = 0; i < arr->nelts; ++i)
  2032. {
  2033. char *file = ARRAY_IDX(arr, i, char*);
  2034. if (IsFileMatch(strFileFilter, _GetFileName(file)))
  2035. {
  2036. if(RemoveFileA(file)){
  2037. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", file);
  2038. }else{
  2039. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", file);
  2040. strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", file);
  2041. bRet = false;
  2042. break;
  2043. }
  2044. }
  2045. else
  2046. {
  2047. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match file: [%s]", file);
  2048. }
  2049. }
  2050. toolkit_array_free2(arr);
  2051. if(!bRet){
  2052. return bRet;
  2053. }
  2054. }
  2055. // 删除所有匹配子目录
  2056. auto subdirs = fileutil_get_sub_dirs(strDestDir.GetData());
  2057. if (subdirs != NULL)
  2058. {
  2059. for (int i = 0; i < subdirs->nelts; ++i)
  2060. {
  2061. const char *dir = ARRAY_IDX(subdirs, i, char*);
  2062. if (IsFileMatch(strFileFilter, _GetFileName(dir)))
  2063. {
  2064. if(RemoveDirRecursive(dir)){
  2065. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", dir);
  2066. }else{
  2067. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", dir);
  2068. strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", dir);
  2069. bRet = false;
  2070. break;
  2071. }
  2072. }
  2073. else
  2074. {
  2075. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match dir: [%s]", dir);
  2076. }
  2077. }
  2078. toolkit_array_free2(subdirs);
  2079. if(!bRet){
  2080. return bRet;
  2081. }
  2082. }
  2083. return bRet;
  2084. }else{
  2085. //直接删除文件
  2086. bool bRet = true;
  2087. if (ExistsFileA(destPath.GetData()))
  2088. {
  2089. if(RemoveFileA(destPath.GetData())){
  2090. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", destPath.GetData());
  2091. }else{
  2092. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", destPath.GetData());
  2093. strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", destPath.GetData());
  2094. bRet = false;
  2095. }
  2096. return bRet;
  2097. }
  2098. else if (ExistsDirA(destPath.GetData()))
  2099. {
  2100. if(RemoveDirRecursiveA(destPath.GetData())){
  2101. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", destPath.GetData());
  2102. }else{
  2103. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", destPath.GetData());
  2104. strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", destPath.GetData());
  2105. bRet = false;
  2106. }
  2107. return bRet;
  2108. }
  2109. else
  2110. {
  2111. //指定文件不再则忽略删除此文件
  2112. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file [%s] not exists,ignore delete file", destPath.GetData());
  2113. return bRet;
  2114. }
  2115. }
  2116. }
  2117. bool CUpgradeTaskFSM::ExecCpoyCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
  2118. {
  2119. CSimpleStringA sourcePath ;//路径+通配符
  2120. if(ins->srcPathType=="0"){
  2121. CSimpleStringA rootPath="";
  2122. if(GetRootTypePath(1,rootPath)){
  2123. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//相对路径
  2124. }else{
  2125. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 1 is fail");
  2126. return false;
  2127. }
  2128. }else if(ins->srcPathType=="1"){
  2129. sourcePath = ins->srcPath;//绝对路径
  2130. }else if(ins->srcPathType=="2"){
  2131. CSimpleStringA rootPath="";
  2132. if(GetRootTypePath(2,rootPath)){
  2133. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//当前版本相对路径
  2134. }else{
  2135. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 2 is fail");
  2136. return false;
  2137. }
  2138. }else if(ins->srcPathType=="3"){
  2139. CSimpleStringA rootPath="";
  2140. if(GetRootTypePath(4,rootPath)){
  2141. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//升级包相对路径
  2142. }else{
  2143. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 4 is fail");
  2144. return false;
  2145. }
  2146. }else{
  2147. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd srcPathType is invalid %s",ins->srcPathType.GetData());
  2148. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd srcPathType is invalid %s",ins->srcPathType.GetData());
  2149. return false;//不支持的路径类型
  2150. }
  2151. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd sourcePath is %s",sourcePath.GetData());
  2152. CSimpleStringA destPath ;//目的路径文件夹
  2153. if(ins->dstPathType=="0"){
  2154. CSimpleStringA rootPath="";
  2155. if(GetRootTypePath(1,rootPath)){
  2156. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
  2157. }else{
  2158. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 1 is fail");
  2159. return false;
  2160. }
  2161. }else if(ins->dstPathType=="1"){
  2162. destPath = ins->dstPath;//绝对路径
  2163. }else if(ins->dstPathType=="2"){
  2164. CSimpleStringA rootPath="";
  2165. if(GetRootTypePath(2,rootPath)){
  2166. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
  2167. }else{
  2168. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 2 is fail");
  2169. return false;
  2170. }
  2171. }else if(ins->dstPathType=="3"){
  2172. CSimpleStringA rootPath="";
  2173. if(GetRootTypePath(3,rootPath)){
  2174. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
  2175. }else{
  2176. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 3 is fail");
  2177. return false;
  2178. }
  2179. //}else if(ins->dstPathType=="4"){
  2180. // CSimpleStringA rootPath="";
  2181. // if(GetRootTypePath(4,rootPath)){
  2182. // destPath = CSimpleStringA::Format("%s\\%s",rootPath.GetData(),ins->dstPath.GetData());//升级包相对路径
  2183. // }else{
  2184. // strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 4 is fail");
  2185. // return false;
  2186. // }
  2187. }else{
  2188. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd dstPathType is invalid %s",ins->dstPathType.GetData());
  2189. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd dstPathType is invalid %s",ins->dstPathType.GetData());
  2190. return false;//不支持的路径类型
  2191. }
  2192. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd destPath is %s",destPath.GetData());
  2193. if(sourcePath.IndexOf("*")>0){
  2194. //循环匹配拷贝
  2195. //找到要扫描的文件夹
  2196. CSimpleStringA strFileDir = GetFileDirectory(sourcePath.GetData());
  2197. //过滤通配条件
  2198. CSimpleStringA strFileFilter = _GetFileName(sourcePath.GetData());
  2199. list<CSimpleStringA> fileList;
  2200. //获取所有根文件夹下的文件相对路径:如mod\test.dll
  2201. RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
  2202. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find fileList =%d",fileList.size());
  2203. if(fileList.size()==0){
  2204. //判断mod文件夹未空则报错
  2205. if(sourcePath.IndexOf("mod")!=-1){
  2206. LogWarn(Severity_Low, Error_Exception, WARN_TASK_COPY_FILE_ZERO,CSimpleStringA::Format("ExecCpoyCmd sourcePath is [%s] file is 0",sourcePath.GetData()));
  2207. }
  2208. }
  2209. for(auto it = fileList.begin(); it != fileList.end(); it++)
  2210. {
  2211. if (IsFileMatch(strFileFilter, _GetFileName((const char*)(*it))))
  2212. {
  2213. CSimpleStringA strSrcName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", GetFileDirectory(sourcePath.GetData()).GetData(), (const char*)(*it));//源文件路径
  2214. CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(),(const char*)(*it));//目标文件路径
  2215. //匹配成功,开始拷贝文件
  2216. CSimpleStringA errMsg = "";
  2217. ErrorCodeEnum rc = CopyFileOperate(strSrcName.GetData(),strDestName.GetData(),3,errMsg);
  2218. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] to [%s] %s", strSrcName.GetData(),strDestName.GetData(), rc == Error_Succeed ? "succeed" : "fail");
  2219. if (rc != Error_Succeed)
  2220. {
  2221. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail: %s",strSrcName.GetData(),errMsg.GetData());
  2222. strErrMsg = CSimpleStringA::Format("copy file [%s] fail: %s",strSrcName.GetData(),errMsg.GetData());
  2223. return false;//报错
  2224. }
  2225. }
  2226. }
  2227. }else{
  2228. //直接拷贝文件:考虑有些文件因智能对比不一定下发,故如果文件不存在,则默认忽略此策略
  2229. CSimpleStringA errMsg = "";
  2230. CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), _GetFileName(sourcePath.GetData()));
  2231. if(ExistsFileA(sourcePath.GetData())){
  2232. ErrorCodeEnum rc = CopyFileOperate(sourcePath.GetData(),strDestName.GetData(),3,errMsg);
  2233. if (rc != Error_Succeed)
  2234. {
  2235. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:%s",sourcePath.GetData(),errMsg.GetData());
  2236. strErrMsg = CSimpleStringA::Format("copy file [%s] fail:%s",sourcePath.GetData(),errMsg.GetData());
  2237. return false;//报错
  2238. }
  2239. }else{
  2240. if(ins->srcPathType=="3"){
  2241. //升级包因智能升级不一定有指定的文件存在
  2242. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("拷贝指定的文件[%s]不存在,因智能升级对比过滤,故忽略此文件拷贝",sourcePath.GetData());
  2243. }else{
  2244. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:file to copy not exist",sourcePath.GetData());
  2245. strErrMsg = CSimpleStringA::Format("copy file [%s] fail:file to copy not exist",sourcePath.GetData());
  2246. return false;//报错
  2247. }
  2248. }
  2249. }
  2250. return true;
  2251. }
  2252. bool CUpgradeTaskFSM::GetRootTypePath(int rootType,CSimpleStringA &Path)
  2253. {
  2254. CSimpleStringA tempPath;
  2255. if (rootType == 1) {
  2256. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Root", tempPath);//例如:C:\Run /opt/Run
  2257. if (Error_Succeed == Error) {
  2258. if (!tempPath.IsNullOrEmpty()) {
  2259. string runPathStr = tempPath.GetData();
  2260. int pos = runPathStr.find_last_of(SPLIT_SLASH);
  2261. Path = runPathStr.substr(0, pos).c_str();
  2262. }
  2263. else {
  2264. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is null");
  2265. return false;
  2266. }
  2267. }
  2268. else {
  2269. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is error");
  2270. return false;
  2271. }
  2272. }
  2273. else if (rootType == 2) {
  2274. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Base", tempPath);//例如:C:\Run\version\4.8.1.1 /opt/Run/version/4.8.1.1
  2275. if (Error_Succeed == Error) {
  2276. if (!tempPath.IsNullOrEmpty()) {
  2277. Path = tempPath;
  2278. }
  2279. else {
  2280. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currVer path is null");
  2281. return false;
  2282. }
  2283. }
  2284. else {
  2285. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currVer path is error");
  2286. return false;
  2287. }
  2288. }
  2289. else if (rootType == 3) {
  2290. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", tempPath);//例如:C:\Run\version\4.9.1.1 /opt/Run/version/4.9.1.1
  2291. if (Error_Succeed == Error) {
  2292. if (!tempPath.IsNullOrEmpty()) {
  2293. Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
  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 upgradeVer path is error");
  2302. return false;
  2303. }
  2304. }
  2305. else if (rootType == 4) {
  2306. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Downloads", tempPath);//例如:C:\rvc\Downloads\4.8.1.1 /opt/rvc/Downloads/4.8.1.1
  2307. if (Error_Succeed == Error) {
  2308. if (!tempPath.IsNullOrEmpty()) {
  2309. CSimpleStringA strUnzipDir;
  2310. strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_name.GetData());
  2311. //解压去除了.zip后缀
  2312. if (strUnzipDir.IsEndWith(".zip")) {
  2313. Path = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  2314. }
  2315. else {
  2316. Path = strUnzipDir;
  2317. }
  2318. }
  2319. else {
  2320. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is null");
  2321. return false;
  2322. }
  2323. }
  2324. else {
  2325. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is error");
  2326. return false;
  2327. }
  2328. }
  2329. return true;
  2330. }
  2331. ErrorCodeEnum CUpgradeTaskFSM::CopyFileOperate(const char* srcPath, const char* destPath, int nCopyMode, CSimpleStringA &strErrMsg)
  2332. {
  2333. //源文件是否存在
  2334. if (!ExistsFileA(srcPath))
  2335. {
  2336. strErrMsg = CSimpleStringA::Format("CopyFileOperate file [%s] to copy not exist", srcPath);
  2337. return Error_NotExist;
  2338. }
  2339. //目标文件夹是否存在
  2340. CSimpleStringA strDestDir = GetFileDirectory(destPath);
  2341. if (!ExistsDirA(strDestDir.GetData())){
  2342. if(!CreateDirA(strDestDir.GetData(), TRUE)){
  2343. strErrMsg = CSimpleStringA::Format("CopyFileOperate create strDestDir[%s] fail", strDestDir.GetData());
  2344. return Error_Exception;
  2345. }
  2346. }
  2347. //目标文件是否存在
  2348. BOOL bDestFileExists = ExistsFileA(destPath);
  2349. if (bDestFileExists){
  2350. RemoveFileReadOnlyAttributeA(destPath);
  2351. }
  2352. BOOL bRet = TRUE;
  2353. switch (nCopyMode)
  2354. {
  2355. case 1:
  2356. {
  2357. if (bDestFileExists) {
  2358. #ifdef RVC_OS_WIN
  2359. bRet = CopyFileA(srcPath, destPath, FALSE);
  2360. #else
  2361. if (fileutil_copy_file(destPath, srcPath) == 0) {
  2362. bRet = TRUE;
  2363. }
  2364. else {
  2365. bRet = FALSE;
  2366. }
  2367. #endif
  2368. }
  2369. else {
  2370. LOG_TRACE("ignore file [%s] copy for dest file not exists", srcPath);
  2371. }
  2372. }
  2373. break;
  2374. case 2:
  2375. {
  2376. if (!bDestFileExists)
  2377. #ifdef RVC_OS_WIN
  2378. bRet = CopyFileA(srcPath, destPath, TRUE);
  2379. #else
  2380. if (fileutil_copy_file(destPath, srcPath) == 0) {
  2381. bRet = TRUE;
  2382. }
  2383. else {
  2384. bRet = FALSE;
  2385. }
  2386. #endif
  2387. else
  2388. LOG_TRACE("ignore file [%s] copy for dest file exists", srcPath);
  2389. }
  2390. break;
  2391. case 3:
  2392. #ifdef RVC_OS_WIN
  2393. bRet = CopyFileA(srcPath, destPath, FALSE);
  2394. #else
  2395. if (fileutil_copy_file(destPath, srcPath) == 0) {
  2396. bRet = TRUE;
  2397. }
  2398. else {
  2399. bRet = FALSE;
  2400. }
  2401. #endif
  2402. break;
  2403. case 4:
  2404. {
  2405. // 不发生拷贝,只进行判断
  2406. if(bDestFileExists)
  2407. LOG_TRACE("file [%s] exist", srcPath);
  2408. else
  2409. LOG_TRACE("file [%s] not exist", srcPath);
  2410. }
  2411. break;
  2412. }
  2413. if (bRet){
  2414. RemoveFileReadOnlyAttributeA(destPath);
  2415. }else{
  2416. #ifdef RVC_OS_WIN
  2417. strErrMsg = CSimpleStringA::Format("CopyFileOperate copy file fail:%d", GetLastError());
  2418. #else
  2419. strErrMsg = CSimpleStringA::Format("CopyFileOperate copy file fail:%d", errno);
  2420. #endif
  2421. }
  2422. ErrorCodeEnum rc = bRet ? Error_Succeed : Error_Unexpect;
  2423. return rc;
  2424. }
  2425. ErrorCodeEnum CUpgradeTaskFSM::SetRunSucceed(const char* pPackFile)
  2426. {
  2427. // 拷贝升级包到Upgraded目录
  2428. CSimpleStringA strDownloadPath, strUpgradedPath;
  2429. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadPath);
  2430. if(rc!=Error_Succeed){
  2431. return rc;
  2432. }
  2433. rc = m_pEntity->GetFunction()->GetPath("Upgraded", strUpgradedPath);
  2434. if(rc!=Error_Succeed){
  2435. return rc;
  2436. }
  2437. CSimpleStringA strSourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strDownloadPath, pPackFile);
  2438. CSimpleStringA strDestPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strUpgradedPath, pPackFile);
  2439. #ifdef RVC_OS_WIN
  2440. CopyFileA(strSourcePath.GetData(), strDestPath.GetData(), FALSE);
  2441. #else
  2442. fileutil_copy_file(strDestPath.GetData(), strSourcePath.GetData());
  2443. #endif
  2444. return Error_Succeed;
  2445. }
  2446. ErrorCodeEnum CUpgradeTaskFSM::UpgradeToNewVersion()
  2447. {
  2448. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin UpgradeToNewVersion");
  2449. //获取新版本号
  2450. if(m_currentTask.NewVersion.IsNullOrEmpty()){
  2451. if(m_currentTask.pack_version.IsNullOrEmpty()){
  2452. return Error_Succeed;
  2453. }else{
  2454. 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());
  2455. 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());
  2456. return Error_Unexpect;//这种情况有问题,需要清除此任务
  2457. }
  2458. }else{
  2459. CSimpleStringA rootVerPath;
  2460. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
  2461. if(rc!=Error_Succeed){
  2462. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpgradeToNewVersion fail , get RootVer path is fail");
  2463. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,"UpgradeToNewVersion: get RootVer path is fail");
  2464. return Error_Bug;
  2465. }
  2466. CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.NewVersion.GetData());
  2467. if(!ExistsDirA(strNewVerPath.GetData())){
  2468. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, strNewVerPath =%s is not exist,fail",strNewVerPath.GetData()).GetData());
  2469. return Error_Unexpect;//这种情况有问题,需要清除此任务
  2470. }
  2471. //修改运行时文件
  2472. //修改active配置
  2473. CSimpleStringA strActiveFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "active.txt", rootVerPath.GetData());
  2474. if(!ExistsFileA(strActiveFile.GetData())){
  2475. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail,active file is not exist");
  2476. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,"UpgradeToNewVersion fail, active file is not exist");
  2477. return Error_Unexpect;
  2478. }
  2479. //先做active文件备份,后面写入失败再copy回去
  2480. #ifdef RVC_OS_WIN
  2481. bool backupSucc = true;
  2482. CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\back_active.txt", rootVerPath.GetData());
  2483. if(!CopyFileA(strActiveFile.GetData(),strBackupActiveFile.GetData(),FALSE)){
  2484. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, back up active.txt fail, err=%d",(int)GetLastError()).GetData());
  2485. backupSucc = false;
  2486. }
  2487. FILE* fp = fopen(strActiveFile.GetData(),"wb+");
  2488. if(fp==NULL){
  2489. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
  2490. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open write active.txt fail, err=%d",(int)GetLastError()).GetData());
  2491. return Error_Unexpect;
  2492. }
  2493. int ret = fwrite(m_currentTask.NewVersion.GetData(),m_currentTask.NewVersion.GetLength(),1,fp);
  2494. if(ret!=1){
  2495. //LogError(Severity_Low, Error_Unexpect, 0, "write active.txt fail");
  2496. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, write active.txt fail, err=%d",(int)GetLastError()).GetData());
  2497. fclose(fp);
  2498. if(backupSucc){
  2499. if(CopyFileA(strBackupActiveFile.GetData(),strActiveFile.GetData(),FALSE)){
  2500. RemoveFileA(strBackupActiveFile.GetData());
  2501. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("back_active.txt copy to active.txt is succ");
  2502. }else{
  2503. 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());
  2504. }
  2505. }
  2506. return Error_Unexpect;
  2507. }else{
  2508. fflush(fp);
  2509. fclose(fp);
  2510. if (ExistsFileA(strBackupActiveFile.GetData())) {
  2511. RemoveFileA(strBackupActiveFile.GetData());
  2512. }
  2513. }
  2514. //重新读active文件,看文件内容是什么
  2515. fp = fopen(strActiveFile.GetData(),"rb");
  2516. if(fp==NULL){
  2517. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
  2518. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open read active.txt fail, err=%d",(int)GetLastError()).GetData());
  2519. return Error_Unexpect;
  2520. }
  2521. char cVer[16] = {0};
  2522. int re = fread(cVer,m_currentTask.NewVersion.GetLength(),1,fp);
  2523. if(re!=1){
  2524. //LogError(Severity_Low, Error_Unexpect, 0, "Read active.txt fail");
  2525. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, read active.txt fail, err=%d",(int)GetLastError()).GetData());
  2526. }else{
  2527. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read active.txt, version[%s]", cVer);
  2528. }
  2529. fclose(fp);
  2530. return Error_Succeed;
  2531. #else
  2532. bool backupSucc = true;
  2533. CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\back_active.txt", rootVerPath.GetData());
  2534. if (fileutil_copy_file( strBackupActiveFile.GetData(),strActiveFile.GetData())!=0) {
  2535. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, back up active.txt fail, err=%d", errno).GetData());
  2536. backupSucc = false;
  2537. }
  2538. FILE* fp = fopen(strActiveFile.GetData(),"wb+");
  2539. if(fp==NULL){
  2540. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
  2541. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, open write active.txt fail, err=%d", errno).GetData());
  2542. return Error_Unexpect;
  2543. }
  2544. int ret = fwrite(m_currentTask.NewVersion.GetData(),m_currentTask.NewVersion.GetLength(),1,fp);
  2545. if(ret!=1){
  2546. //LogError(Severity_Low, Error_Unexpect, 0, "write active.txt fail");
  2547. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, write active.txt fail, err=%d", errno).GetData());
  2548. fclose(fp);
  2549. if (backupSucc) {
  2550. if (fileutil_copy_file(strActiveFile.GetData(), strBackupActiveFile.GetData())==0) {
  2551. RemoveFileA(strBackupActiveFile.GetData());
  2552. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("back_active.txt copy to active.txt is succ");
  2553. }else{
  2554. 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());
  2555. }
  2556. }
  2557. return Error_Unexpect;
  2558. }else{
  2559. fflush(fp);
  2560. fclose(fp);
  2561. if (ExistsFileA(strBackupActiveFile.GetData())) {
  2562. RemoveFileA(strBackupActiveFile.GetData());
  2563. }
  2564. }
  2565. //重新读active文件,看文件内容是什么
  2566. fp = fopen(strActiveFile.GetData(),"rb");
  2567. if(fp==NULL){
  2568. //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
  2569. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open read active.txt fail, err=%d", errno).GetData());
  2570. return Error_Unexpect;
  2571. }
  2572. char cVer[16] = {0};
  2573. int re = fread(cVer,m_currentTask.NewVersion.GetLength(),1,fp);
  2574. if(re!=1){
  2575. //LogError(Severity_Low, Error_Unexpect, 0, "Read active.txt fail");
  2576. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, read active.txt fail, err=%d", errno).GetData());
  2577. }else{
  2578. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read active.txt, version[%s]", cVer);
  2579. }
  2580. fclose(fp);
  2581. return Error_Succeed;
  2582. #endif
  2583. }
  2584. }
  2585. ErrorCodeEnum CUpgradeTaskFSM::RollBackToHistoryVersion(CVersion historyVersion)
  2586. {
  2587. // 判断目标版本是否小于当前版本
  2588. CVersion v=m_currentVersion;//当前版本
  2589. CVersion curVersion(v.GetMajor(), v.GetMinor(), v.GetRevision(), v.GetBuild());
  2590. if (curVersion <= historyVersion)
  2591. {
  2592. 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());
  2593. return Error_Param;
  2594. }
  2595. // 检查对应文件夹是否存在
  2596. CSimpleStringA strHisVersion = historyVersion.ToString();
  2597. CSimpleStringA rootVerPath;
  2598. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
  2599. if(rc!=Error_Succeed){
  2600. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryVersion fail , get RootVer path is fail");
  2601. return Error_Bug;
  2602. }
  2603. CSimpleStringA strHisVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), strHisVersion.GetData());
  2604. if (!ExistsDirA(strHisVerPath.GetData()))
  2605. {
  2606. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryVersion fail, history version dir [%s] not exists", strHisVerPath.GetData()).GetData());
  2607. return Error_NotExist;
  2608. }
  2609. //删除当时的运行缓存值
  2610. // 修改active.txt文件,可能存在失败
  2611. CSimpleStringA strActiveFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "active.txt", rootVerPath.GetData());
  2612. if(!ExistsFileA(strActiveFile.GetData())){
  2613. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryVersion fail, active file is not exist");
  2614. return Error_Unexpect;
  2615. }
  2616. //先做active文件备份,后面写入失败再copy回去
  2617. #ifdef RVC_OS_WIN
  2618. bool backupSucc = true;
  2619. CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\Rollback_active.txt", rootVerPath.GetData());
  2620. if(!CopyFileA(strActiveFile.GetData(),strBackupActiveFile.GetData(),FALSE)){
  2621. 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());
  2622. backupSucc = false;
  2623. }
  2624. FILE* fp = fopen(strActiveFile.GetData(),"wb+");
  2625. if(fp==NULL){
  2626. 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());
  2627. return Error_Unexpect;
  2628. }
  2629. int ret = fwrite(strHisVersion.GetData(),strHisVersion.GetLength(),1,fp);
  2630. if(ret!=1){
  2631. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, write active.txt fail,err=%d", (int)GetLastError()).GetData());
  2632. fclose(fp);
  2633. if(backupSucc){
  2634. if(CopyFileA(strBackupActiveFile.GetData(),strActiveFile.GetData(),FALSE)){
  2635. RemoveFileA(strBackupActiveFile.GetData());
  2636. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Rollback_active.txt copy to active.txt is succ");
  2637. }else{
  2638. 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());
  2639. }
  2640. }
  2641. return Error_Unexpect;
  2642. }else{
  2643. fflush(fp);
  2644. fclose(fp);
  2645. if (ExistsFileA(strBackupActiveFile.GetData())) {
  2646. RemoveFileA(strBackupActiveFile.GetData());
  2647. }
  2648. }
  2649. //重新读active文件,看文件内容是什么
  2650. fp = fopen(strActiveFile.GetData(),"rb");
  2651. if(fp==NULL){
  2652. 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());
  2653. return Error_Unexpect;
  2654. }
  2655. char cVer[16] = {0};
  2656. int re = fread(cVer,strHisVersion.GetLength(),1,fp);
  2657. if(re!=1){
  2658. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Read active.txt fail,err=%d", (int)GetLastError()).GetData());
  2659. }else{
  2660. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read active.txt, version[%s]", cVer);
  2661. }
  2662. fclose(fp);
  2663. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set rollback to history version [%s] succeed", (const char*)strHisVersion);
  2664. return Error_Succeed;
  2665. #else
  2666. bool backupSucc = true;
  2667. CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\Rollback_active.txt", rootVerPath.GetData());
  2668. if (fileutil_copy_file(strBackupActiveFile.GetData(), strActiveFile.GetData())!=0) {
  2669. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, back up active.txt fail, err=%d", errno).GetData());
  2670. backupSucc = false;
  2671. }
  2672. FILE* fp = fopen(strActiveFile.GetData(),"wb+");
  2673. if(fp==NULL){
  2674. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open write active.txt fail,err=%d", errno).GetData());
  2675. return Error_Unexpect;
  2676. }
  2677. int ret = fwrite(strHisVersion.GetData(),strHisVersion.GetLength(),1,fp);
  2678. if(ret!=1){
  2679. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, write active.txt fail,err=%d", errno).GetData());
  2680. fclose(fp);
  2681. if (backupSucc) {
  2682. if (fileutil_copy_file(strActiveFile.GetData(), strBackupActiveFile.GetData())==0) {
  2683. RemoveFileA(strBackupActiveFile.GetData());
  2684. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Rollback_active.txt copy to active.txt is succ");
  2685. }else{
  2686. 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());
  2687. }
  2688. }
  2689. return Error_Unexpect;
  2690. }else{
  2691. fflush(fp);
  2692. fclose(fp);
  2693. if (ExistsFileA(strBackupActiveFile.GetData())) {
  2694. RemoveFileA(strBackupActiveFile.GetData());
  2695. }
  2696. }
  2697. //重新读active文件,看文件内容是什么
  2698. fp = fopen(strActiveFile.GetData(),"rb");
  2699. if(fp==NULL){
  2700. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open read active.txt fail,err=%d", errno).GetData());
  2701. return Error_Unexpect;
  2702. }
  2703. char cVer[16] = {0};
  2704. int re = fread(cVer,strHisVersion.GetLength(),1,fp);
  2705. if(re!=1){
  2706. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Read active.txt fail,err=%d", errno).GetData());
  2707. }else{
  2708. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read active.txt, version[%s]", cVer);
  2709. }
  2710. fclose(fp);
  2711. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set rollback to history version [%s] succeed", (const char*)strHisVersion);
  2712. return Error_Succeed;
  2713. #endif
  2714. }
  2715. void CUpgradeTaskFSM::RecursiveGetSubFiles(const char *pszDir, const char *pszTrimStart, list<CSimpleStringA>& retList)
  2716. {
  2717. if (!ExistsDirA(pszDir))
  2718. return;
  2719. auto arr = fileutil_get_sub_files(pszDir);
  2720. if (arr != NULL)
  2721. {
  2722. for (int i = 0; i < arr->nelts; ++i)
  2723. {
  2724. char *file = ARRAY_IDX(arr, i, char*);
  2725. #ifdef RVC_OS_WIN
  2726. //不区分大小写
  2727. if (pszTrimStart != NULL && strnicmp(file, pszTrimStart, strlen(pszTrimStart))==0) {
  2728. #else
  2729. //区分大小写
  2730. if (pszTrimStart != NULL && strncmp(file, pszTrimStart, strlen(pszTrimStart)) == 0) {
  2731. #endif
  2732. file += strlen(pszTrimStart);
  2733. if (*file == SPLIT_SLASH)
  2734. file++;
  2735. }
  2736. retList.push_back(file);
  2737. }
  2738. toolkit_array_free2(arr);
  2739. }
  2740. arr = fileutil_get_sub_dirs(pszDir);
  2741. if (arr != NULL)
  2742. {
  2743. for (int i = 0; i < arr->nelts; ++i)
  2744. {
  2745. char *dir = ARRAY_IDX(arr, i, char*);
  2746. RecursiveGetSubFiles(dir, pszTrimStart, retList);
  2747. }
  2748. toolkit_array_free2(arr);
  2749. }
  2750. }
  2751. bool CUpgradeTaskFSM::IsFileMatch(const char *pszFilter, const char *pszFileName)
  2752. {
  2753. const char *p1 = pszFilter;
  2754. const char *p2 = pszFileName;
  2755. if (p1 == NULL)
  2756. return true;
  2757. if (p2 == NULL)
  2758. return false;
  2759. if (*p1 ==NULL && *p2 ==NULL)
  2760. return true;
  2761. else if (*p1 == NULL)
  2762. return false;
  2763. else if (*p2 == NULL)
  2764. {
  2765. // 查找*p1是否全是*
  2766. while(*p1 == '*')
  2767. p1++;
  2768. if (*p1 == NULL)
  2769. return true;
  2770. else
  2771. return false;
  2772. }
  2773. if (*p1 != '*')
  2774. {
  2775. if (tolower(*p1) != tolower(*p2))
  2776. return false;
  2777. else
  2778. return IsFileMatch(p1+1, p2+1);
  2779. }
  2780. else
  2781. {
  2782. while(*++p1 == '*');
  2783. if (*p1 == NULL)
  2784. return true;
  2785. while (*p2)
  2786. {
  2787. while(tolower(*p1) != tolower(*p2) && *++p2);
  2788. if (*p2 == NULL)
  2789. return false;
  2790. if(IsFileMatch(p1+1, p2+1))
  2791. return true;
  2792. p2++;
  2793. }
  2794. return false;
  2795. }
  2796. }
  2797. bool CUpgradeTaskFSM::RecursiveCopyDir(const char *pszSourceDir, const char *pszDestDir,CSimpleStringA &strErrInfo)
  2798. {
  2799. array_header_t *arr;
  2800. #ifdef RVC_OS_WIN
  2801. if (!ExistsDirA(pszSourceDir))
  2802. {
  2803. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("source dir [%s] not exists: %d", pszSourceDir,GetLastError());
  2804. strErrInfo = CSimpleStringA::Format("source dir [%s] not exists: %d", pszSourceDir, GetLastError());
  2805. return false;
  2806. }
  2807. if (!ExistsDirA(pszDestDir))
  2808. {
  2809. if (!CreateDirRecursiveA(pszDestDir))
  2810. {
  2811. strErrInfo = CSimpleStringA::Format("create dir [%s] fail: %d", pszDestDir, GetLastError());
  2812. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("create dir fail: %s",strErrInfo.GetData());
  2813. return false;
  2814. }
  2815. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("create dir [%s] succ", pszDestDir);
  2816. }
  2817. #else
  2818. if (!ExistsDirA(pszSourceDir))
  2819. {
  2820. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("source dir [%s] not exists: %d", pszSourceDir, errno);
  2821. strErrInfo = CSimpleStringA::Format("source dir [%s] not exists: %d", pszSourceDir, errno);
  2822. return false;
  2823. }
  2824. if (!ExistsDirA(pszDestDir))
  2825. {
  2826. if (!CreateDirRecursiveA(pszDestDir))
  2827. {
  2828. strErrInfo = CSimpleStringA::Format("create dir [%s] fail: %d", pszDestDir, errno);
  2829. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("create dir fail: %s",strErrInfo.GetData());
  2830. return false;
  2831. }
  2832. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("create dir [%s] succ", pszDestDir);
  2833. }
  2834. #endif
  2835. arr = fileutil_get_sub_files_a(pszSourceDir);
  2836. if (arr)
  2837. {
  2838. int i;
  2839. for (i = 0; i < arr->nelts; ++i)
  2840. {
  2841. char szDestFile[256] = { 0 };
  2842. char *file = ARRAY_IDX(arr, i, char*);
  2843. strcpy(szDestFile, pszDestDir);
  2844. if (szDestFile[strlen(szDestFile) - 1] != SPLIT_SLASH)
  2845. strcat(szDestFile, SPLIT_SLASH_STR);
  2846. strcat(szDestFile, strrchr(file, SPLIT_SLASH) + 1);
  2847. #ifdef RVC_OS_WIN
  2848. if (!CopyFileA(file, szDestFile, FALSE))
  2849. {
  2850. strErrInfo = CSimpleStringA::Format("copy file [%s] fail: %d", file, GetLastError());
  2851. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy file fail:%s",strErrInfo.GetData());
  2852. toolkit_array_free2(arr);
  2853. return false;
  2854. }
  2855. #else
  2856. if (fileutil_copy_file(szDestFile, file)!=0)
  2857. {
  2858. strErrInfo = CSimpleStringA::Format("copy file [%s] fail: %d", file, errno);
  2859. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy file fail:%s",strErrInfo.GetData());
  2860. toolkit_array_free2(arr);
  2861. return false;
  2862. }
  2863. #endif
  2864. }
  2865. toolkit_array_free2(arr);
  2866. }
  2867. arr = fileutil_get_sub_dirs_a(pszSourceDir);
  2868. if (arr)
  2869. {
  2870. int i;
  2871. for (i = 0; i < arr->nelts; ++i)
  2872. {
  2873. char szDestSubDir[256] = { 0 };
  2874. char *dir = ARRAY_IDX(arr, i, char*);
  2875. strcpy(szDestSubDir, pszDestDir);
  2876. if (szDestSubDir[strlen(szDestSubDir) - 1] != SPLIT_SLASH)
  2877. strcat(szDestSubDir, SPLIT_SLASH_STR);
  2878. strcat(szDestSubDir, strrchr(dir, SPLIT_SLASH) + 1);
  2879. if (!RecursiveCopyDir(dir, szDestSubDir,strErrInfo))
  2880. {
  2881. #ifdef RVC_OS_WIN
  2882. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy dir [%s] fail: %d", dir, GetLastError());
  2883. if(strErrInfo.IsNullOrEmpty()){
  2884. strErrInfo = CSimpleStringA::Format("copy dir [%s] fail: %d", dir, GetLastError());
  2885. }
  2886. toolkit_array_free2(arr);
  2887. return false;
  2888. #else
  2889. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy dir [%s] fail: %d", dir, errno);
  2890. if (strErrInfo.IsNullOrEmpty()) {
  2891. strErrInfo = CSimpleStringA::Format("copy dir [%s] fail: %d", dir, errno);
  2892. }
  2893. toolkit_array_free2(arr);
  2894. return false;
  2895. #endif
  2896. }
  2897. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy dir [%s] succ", dir);
  2898. }
  2899. toolkit_array_free2(arr);
  2900. }
  2901. return true;
  2902. }
  2903. CSimpleStringA CUpgradeTaskFSM::GetFileDirectory(const char *pszFullPath)
  2904. {
  2905. int i=strlen(pszFullPath)-1;
  2906. for( ; i>0 && pszFullPath[i]!= SPLIT_SLASH; i--)NULL;
  2907. return CSimpleStringA(pszFullPath, i);
  2908. }
  2909. bool CUpgradeTaskFSM::IsWow64Process()
  2910. {
  2911. #ifdef RVC_OS_WIN
  2912. typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  2913. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
  2914. BOOL bIsWow64 = FALSE;
  2915. if (NULL != fnIsWow64Process)
  2916. {
  2917. if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
  2918. {
  2919. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("call IsWow64Process error: %d", GetLastError());
  2920. return false;
  2921. }
  2922. return bIsWow64 == TRUE;
  2923. }
  2924. else
  2925. {
  2926. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get IsWow64Process error: %d", GetLastError());
  2927. return false;
  2928. }
  2929. #endif
  2930. return true;
  2931. }
  2932. int CUpgradeTaskFSM::system_on(string cmdFilePath, bool isWait,CSimpleStringA &errMsg)
  2933. {
  2934. #ifdef RVC_OS_WIN
  2935. string cmdLine = "cmd /c ";
  2936. cmdLine.append(cmdFilePath.c_str());
  2937. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("exec bat %s",cmdLine.c_str());
  2938. return waitSystem("cmd.exe", cmdLine.c_str(), true, errMsg);
  2939. #else
  2940. //linux直接用system函数即可
  2941. return system(cmdFilePath.c_str());
  2942. #endif
  2943. }
  2944. //返回值是0则正常执行,其他都是非正常未知状态
  2945. int CUpgradeTaskFSM::waitSystem(string cmd, const char * par, bool nShow,CSimpleStringA &errMsg)
  2946. {
  2947. #ifdef RVC_OS_WIN
  2948. SHELLEXECUTEINFOA ShExecInfo = { 0 };
  2949. ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
  2950. ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
  2951. ShExecInfo.hwnd = NULL;
  2952. ShExecInfo.lpVerb = NULL;
  2953. ShExecInfo.lpFile = cmd.c_str(); //调用的程序名
  2954. ShExecInfo.lpParameters = par; //调用程序的命令行参数
  2955. ShExecInfo.lpDirectory = NULL;
  2956. ShExecInfo.nShow = nShow ? SW_MINIMIZE: SW_HIDE; //窗口状态为隐藏
  2957. ShExecInfo.hInstApp = NULL;
  2958. if (!ShellExecuteEx(&ShExecInfo))
  2959. {
  2960. errMsg = CSimpleStringA::Format("shellExecute is fail :%d",GetLastError());
  2961. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is fail :%s",errMsg.GetData());
  2962. return -1;
  2963. }
  2964. //等到该进程结束,如果5分钟没结束,强行杀死进程
  2965. if (WaitForSingleObject(ShExecInfo.hProcess, 5*60*1000) == WAIT_TIMEOUT)
  2966. {
  2967. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is time out");
  2968. errMsg = CSimpleStringA::Format("shellExecute is time out");
  2969. if (TerminateProcess(ShExecInfo.hProcess, 0))
  2970. {
  2971. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminateProcess is succ");
  2972. }else {
  2973. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminateProcess is fail :%d",GetLastError());
  2974. }
  2975. if (CloseHandle(ShExecInfo.hProcess))
  2976. {
  2977. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is succ");
  2978. }else {
  2979. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is fail");
  2980. }
  2981. return -1;
  2982. }
  2983. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is succ");
  2984. DWORD exitCode = 0;
  2985. if (!GetExitCodeProcess(ShExecInfo.hProcess, &exitCode))
  2986. {
  2987. errMsg = CSimpleStringA::Format("GetExitCodeProcess is fail:%d",GetLastError());
  2988. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetExitCodeProcess is fail:%s",errMsg.GetData());
  2989. return -1;
  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. if(exitCode!=0){
  2998. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetExitCodeProcess ret exitCode=%d",(int)exitCode);
  2999. errMsg = CSimpleStringA::Format("GetExitCodeProcess ret exitCode=%d",(int)exitCode);
  3000. }
  3001. return exitCode;
  3002. #else
  3003. return 0;
  3004. #endif
  3005. }
  3006. char* CUpgradeTaskFSM::ConvertUtf8ToGBK(const char* strUtf8)
  3007. {
  3008. int len = MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, NULL, 0);
  3009. WCHAR* wszGBK = new WCHAR[len + 1];
  3010. memset(wszGBK, 0, len * 2 + 2);
  3011. MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, wszGBK, len);
  3012. len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
  3013. char* szGBK = new char[len + 1];
  3014. memset(szGBK, 0, len + 1);
  3015. WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
  3016. delete[] wszGBK;
  3017. return szGBK;
  3018. }
  3019. void CUpgradeTaskFSM::ConvertUtf8ToGBK(std::string &str)
  3020. {
  3021. char *dst = ConvertUtf8ToGBK(str.c_str());
  3022. str = dst;
  3023. delete[] dst;
  3024. }
  3025. char* CUpgradeTaskFSM::ConvertGBKToUtf8(const char* gbk, int *n)
  3026. {
  3027. int len = MultiByteToWideChar(CP_ACP, 0, gbk, -1, NULL, 0);
  3028. WCHAR* wszGBK = new WCHAR[len + 1];
  3029. memset(wszGBK, 0, len * 2 + 2);
  3030. MultiByteToWideChar(CP_ACP, 0, gbk, -1, wszGBK, len);
  3031. len = WideCharToMultiByte(CP_UTF8, 0, wszGBK, -1, NULL, 0, NULL, NULL);
  3032. char* szUtf8 = new char[len + 1];
  3033. memset(szUtf8, 0, len + 1);
  3034. WideCharToMultiByte(CP_UTF8, 0, wszGBK, -1, szUtf8, len, NULL, NULL);
  3035. delete[] wszGBK;
  3036. *n = len - 1;
  3037. return szUtf8;
  3038. }
  3039. void CUpgradeTaskFSM::ConvertGBKToUtf8(std::string &str)
  3040. {
  3041. int len = 0;
  3042. char *dst = ConvertGBKToUtf8(str.c_str(), &len);
  3043. str = dst;
  3044. delete[] dst;
  3045. }
  3046. bool CUpgradeTaskFSM::is_str_utf8(const char* str)
  3047. {
  3048. unsigned int nBytes = 0;//UFT8可用1-6个字节编码,ASCII用一个字节
  3049. unsigned char chr = *str;
  3050. bool bAllAscii = true;
  3051. for (unsigned int i = 0; str[i] != '\0'; ++i) {
  3052. chr = *(str + i);
  3053. //判断是否ASCII编码,如果不是,说明有可能是UTF8,ASCII用7位编码,最高位标记为0,0xxxxxxx
  3054. if (nBytes == 0 && (chr & 0x80) != 0) {
  3055. bAllAscii = false;
  3056. }
  3057. if (nBytes == 0) {
  3058. //如果不是ASCII码,应该是多字节符,计算字节数
  3059. if (chr >= 0x80) {
  3060. if (chr >= 0xFC && chr <= 0xFD) {
  3061. nBytes = 6;
  3062. }
  3063. else if (chr >= 0xF8) {
  3064. nBytes = 5;
  3065. }
  3066. else if (chr >= 0xF0) {
  3067. nBytes = 4;
  3068. }
  3069. else if (chr >= 0xE0) {
  3070. nBytes = 3;
  3071. }
  3072. else if (chr >= 0xC0) {
  3073. nBytes = 2;
  3074. }
  3075. else {
  3076. return false;
  3077. }
  3078. nBytes--;
  3079. }
  3080. }
  3081. else {
  3082. //多字节符的非首字节,应为 10xxxxxx
  3083. if ((chr & 0xC0) != 0x80) {
  3084. return false;
  3085. }
  3086. //减到为零为止
  3087. nBytes--;
  3088. }
  3089. }
  3090. //违返UTF8编码规则
  3091. if (nBytes != 0) {
  3092. return false;
  3093. }
  3094. if (bAllAscii) { //如果全部都是ASCII, 也是UTF8
  3095. return true;
  3096. }
  3097. return true;
  3098. }
  3099. ErrorCodeEnum CUpgradeTaskFSM::UnzipPack(const char* unZipPackName)
  3100. {
  3101. #ifdef RVC_OS_WIN
  3102. // 设定解压临时目录
  3103. char szOldPath[MAX_PATH] = {};
  3104. GetCurrentDirectoryA(MAX_PATH, szOldPath);
  3105. CSimpleStringA strDownloadsPath;
  3106. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
  3107. if(rc!=Error_Succeed){
  3108. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,get Downloads Path is fail");
  3109. return Error_Unexpect;
  3110. }
  3111. CSimpleStringA strZipFile = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), unZipPackName);
  3112. //升级包是否存在
  3113. if(!ExistsFileA(strZipFile)){
  3114. LogWarn(Severity_Low, Error_NotExist, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
  3115. return Error_NotExist;
  3116. }
  3117. CSimpleStringA strUnzipDir;
  3118. strUnzipDir = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), unZipPackName);
  3119. //解压去除了.zip后缀
  3120. if (strUnzipDir.IsEndWith(".zip")){
  3121. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
  3122. }
  3123. // 解压目录是否存在,则先删除
  3124. if (ExistsDirA(strUnzipDir.GetData()))
  3125. {
  3126. if(!RemoveDirRecursiveA(strUnzipDir.GetData())){
  3127. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,delete exist temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
  3128. return Error_Unexpect;
  3129. }
  3130. }
  3131. // 创建临时解压目录
  3132. if(!CreateDirectoryA(strUnzipDir.GetData(), NULL)){
  3133. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,create temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
  3134. return Error_Unexpect;
  3135. }
  3136. //设置当前目录为主目录
  3137. if(!SetCurrentDirectoryA(strUnzipDir.GetData())){
  3138. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,SetCurrentDirectoryA dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
  3139. return Error_Unexpect;
  3140. }
  3141. // 解压
  3142. HZIP hz = OpenZip((void*)(const char*)strZipFile,0,ZIP_FILENAME);
  3143. if (hz == 0)
  3144. {
  3145. SetCurrentDirectoryA(szOldPath);
  3146. LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("open zip file [%s] fail", unZipPackName).GetData());
  3147. return Error_Unexpect;
  3148. }
  3149. ZIPENTRY ze;
  3150. ZRESULT zrc = GetZipItemA(hz,-1,&ze);
  3151. if(zrc == ZR_OK){
  3152. int numitems=ze.index;
  3153. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("zip entry count is %d",ze.index);
  3154. for (int i=0; i<numitems; i++)
  3155. {
  3156. zrc = GetZipItemA(hz,i,&ze);
  3157. if(zrc==ZR_OK){
  3158. //兼容压缩包里面中文名称是utf8编码
  3159. if(is_str_utf8(ze.name)){
  3160. char *pGBK = ConvertUtf8ToGBK((const char*)ze.name);
  3161. zrc = UnzipItem(hz,i,pGBK,0,ZIP_FILENAME);
  3162. if(zrc ==ZR_OK){
  3163. //Dbg("unzip [%s] UTF8 item succeed", pGBK);
  3164. delete[] pGBK;
  3165. }else{
  3166. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip [%s] UTF8 item fail,result=0x%X", pGBK,(int)zrc);
  3167. delete[] pGBK;
  3168. break;
  3169. }
  3170. }else{
  3171. zrc = UnzipItem(hz,i,ze.name,0,ZIP_FILENAME);
  3172. if(zrc ==ZR_OK){
  3173. //Dbg("unzip [%s] GBK item succeed", ze.name);
  3174. }else{
  3175. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip [%s] GBK item fail,result=0x%X", ze.name,(int)zrc);
  3176. break;
  3177. }
  3178. }
  3179. }else{
  3180. //出错,退出
  3181. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip GetZipItemA [%d] item fail,fail=0x%X",i,(int)zrc);
  3182. break;
  3183. }
  3184. }
  3185. CloseZip(hz);
  3186. }else{
  3187. CloseZip(hz);
  3188. }
  3189. // 恢复当前目录
  3190. SetCurrentDirectoryA(szOldPath);
  3191. if(zrc!=ZR_OK){
  3192. return Error_Exception;
  3193. }
  3194. return Error_Succeed;
  3195. #else
  3196. CSimpleStringA strDownloadsPath;
  3197. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
  3198. if (rc != Error_Succeed) {
  3199. Dbg("unzipPack is fail,get Downloads Path is fail");
  3200. return Error_Unexpect;
  3201. }
  3202. CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
  3203. //升级包是否存在
  3204. if (!ExistsFileA(strZipFile)) {
  3205. LogWarn(Severity_Low, Error_NotExist, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
  3206. return Error_NotExist;
  3207. }
  3208. CSimpleStringA strUnzipDir;
  3209. strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
  3210. //解压去除了.zip后缀
  3211. if (strUnzipDir.IsEndWith(".zip")) {
  3212. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  3213. }
  3214. // 解压目录是否存在,存在先删除
  3215. if (ExistsDirA(strUnzipDir.GetData()))
  3216. {
  3217. if (!RemoveDirRecursiveA(strUnzipDir.GetData())) {
  3218. Dbg("unzipPack is fail,delete exist temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), errno);
  3219. return Error_Unexpect;
  3220. }
  3221. }
  3222. // 创建临时解压目录
  3223. if (!CreateDirA(strUnzipDir.GetData(), false)) {
  3224. // 创建临时解压目录失败
  3225. Dbg("unzipPack is fail,create temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), errno);
  3226. return Error_Unexpect;
  3227. }
  3228. if (changeFileAtt(strZipFile.GetData())!=0) {
  3229. //改变文件属性
  3230. Dbg("unzipPack is fail,changeFileAtt zip [%s] fail,err=%d", strZipFile.GetData(), errno);
  3231. return Error_Unexpect;
  3232. }
  3233. // 解压
  3234. string zipFileStr = strZipFile.GetData();
  3235. string zipTempDir = strUnzipDir.GetData();
  3236. if (UnZipToDir(zipFileStr, zipTempDir) != 0)
  3237. {
  3238. LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("unzip pack [%s] fail", unZipPackName));
  3239. return Error_NotExist;
  3240. }
  3241. return Error_Succeed;
  3242. #endif
  3243. }
  3244. ErrorCodeEnum CUpgradeTaskFSM::DeleteUnzipDir()
  3245. {
  3246. CSimpleStringA strDownloadsPath;
  3247. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
  3248. if(rc!=Error_Succeed){
  3249. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("DeleteUnzipDir is fail,get Downloads Path is fail");
  3250. return Error_Unexpect;
  3251. }
  3252. //判断解压缩文件夹名是否存在,不存在告警
  3253. if (m_currentTask.pack_name.IsNullOrEmpty()) {
  3254. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("DeleteUnzipDir is fail ,temp unzip dir name is null");
  3255. return Error_Unexpect;
  3256. }
  3257. CSimpleStringA strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), m_currentTask.pack_name.GetData());
  3258. //解压去除了.zip后缀
  3259. if (strUnzipDir.IsEndWith(".zip")){
  3260. strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
  3261. }
  3262. // 解压目录是否存在,存在则删除
  3263. if (ExistsDirA(strUnzipDir.GetData()))
  3264. {
  3265. if(!RemoveDirRecursiveA(strUnzipDir.GetData())){
  3266. #ifdef RVC_OS_WIN
  3267. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),(int)GetLastError());
  3268. #else
  3269. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(), errno);
  3270. #endif
  3271. return Error_Unexpect;
  3272. }else{
  3273. return Error_Succeed;
  3274. }
  3275. }
  3276. return Error_Succeed;
  3277. }
  3278. void CUpgradeTaskFSM::SendUpgradeTaskProgress(CTaskProcess &process, CSimpleStringA logCodeStr, CSimpleStringA rtaStr)
  3279. {
  3280. Json::Value root;
  3281. Json::FastWriter fw;//写入对象
  3282. if(!process.strPackName.IsNullOrEmpty()){
  3283. root["strPackName"]=process.strPackName.GetData();
  3284. }else{
  3285. root["strPackName"]="";
  3286. }
  3287. if(process.installVersion.IsNullOrEmpty()){
  3288. root["installVersion"]="0.0.0.0";
  3289. }else{
  3290. root["installVersion"]=process.installVersion.GetData();
  3291. }
  3292. //string currentBuildStr = CSimpleStringA::Format("%d.%d.%d",process.CurrentVersion.GetMajor(),process.CurrentVersion.GetMinor(),process.CurrentVersion.GetRevision()).GetData();
  3293. root["CurrentVersion"]=process.CurrentVersion.GetData();
  3294. root["CurrentBuild"]= process.CurrentVersion.GetData();
  3295. root["upgradeTimeStr"]=CSmallDateTime::GetNow().ToTimeString().GetData();
  3296. if(!process.cInstallState.IsNullOrEmpty()){
  3297. root["cInstallState"]=process.cInstallState.GetData();
  3298. }else{
  3299. root["cInstallState"]="";
  3300. }
  3301. if(!process.strInstallComment.IsNullOrEmpty()){
  3302. CSimpleStringA comment = "task:";
  3303. comment.Append(process.strInstallComment.GetData());
  3304. root["strInstallComment"]=comment.GetData();
  3305. }else{
  3306. root["strInstallComment"]="";
  3307. }
  3308. string upgradeStr = fw.write(root);
  3309. if (!upgradeStr.empty()) {
  3310. LogWarn(Severity_Low, Error_Succeed, LOG_WRAN_UPGRADE_PROGRESS, upgradeStr.c_str());
  3311. if (rtaStr.IsNullOrEmpty()) {
  3312. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(logCodeStr).setAPI("SendUpgradeTaskProgress")(upgradeStr.c_str());
  3313. }
  3314. else {
  3315. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(logCodeStr).setResultCode(rtaStr).setAPI("SendUpgradeTaskProgress")(upgradeStr.c_str());
  3316. }
  3317. }else{
  3318. LogWarn(Severity_Middle,Error_Unexpect,ERR_WRAN_UPGRADE_PROGRESS,"获取升级过程信息错误");
  3319. }
  3320. }
  3321. ErrorCodeEnum CUpgradeTaskFSM::GetRunConfigStrValue(const char *pszSection, const char *pszKey, CSimpleStringA &strValue)
  3322. {
  3323. CSmartPointer<IConfigInfo> pConfig;
  3324. ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_Run, pConfig);
  3325. if (rc != Error_Succeed){
  3326. return rc;
  3327. }
  3328. return pConfig->ReadConfigValue(pszSection, pszKey, strValue);
  3329. }
  3330. ErrorCodeEnum CUpgradeTaskFSM::SetRunConfigStrValue(const char *pszSection, const char *pszKey, const char *pszValue)
  3331. {
  3332. CSmartPointer<IConfigInfo> pConfig;
  3333. ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_Run, pConfig);
  3334. if (rc != Error_Succeed){
  3335. return rc;
  3336. }
  3337. return pConfig->WriteConfigValue(pszSection, pszKey, pszValue);
  3338. }
  3339. bool CUpgradeTaskFSM::ClearCurrTaskInfo()
  3340. {
  3341. if(SetRunConfigStrValue("upgradeTask","UpgradeTaskId","")!=Error_Succeed){
  3342. return false;
  3343. }
  3344. if(SetRunConfigStrValue("upgradeTask","CreateTaskVersion","")!=Error_Succeed){
  3345. return false;
  3346. }
  3347. if(SetRunConfigStrValue("upgradeTask","PackName","")!=Error_Succeed){
  3348. return false;
  3349. }
  3350. if(SetRunConfigStrValue("upgradeTask","PendingState","")!=Error_Succeed){
  3351. return false;
  3352. }
  3353. if(SetRunConfigStrValue("upgradeTask","NewVersion","")!=Error_Succeed){
  3354. return false;
  3355. }
  3356. if (SetRunConfigStrValue("upgradeTask", "TaskType", "") != Error_Succeed) {
  3357. return false;
  3358. }
  3359. if (SetRunConfigStrValue("upgradeTask", "depNewVersion", "") != Error_Succeed) {
  3360. return false;
  3361. }
  3362. //试着删除可能临时下载的升级包文件
  3363. CSimpleStringA strPath;
  3364. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strPath);
  3365. if(Error_Succeed != rc){
  3366. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearCurrTaskInfo get Downloads path fail,upgradeTaskId=%s",m_currentTask.upgradeTaskId.GetData());
  3367. return false;
  3368. }
  3369. CSimpleStringA tempPackPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s%s", strPath.GetData(), m_currentTask.pack_name.GetData(),".tmp");
  3370. if(ExistsFileA(tempPackPath.GetData())){
  3371. if(!RemoveFileA(tempPackPath.GetData())){
  3372. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearCurrTaskInfo delete tempPack fail,packPath=%s",tempPackPath.GetData());
  3373. return false;
  3374. }
  3375. }
  3376. //清空内存变量
  3377. m_currentTask.upgradeTaskId = "";
  3378. m_currentTask.createTaskVersion = "";
  3379. m_currentTask.pack_name = "";
  3380. m_currentTask.cPendingState = "";
  3381. m_currentTask.NewVersion="";
  3382. m_currentTask.task_type = "";
  3383. m_currentTask.depNewVersion = "";
  3384. m_currentTask.pack_version = "";
  3385. m_currentTask.stop_media_play =false;
  3386. m_currentTask.reboot_type = 0;
  3387. m_currentTask.file_path="";
  3388. m_currentTask.download_url = "";
  3389. m_currentTask.pack_hash = "";
  3390. m_currentTask.pack_length = 0;
  3391. ClearInstallStep();
  3392. return true;
  3393. }
  3394. bool CUpgradeTaskFSM::ClearInstallStep()
  3395. {
  3396. //清理安装步骤
  3397. int iCount = m_currentTask.install_step.size();
  3398. for (int j = 0; j < iCount; j++){
  3399. CInstallStep* tmp = m_currentTask.install_step.front();
  3400. m_currentTask.install_step.pop();
  3401. delete tmp;//删除对象
  3402. }
  3403. return true;
  3404. }
  3405. ErrorCodeEnum CUpgradeTaskFSM::LoadPersistTaskInfo()
  3406. {
  3407. // 从运行配置中读出上次未处理完的任务
  3408. // 上次未安装结束
  3409. CTaskInfo taskInfo = {};
  3410. CSimpleStringA strValue;
  3411. ErrorCodeEnum rc = GetRunConfigStrValue("upgradeTask", "UpgradeTaskId", strValue);
  3412. if(rc!=Error_Succeed){
  3413. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][UpgradeTaskId] fail ,err=%d",(int)rc);
  3414. return rc;
  3415. }
  3416. taskInfo.upgradeTaskId = strValue;
  3417. rc = GetRunConfigStrValue("upgradeTask", "CreateTaskVersion", strValue);
  3418. if(rc!=Error_Succeed){
  3419. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][CreateTaskVersion] fail ,err=%d",(int)rc);
  3420. return rc;
  3421. }
  3422. taskInfo.createTaskVersion = strValue;
  3423. rc = GetRunConfigStrValue("upgradeTask", "PackName", strValue);
  3424. if(rc!=Error_Succeed){
  3425. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][PackName] fail ,err=%d",(int)rc);
  3426. return rc;
  3427. }
  3428. taskInfo.pack_name = strValue;
  3429. rc = GetRunConfigStrValue("upgradeTask", "PendingState", strValue);
  3430. if(rc!=Error_Succeed){
  3431. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][PendingState] fail ,err=%d",(int)rc);
  3432. return rc;
  3433. }
  3434. taskInfo.cPendingState = strValue;
  3435. rc = GetRunConfigStrValue("upgradeTask", "NewVersion", strValue);
  3436. if(rc!=Error_Succeed){
  3437. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][NewVersion] fail ,err=%d",(int)rc);
  3438. return rc;
  3439. }
  3440. taskInfo.NewVersion = strValue;
  3441. rc = GetRunConfigStrValue("upgradeTask", "TaskType", strValue);
  3442. if (rc != Error_Succeed) {
  3443. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][TaskType] fail ,err=%d", (int)rc);
  3444. return rc;
  3445. }
  3446. taskInfo.task_type = strValue;
  3447. rc = GetRunConfigStrValue("upgradeTask", "depNewVersion", strValue);
  3448. if (rc != Error_Succeed) {
  3449. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][depNewVersion] fail ,err=%d", (int)rc);
  3450. return rc;
  3451. }
  3452. taskInfo.depNewVersion = strValue;
  3453. //初始化其他变量
  3454. //CSimpleStringA pack_version; //升级包指定的版本号
  3455. //CSimpleStringA to_copy; //拷贝文件列表
  3456. //CSimpleStringA to_run; //体系外运行脚本文件名称
  3457. //bool reboot_type; //重启类型
  3458. //CSimpleStringA download_url; //升级包下载地址
  3459. //CSimpleStringA pack_hash; //升级包hash值
  3460. //long pack_length; //升级包长度
  3461. taskInfo.pack_version = "";
  3462. taskInfo.reboot_type = 0;
  3463. taskInfo.file_path = "";
  3464. taskInfo.download_url = "";
  3465. taskInfo.pack_hash = "";
  3466. taskInfo.pack_length = 0;
  3467. taskInfo.stop_media_play = true;
  3468. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, UpgradeTaskId=%s", taskInfo.upgradeTaskId.GetData());
  3469. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, CreateTaskVersion=%s",taskInfo.createTaskVersion.GetData());
  3470. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, PackName=%s",taskInfo.pack_name.GetData());
  3471. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, PendingState=%s",taskInfo.cPendingState.GetData());
  3472. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, NewVersion=%s",taskInfo.NewVersion.GetData());
  3473. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, TaskType=%s", taskInfo.task_type.GetData());
  3474. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, depNewVersion=%s", taskInfo.depNewVersion.GetData());
  3475. m_currentTask = taskInfo;
  3476. return Error_Succeed;
  3477. }
  3478. ErrorCodeEnum CUpgradeTaskFSM::loadCenterCfgInfo()
  3479. {
  3480. //访问http地址的读取
  3481. CSmartPointer<IConfigInfo> spConfig;
  3482. ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  3483. if (rc == Error_Succeed){
  3484. CSimpleStringA str="";
  3485. //加载后端服务访问地址
  3486. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryPreTaskUrl", str);
  3487. if(rc==Error_Succeed){
  3488. m_centerUrl.queryPreTaskUrl = str;
  3489. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryPreTaskUrl=%s",str.GetData());
  3490. }else{
  3491. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryPreTaskUrl error");
  3492. return rc;
  3493. }
  3494. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryContinueTaskUrl", str);
  3495. if(rc==Error_Succeed){
  3496. m_centerUrl.queryContinueTaskUrl = str;
  3497. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryContinueTaskUrl=%s",str.GetData());
  3498. }else{
  3499. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryContinueTaskUrl error");
  3500. return rc;
  3501. }
  3502. rc = spConfig->ReadConfigValue("UpgradeManager", "UpdateTaskUrl", str);
  3503. if(rc==Error_Succeed){
  3504. m_centerUrl.updateTaskUrl = str;
  3505. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini UpdateTaskUrl=%s",str.GetData());
  3506. }else{
  3507. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini UpdateTaskUrl error");
  3508. return rc;
  3509. }
  3510. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryCurrTaskUrl", str);
  3511. if(rc==Error_Succeed){
  3512. m_centerUrl.queryCurrTaskUrl = str;
  3513. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryCurrTaskUrl=%s",str.GetData());
  3514. }else{
  3515. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryCurrTaskUrl error");
  3516. return rc;
  3517. }
  3518. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryNewTaskUrl", str);
  3519. if(rc==Error_Succeed){
  3520. m_centerUrl.queryNewTaskUrl = str;
  3521. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryNewTaskUrl=%s",str.GetData());
  3522. }else{
  3523. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryNewTaskUrl error");
  3524. return rc;
  3525. }
  3526. rc = spConfig->ReadConfigValue("UpgradeManager", "QueryTaskStatus", str);
  3527. if(rc==Error_Succeed){
  3528. m_centerUrl.queryTaskStatus = str;
  3529. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryTaskStatus=%s",str.GetData());
  3530. }else{
  3531. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryTaskStatus error");
  3532. return rc;
  3533. }
  3534. rc = spConfig->ReadConfigValue("UpgradeManager", "SendSM3TaskUrl", str);
  3535. if(rc==Error_Succeed){
  3536. m_centerUrl.sendSM3TaskUrl = str;
  3537. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini SendSM3TaskUrl=%s",str.GetData());
  3538. }else{
  3539. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini SendSM3TaskUrl error");
  3540. return rc;
  3541. }
  3542. //新的下载分段切片长度值(单位K)
  3543. rc = spConfig->ReadConfigValue("UpgradeManager", "NewEachDownloadLen", str);
  3544. if(rc==Error_Succeed){
  3545. if(str.IsNullOrEmpty()){
  3546. m_newEachDownloadLen = DOWNLOAD_CONTENT_EACH_LEN;
  3547. }else{
  3548. if(atoi(str.GetData())>16){
  3549. m_newEachDownloadLen = atoi(str.GetData())*1024;
  3550. }else{
  3551. m_newEachDownloadLen = 16*1024;//设置默认最小值
  3552. }
  3553. }
  3554. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini NewEachDownloadLen=%d K", m_newEachDownloadLen);
  3555. }else{
  3556. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini NewEachDownloadLen error");
  3557. return rc;
  3558. }
  3559. //加载是否打印http通讯日志
  3560. int printlogInt =0;
  3561. rc = spConfig->ReadConfigValueInt("UpgradeManager", "PrintLog", printlogInt);
  3562. if(rc==Error_Succeed){
  3563. if(printlogInt==0){
  3564. m_PrintHttpLog = false;
  3565. }else{
  3566. m_PrintHttpLog = true;
  3567. }
  3568. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini PrintLog=%d",printlogInt);
  3569. }else{
  3570. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini PrintLog error");
  3571. return rc;
  3572. }
  3573. int startFlagInt =0;
  3574. rc = spConfig->ReadConfigValueInt("UpgradeManager", "StartFlag", startFlagInt);
  3575. if(rc==Error_Succeed){
  3576. if(startFlagInt==0){
  3577. m_startFlag = false;
  3578. }else{
  3579. m_startFlag = true;
  3580. }
  3581. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini StartFlag=%d",startFlagInt);
  3582. }else{
  3583. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini StartFlag error");
  3584. return rc;
  3585. }
  3586. int queryNewTaskInterval = 0;
  3587. rc = spConfig->ReadConfigValueInt("UpgradeManager", "queryNewTaskInterval", queryNewTaskInterval);
  3588. if (rc == Error_Succeed) {
  3589. if (queryNewTaskInterval != 0) {
  3590. if (queryNewTaskInterval < 10) {
  3591. m_queryNewTaskInterval = 10;
  3592. }
  3593. else {
  3594. m_queryNewTaskInterval = queryNewTaskInterval;
  3595. }
  3596. }
  3597. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init read CenterSetting.ini queryNewTaskInterval=%d", m_queryNewTaskInterval);
  3598. }
  3599. else {
  3600. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini queryNewTaskInterval error");
  3601. return rc;
  3602. }
  3603. int installStopCopyDep = 0;
  3604. rc = spConfig->ReadConfigValueInt("UpgradeManager", "installStopCopyDep", installStopCopyDep);
  3605. if (rc == Error_Succeed) {
  3606. if (installStopCopyDep == 1) {
  3607. m_installStopCopyDep = true;//配置1时停止拷贝
  3608. }
  3609. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init read CenterSetting.ini installStopCopyDep=%d", m_installStopCopyDep);
  3610. }
  3611. else {
  3612. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini installStopCopyDep error");
  3613. return rc;
  3614. }
  3615. //加载扫描hash配置文件列表
  3616. rc = spConfig->ReadConfigValue("UpgradeManager", "relativeDir", str);
  3617. if(rc==Error_Succeed){
  3618. m_hashScanSet.relativeDir = str;
  3619. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini relativeDir=%s",str.GetData());
  3620. }else{
  3621. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini relativeDir error");
  3622. return rc;
  3623. }
  3624. rc = spConfig->ReadConfigValue("UpgradeManager", "absoluteDir", str);
  3625. if(rc==Error_Succeed){
  3626. m_hashScanSet.absoluteDir = str;
  3627. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini absoluteDir=%s",str.GetData());
  3628. }else{
  3629. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini absoluteDir error");
  3630. return rc;
  3631. }
  3632. rc = spConfig->ReadConfigValue("UpgradeManager", "currVerDir", str);
  3633. if(rc==Error_Succeed){
  3634. m_hashScanSet.currVerDir = str;
  3635. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini currVerDir=%s",str.GetData());
  3636. }else{
  3637. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini currVerDir error");
  3638. return rc;
  3639. }
  3640. rc = spConfig->ReadConfigValue("UpgradeManager", "blackFile", str);
  3641. if(rc==Error_Succeed){
  3642. m_hashScanSet.blackFile = str;
  3643. CAutoArray<CSimpleStringA> arr = str.Split('|');
  3644. for(int i=0; i< arr.GetCount(); i++)
  3645. {
  3646. m_FileBlacklist.push_back(arr[i]);
  3647. }
  3648. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini blackFile=%s",str.GetData());
  3649. }else{
  3650. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini blackFile error");
  3651. return rc;
  3652. }
  3653. rc = spConfig->ReadConfigValue("UpgradeManager", "blackDir", str);
  3654. if(rc==Error_Succeed){
  3655. m_hashScanSet.blackDir = str;
  3656. CAutoArray<CSimpleStringA> arr = str.Split('|');
  3657. for(int i=0; i< arr.GetCount(); i++)
  3658. {
  3659. m_DirBlacklist.push_back(arr[i]);
  3660. }
  3661. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini blackDir=%s",str.GetData());
  3662. }else{
  3663. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini blackDir error");
  3664. return rc;
  3665. }
  3666. }else{
  3667. LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini error");
  3668. return rc;
  3669. }
  3670. return Error_Succeed;
  3671. }
  3672. bool CUpgradeTaskFSM::GetFileLength(const char* filePath,long &fileLen)
  3673. {
  3674. FILE* file = fopen(filePath, "rb");
  3675. if (file!=NULL)
  3676. {
  3677. #ifdef RVC_OS_WIN
  3678. fileLen = filelength(fileno(file));
  3679. fclose(file);
  3680. return true;
  3681. #else
  3682. if (fseek(file, 0, SEEK_END)!=0) {
  3683. Dbg("GetFileLength fseek is error,%s",strerror(errno));
  3684. fclose(file);
  3685. fileLen = 0;
  3686. return false;
  3687. }
  3688. fileLen = ftell(file); ///求出当前文件指针距离文件开始的字节数
  3689. if (fileLen == -1) {
  3690. Dbg("GetFileLength ftell is error,%s", strerror(errno));
  3691. fclose(file);
  3692. fileLen = 0;
  3693. return false;
  3694. }
  3695. else {
  3696. fclose(file);
  3697. return true;
  3698. }
  3699. #endif
  3700. } else{
  3701. fileLen = 0;
  3702. return false;
  3703. }
  3704. return true;
  3705. }
  3706. ErrorCodeEnum CUpgradeTaskFSM::GetSM3List(CSimpleStringA &strSM3List)
  3707. {
  3708. if (!m_fileSM3List.IsNullOrEmpty())
  3709. {
  3710. strSM3List = m_fileSM3List;
  3711. return Error_Succeed;
  3712. }
  3713. m_fileSM3Map.clear();//生成文件hash列表前先清空
  3714. //根据配置项开始扫描文件和计算hash
  3715. ErrorCodeEnum rc = Error_Succeed ;
  3716. if(!m_hashScanSet.absoluteDir.IsNullOrEmpty()){
  3717. //绝对路径扫描
  3718. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetSM3List scan absoluteDir=%s",m_hashScanSet.absoluteDir.GetData());
  3719. rc = ScanSM3ByType(1,m_hashScanSet.absoluteDir);
  3720. if(rc!=Error_Succeed){
  3721. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan absoluteDir is fail");
  3722. return rc;
  3723. }
  3724. }
  3725. if(!m_hashScanSet.relativeDir.IsNullOrEmpty()){
  3726. //相对路径扫描
  3727. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetSM3List scan relativeDir=%s",m_hashScanSet.relativeDir.GetData());
  3728. ScanSM3ByType(2,m_hashScanSet.relativeDir);
  3729. if(rc!=Error_Succeed){
  3730. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan relativeDir is fail");
  3731. return rc;
  3732. }
  3733. }
  3734. if(!m_hashScanSet.currVerDir.IsNullOrEmpty()){
  3735. //当前版本扫描
  3736. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetSM3List scan currVerDir=%s",m_hashScanSet.currVerDir.GetData());
  3737. ScanSM3ByType(3,m_hashScanSet.currVerDir);
  3738. if(rc!=Error_Succeed){
  3739. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan currVerDir is fail");
  3740. return rc;
  3741. }
  3742. }
  3743. if(m_iBlackFileCount>50){
  3744. LogWarn(Severity_Low, rc, WARN_BLACK_FILE_SUM, CSimpleStringA::Format("get MD5List black file count=%d",m_iBlackFileCount));
  3745. }
  3746. m_iBlackFileCount=0;
  3747. for(auto it=m_fileSM3Map.begin(); it!=m_fileSM3Map.end(); it++)
  3748. {
  3749. strSM3List += it->first;
  3750. strSM3List += ",";
  3751. strSM3List += it->second;
  3752. strSM3List += ";";
  3753. }
  3754. m_fileSM3List = strSM3List;
  3755. return Error_Succeed;
  3756. }
  3757. ErrorCodeEnum CUpgradeTaskFSM::ScanSM3ByType(int type,CSimpleStringA pathFilter)
  3758. {
  3759. if(!pathFilter.IsNullOrEmpty()){
  3760. CSimpleStringA rootPath;//根路径
  3761. CSimpleStringA replacePath;//替换路径
  3762. CSimpleStringA currPath;//当前版本路径
  3763. CSimpleStringA tempPath ="";
  3764. ErrorCodeEnum Error =m_pEntity->GetFunction()->GetPath("Root",tempPath);//例如:C:\Run /opt/Run
  3765. if(Error_Succeed == Error){
  3766. if(!tempPath.IsNullOrEmpty()){
  3767. string runPathStr = tempPath.GetData();
  3768. int pos = runPathStr.find_last_of(SPLIT_SLASH);
  3769. rootPath = runPathStr.substr(0,pos).c_str();
  3770. }else{
  3771. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get Root path is null");
  3772. return Error_Null;
  3773. }
  3774. }else{
  3775. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get Root path is error");
  3776. return Error;
  3777. }
  3778. CSimpleStringA tempCurrPath = "";
  3779. Error =m_pEntity->GetFunction()->GetPath("Base",tempCurrPath);//例如:C:\Run\version\4.8.1.1 /opt/Run/version/4.8.1.1
  3780. if(Error_Succeed == Error){
  3781. if(!tempCurrPath.IsNullOrEmpty()){
  3782. currPath = tempCurrPath;
  3783. }else{
  3784. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get currVer path is null");
  3785. return Error_Null;
  3786. }
  3787. }else{
  3788. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get currVer path is error");
  3789. return Error;
  3790. }
  3791. //路径扫描
  3792. CAutoArray<CSimpleStringA> copyList = pathFilter.Split('|');
  3793. for(int i=0; i<copyList.GetCount(); i++)
  3794. {
  3795. CSimpleStringA file = copyList[i];
  3796. #ifdef RVC_OS_WIN
  3797. #else
  3798. //UOS把路径改为反斜杠
  3799. string replaceStr = file.GetData();
  3800. std::replace(replaceStr.begin(), replaceStr.end(), '\\', '/');
  3801. file = replaceStr.c_str();
  3802. #endif
  3803. if(file.IsNullOrEmpty()){
  3804. continue;
  3805. }else{
  3806. //构造扫描的绝对路径
  3807. CSimpleStringA scanFilter = "";
  3808. CSimpleStringA replaceDir = "";
  3809. if(type==1){
  3810. //绝对路径
  3811. scanFilter = file;
  3812. replaceDir = GetFileDirectory(file.GetData());
  3813. }else if(type==2){
  3814. //相对路径
  3815. scanFilter = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),file.GetData());
  3816. replaceDir = GetFileDirectory(file.GetData());
  3817. }else if(type==3){
  3818. //当前版本路径:特殊处理下替换路径为Run\version\4.8.1.1
  3819. scanFilter = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",currPath.GetData(),file.GetData());
  3820. CSimpleStringA temp = scanFilter.SubString(rootPath.GetLength()+1,scanFilter.GetLength()-(rootPath.GetLength()+1));
  3821. replaceDir = GetFileDirectory(temp.GetData());
  3822. }
  3823. //替换路径前缀
  3824. ErrorCodeEnum ret = NewSM3Folder(scanFilter,replaceDir);
  3825. if(ret!=Error_Succeed){
  3826. return ret;
  3827. }
  3828. }
  3829. }
  3830. }
  3831. return Error_Succeed;
  3832. }
  3833. ErrorCodeEnum CUpgradeTaskFSM::NewSM3Folder(CSimpleStringA scanFilter,CSimpleStringA replaceDir)
  3834. {
  3835. if(scanFilter.IsNullOrEmpty()){
  3836. return Error_Succeed;
  3837. }
  3838. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("scan file scanFilter is %s",scanFilter.GetData());
  3839. //通配符
  3840. if(scanFilter.IndexOf("*")>0){
  3841. //找到要扫描的文件夹
  3842. CSimpleStringA strFileDir = GetFileDirectory(scanFilter.GetData());
  3843. //过滤通配条件
  3844. CSimpleStringA strFileFilter = _GetFileName(scanFilter.GetData());
  3845. list<CSimpleStringA> fileList;
  3846. //获取所有根文件夹下的文件相对路径:如mod\test.dll
  3847. RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
  3848. for(auto it = fileList.begin(); it != fileList.end(); it++)
  3849. {
  3850. CSimpleStringA tempFile = *it;
  3851. if (IsFileMatch(strFileFilter, _GetFileName(tempFile.GetData())))
  3852. {
  3853. CSimpleStringA tempFullName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",strFileDir.GetData(),tempFile.GetData());
  3854. CSimpleStringA tempFileName = _GetFileName(tempFile.GetData());
  3855. CSimpleStringA tempFileDir = GetFileDirectory(tempFile.GetData());
  3856. //整个黑名单文件过滤
  3857. bool isBlackFile = false;
  3858. list<CSimpleStringA>::iterator itorFile = m_FileBlacklist.begin();
  3859. while(itorFile!=m_FileBlacklist.end())
  3860. {
  3861. CSimpleStringA fileBlack = *itorFile;
  3862. //if(tempFileName.IsEndWith(fileBlack.GetData(),true)){
  3863. // isBlackFile=true;
  3864. // break;
  3865. //}
  3866. if(IsFileMatch(fileBlack.GetData(),tempFileName.GetData())){
  3867. isBlackFile=true;
  3868. break;
  3869. }
  3870. itorFile++;
  3871. }
  3872. if(isBlackFile){
  3873. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackFile Filter don't add to md5 list, file = [%s]", tempFullName.GetData());
  3874. m_iBlackFileCount++;
  3875. continue;
  3876. }
  3877. //整个黑名单文件夹过滤
  3878. bool isBlackDir = false;
  3879. list<CSimpleStringA>::iterator itorDir = m_DirBlacklist.begin();
  3880. while(itorDir!=m_DirBlacklist.end())
  3881. {
  3882. CSimpleStringA dirBlack = *itorDir;
  3883. if(tempFileDir.IndexOf(dirBlack.GetData())>0){
  3884. isBlackDir=true;
  3885. break;
  3886. }
  3887. itorDir++;
  3888. }
  3889. if(isBlackDir){
  3890. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackDir Filter don't add to md5 list, dir = [%s]", tempFullName.GetData());
  3891. continue;
  3892. }
  3893. //计算hash值,加入到hash列表
  3894. CSimpleStringA strMD5Val;
  3895. ErrorCodeEnum rErrcode = SM3FileToStr(tempFullName, strMD5Val,false);
  3896. if (Error_Succeed != rErrcode)
  3897. {
  3898. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("%s get sm3 fail ,error:%d", tempFullName.GetData(), (int)rErrcode);
  3899. return rErrcode;
  3900. }
  3901. CSimpleStringA relativePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",replaceDir.GetData(),tempFile.GetData());
  3902. //Dbg("scan file succ [%s]",relativePath.GetData());
  3903. m_fileSM3Map[relativePath] = strMD5Val;
  3904. Sleep(100);//时间片
  3905. }
  3906. }
  3907. }else{
  3908. if(ExistsFileA(scanFilter.GetData())){
  3909. //整个黑名单文件过滤
  3910. bool isBlackFile = false;
  3911. CSimpleStringA tempFileName = _GetFileName(scanFilter.GetData());//文件名称
  3912. CSimpleStringA tempFileDir = GetFileDirectory(scanFilter.GetData());//文件夹名称
  3913. list<CSimpleStringA>::iterator itorFile = m_FileBlacklist.begin();
  3914. while(itorFile!=m_FileBlacklist.end())
  3915. {
  3916. CSimpleStringA fileBlack = *itorFile;
  3917. //if(scanFilter.IsEndWith(fileBlack.GetData(),true)){
  3918. // isBlackFile=true;
  3919. // break;
  3920. //}
  3921. if(IsFileMatch(fileBlack.GetData(),tempFileName.GetData())){
  3922. isBlackFile=true;
  3923. break;
  3924. }
  3925. itorFile++;
  3926. }
  3927. if(isBlackFile){
  3928. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackFile Filter don't add to md5 list, file = [%s]", scanFilter.GetData());
  3929. m_iBlackFileCount++;
  3930. }
  3931. //整个黑名单文件夹过滤
  3932. bool isBlackDir = false;
  3933. list<CSimpleStringA>::iterator itorDir = m_DirBlacklist.begin();
  3934. while(itorDir!=m_DirBlacklist.end())
  3935. {
  3936. CSimpleStringA dirBlack = *itorDir;
  3937. if(tempFileDir.IndexOf(dirBlack.GetData())>0){
  3938. isBlackDir=true;
  3939. break;
  3940. }
  3941. itorDir++;
  3942. }
  3943. if(isBlackDir){
  3944. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackDir Filter don't add to md5 list, dir = [%s]", scanFilter.GetData());
  3945. }
  3946. if(!isBlackDir&&!isBlackFile){
  3947. //加入hash列表
  3948. CSimpleStringA strMD5Val;
  3949. ErrorCodeEnum rErrcode = SM3FileToStr(scanFilter, strMD5Val,false);
  3950. if (Error_Succeed != rErrcode)
  3951. {
  3952. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("%s get sm3 fail ,error:%d", scanFilter.GetData(), (int)rErrcode);
  3953. return rErrcode;
  3954. }
  3955. CSimpleStringA tempFileName = _GetFileName(scanFilter.GetData());
  3956. CSimpleStringA relativePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",replaceDir.GetData(),tempFileName.GetData());
  3957. //Dbg("scan file succ [%s]",relativePath.GetData());
  3958. #ifdef RVC_OS_WIN
  3959. #else
  3960. Sleep(100);//加入时间碎片
  3961. #endif
  3962. m_fileSM3Map[relativePath] = strMD5Val;
  3963. }
  3964. }
  3965. }
  3966. return Error_Succeed;
  3967. }
  3968. ErrorCodeEnum CUpgradeTaskFSM::RollBackVersionCheck(string& failReason, CSimpleStringA& strErrMsg)
  3969. {
  3970. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin RollBackVersionCheck");
  3971. //获取新版本号
  3972. CSimpleStringA rootVerPath;
  3973. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer", rootVerPath);//获取version根路径
  3974. if (rc != Error_Succeed) {
  3975. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RollBackVersionCheck fail , get RootVer path is fail");
  3976. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "RollBackVersionCheck: get RootVer path is fail");
  3977. failReason = "C";
  3978. strErrMsg = "RollBackVersionCheck fail , get RootVer path is fail";
  3979. return Error_Bug;
  3980. }
  3981. CSimpleStringA strRollbackVersion = m_currentTask.pack_version;
  3982. CVersion curVer = m_currentVersion;//当前版本号
  3983. // 指定版本
  3984. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  3985. int n = sscanf(strRollbackVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  3986. if (n != 4)
  3987. {
  3988. strErrMsg = CSimpleStringA::Format("指定回退版本号无效(%s)", strRollbackVersion.GetData());
  3989. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("specified Rollback version is invalid: [%s]", strRollbackVersion.GetData()).GetData());
  3990. failReason = "C";
  3991. strErrMsg = CSimpleStringA::Format("specified Rollback version is invalid: [%s]", strRollbackVersion.GetData());
  3992. return Error_Bug;
  3993. }
  3994. else {
  3995. m_currentTask.NewVersion = strRollbackVersion;//赋值回退版本号给内存变量
  3996. }
  3997. if (curVer.ToString() == strRollbackVersion) {
  3998. //版本号相同,
  3999. strErrMsg = CSimpleStringA::Format("指定回退版本号与当前版本相同,无效(配置:%s, 当前:%s)", strRollbackVersion.GetData(), curVer.ToString().GetData());
  4000. failReason = "X";
  4001. return Error_Unexpect;
  4002. }
  4003. else if (dwMajor > curVer.GetMajor()
  4004. || (dwMajor == curVer.GetMajor() && dwMinor > curVer.GetMinor())
  4005. || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision > curVer.GetRevision())
  4006. || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision == curVer.GetRevision() && dwBuild > curVer.GetBuild())) {
  4007. //升级版本大于当前版本
  4008. strErrMsg = CSimpleStringA::Format("指定回退版本号大于当前版本号(配置:%s,当前:%s)", strRollbackVersion.GetData(), curVer.ToString().GetData());
  4009. failReason = "X";
  4010. return Error_Unexpect;
  4011. }
  4012. //回退版本是否存在
  4013. CSimpleStringA strRollbackVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.NewVersion.GetData());
  4014. if (!ExistsDirA(strRollbackVerPath.GetData())) {
  4015. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("RollBackVersionCheck fail, strRollbackVerPath =%s is not exist,fail", strRollbackVerPath.GetData()).GetData());
  4016. strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", strRollbackVersion.GetData());
  4017. failReason = "X";
  4018. return Error_Unexpect;
  4019. }
  4020. return Error_Succeed;
  4021. }
  4022. void CUpgradeTaskFSM::judgeTaskClass()
  4023. {
  4024. m_TempDepUpgradeFlag = false;//每次安装前初始化。
  4025. //临时方案判定是适配器升级还是应用升级
  4026. if (isTerminalInstall()) {
  4027. //安装时判断
  4028. if (m_currentTask.pack_name.IndexOf("adapter") != -1) {
  4029. m_TempDepUpgradeFlag = true;
  4030. }
  4031. }
  4032. else {
  4033. //非安装时判断:判断只有一条拷贝dep路径的策略
  4034. if (!m_currentTask.install_step.empty()) {
  4035. int iCount = m_currentTask.install_step.size();
  4036. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d", iCount);
  4037. if (iCount == 1) {
  4038. CInstallStep* tmp = m_currentTask.install_step.front();
  4039. if (tmp->cmdType == "Copy") {
  4040. if (tmp->srcPathType == "3") {
  4041. CSimpleStringA depStr = "";
  4042. depStr.Append(SPLIT_SLASH_STR).Append("dep").Append(SPLIT_SLASH_STR); //win :\dep\ uos: /dep/
  4043. if (tmp->srcPath.IndexOf(depStr.GetData()) != -1) {
  4044. m_TempDepUpgradeFlag = true;
  4045. }
  4046. }
  4047. }
  4048. }
  4049. }
  4050. }
  4051. }
  4052. ErrorCodeEnum CUpgradeTaskFSM::judgeRollbackTaskClass(CSimpleStringA verDirName, string& failReason, CSimpleStringA& strErrMsg)
  4053. {
  4054. //搜索终端应用目录,适配器应用目录,
  4055. CSimpleStringA depPathStr(true);
  4056. CSimpleStringA verPathStr(true);
  4057. ErrorCodeEnum Err = GetEntityBase()->GetFunction()->GetPath("DepBase", depPathStr);
  4058. if (Err != Error_Succeed) {
  4059. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("judgeRollbackTaskClass fail , get DepBase path is fail");
  4060. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "judgeRollbackTaskClass: get DepBase path is fail");
  4061. failReason = "C";
  4062. strErrMsg = "judgeRollbackTaskClass fail , get DepBase path is fail";
  4063. return Error_Bug;
  4064. }
  4065. Err = m_pEntity->GetFunction()->GetPath("RootVer", verPathStr);
  4066. if (Err != Error_Succeed) {
  4067. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("judgeRollbackTaskClass fail , get RootVer path is fail");
  4068. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "judgeRollbackTaskClass: get RootVer path is fail");
  4069. failReason = "C";
  4070. strErrMsg = "judgeRollbackTaskClass fail , get RootVer path is fail";
  4071. return Error_Bug;
  4072. }
  4073. CSimpleStringA strDestDir = "";
  4074. if (DirIsExist(verPathStr.GetData(), verDirName.GetData())) {
  4075. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("app version dir find is ok,dir=%s", verDirName.GetData());
  4076. m_TempDepUpgradeFlag = false;//应用版本
  4077. return Error_Succeed;
  4078. }
  4079. else if (DirIsExist(depPathStr.GetData(), verDirName.GetData())) {
  4080. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("dep version dir find is ok, dir=%s", verDirName.GetData());
  4081. m_TempDepUpgradeFlag = true;//适配器版本
  4082. return Error_Succeed;
  4083. }
  4084. else {
  4085. CSimpleStringA errStr = CSimpleStringA::Format("judgeRollbackTaskClass fail, RollbackVerRootPath =[%s|%s] not find version dir [%s],fail", verPathStr.GetData(), depPathStr.GetData(), verDirName.GetData());
  4086. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, errStr.GetData());
  4087. strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", verDirName.GetData());
  4088. failReason = "X";
  4089. return Error_Unexpect;//不存在
  4090. }
  4091. }
  4092. bool CUpgradeTaskFSM::DirIsExist(const char* scanPath, const char* dirName)
  4093. {
  4094. CSimpleStringA strDestDir = "";
  4095. if (dirName == NULL||scanPath==NULL) {
  4096. return false;
  4097. }
  4098. auto subdirs = fileutil_get_sub_dirs(scanPath);
  4099. if (subdirs != NULL)
  4100. {
  4101. bool isMatch = false;
  4102. for (int i = 0; i < subdirs->nelts; ++i)
  4103. {
  4104. const char* dir = ARRAY_IDX(subdirs, i, char*);
  4105. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("dir=%s,dirName=%s", dir, dirName);
  4106. CSimpleStringA dirNameStr = dirName;
  4107. if (dirNameStr.Compare(_GetFileName(dir))==0) {
  4108. isMatch = true;
  4109. break;
  4110. }
  4111. }
  4112. toolkit_array_free2(subdirs);
  4113. return isMatch;
  4114. }
  4115. else {
  4116. return false;
  4117. }
  4118. }
  4119. int CUpgradeTaskFSM::ExecDepInstall(CSimpleStringA& strErrMsg)
  4120. {
  4121. if (!isTerminalInstall()) {
  4122. //升级
  4123. if (!m_currentTask.pack_version.IsNullOrEmpty()) {
  4124. CSimpleStringA strUpgradeDepVersion = m_currentTask.pack_version;
  4125. CSimpleStringA latterDepVersion;//要更新到的版本号
  4126. CSimpleStringA curVer = m_currentDepVersion;//当前版本号
  4127. // 指定版本
  4128. latterDepVersion = strUpgradeDepVersion.GetData();
  4129. if (curVer == strUpgradeDepVersion) {
  4130. //版本号相同
  4131. strErrMsg = CSimpleStringA::Format("指定升级适配器版本号与当前版本相同,无效(配置:%s, 当前:%s)", strUpgradeDepVersion.GetData(), curVer.GetData());
  4132. return 0;
  4133. }
  4134. CSimpleStringA strErrInfo = "";
  4135. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateNewDepVersion,version[%s],pack[%s]", strUpgradeDepVersion.GetData(), m_currentTask.pack_name.GetData());
  4136. ErrorCodeEnum rc = CreateNewDepVersion(latterDepVersion, strErrInfo);
  4137. if (rc != Error_Succeed)
  4138. {
  4139. strErrMsg = CSimpleStringA::Format("CreateNewDepVersion fail:%s", strErrInfo.GetData());
  4140. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewDepVersion,version[%s] fail:%s", strUpgradeDepVersion.GetData(), strErrInfo.GetData());
  4141. //清理临时版本文件夹
  4142. ClearUpgradeFailDepVersion(latterDepVersion);
  4143. return 0;
  4144. }
  4145. else {
  4146. m_currentTask.depNewVersion = strUpgradeDepVersion;//赋值升级适配器版本号给内存变量
  4147. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewDepVersion,version[%s] succ", strUpgradeDepVersion.GetData());
  4148. }
  4149. }
  4150. else {
  4151. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDepInstall fail ,pack_version is null");
  4152. return 0;
  4153. }
  4154. }
  4155. else {
  4156. //新安装,无值则填写默认初始版本号
  4157. if (m_currentTask.pack_version.IsNullOrEmpty()) {
  4158. m_currentTask.pack_version = "0.0.0.1";//新安装,默认初始适配器版本
  4159. m_currentTask.depNewVersion = "0.0.0.1";
  4160. }
  4161. else {
  4162. m_currentTask.depNewVersion = m_currentTask.pack_version.GetData();
  4163. }
  4164. if (m_installStopCopyDep) {
  4165. //不需要拷贝dep公共库
  4166. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("installStopCopyDep is %d , No need to copy common Dep dir", m_installStopCopyDep);
  4167. }
  4168. else {
  4169. //兼容拷贝dep公共库
  4170. CSimpleStringA strErrInfo = "";
  4171. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateInstallDepVersion,version[%s],pack[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.pack_name.GetData());
  4172. ErrorCodeEnum rc = CreateInstallDepVersion(m_currentTask.depNewVersion, strErrInfo);
  4173. if (rc != Error_Succeed)
  4174. {
  4175. strErrMsg = CSimpleStringA::Format("CreateInstallDepVersion fail:%s", strErrInfo.GetData());
  4176. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateInstallDepVersion,version[%s] fail:%s", m_currentTask.depNewVersion.GetData(), strErrInfo.GetData());
  4177. //清理临时版本文件夹
  4178. ClearUpgradeFailDepVersion(m_currentTask.depNewVersion);
  4179. return 0;
  4180. }
  4181. else {
  4182. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateInstallDepVersion,version[%s] succ", m_currentTask.depNewVersion.GetData());
  4183. }
  4184. }
  4185. }
  4186. //循环执行安装命令
  4187. int iRet = 1;//默认是成功
  4188. if (!m_currentTask.install_step.empty()) {
  4189. int iCount = m_currentTask.install_step.size();
  4190. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install Dep cmd size = %d", iCount);
  4191. for (int j = 0; j < iCount; j++) {
  4192. CInstallStep* tmp = m_currentTask.install_step.front();
  4193. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====begin Dep cmd=[%s]=====", tmp->cmdType.GetData());
  4194. //开始处理具体命令
  4195. if (tmp->cmdType == "Delete") {
  4196. bool ret = ExecDepDeleteCmd(strErrMsg, tmp);
  4197. if (!ret) {
  4198. //报错才判断
  4199. if (tmp->cmdFail == 0) {
  4200. iRet = 0;
  4201. break;//出错直接退出
  4202. }
  4203. else if (tmp->cmdFail == 1) {
  4204. //继续
  4205. }
  4206. else {
  4207. iRet = 0;
  4208. break;//其他值也退出
  4209. }
  4210. }
  4211. }
  4212. else if (tmp->cmdType == "Copy") {
  4213. bool ret = ExecDepCpoyCmd(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 == "Run") {
  4230. int retInt = ExecDepRunCmd(strErrMsg, tmp);
  4231. if (retInt == 0 || retInt == -1) {
  4232. //报错才判断
  4233. if (tmp->cmdFail == 0) {
  4234. iRet = retInt;//会有0,-1值
  4235. break;//出错直接退出,并返回体系外结果
  4236. }
  4237. else if (tmp->cmdFail == 1) {
  4238. //继续
  4239. }
  4240. else {
  4241. iRet = 0;
  4242. break;//其他值也退出
  4243. }
  4244. }
  4245. }
  4246. else {
  4247. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cmd=[%s] is invalid", tmp->cmdType.GetData());
  4248. iRet = 0;
  4249. break;//命令无效直接退出
  4250. }
  4251. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====end Dep cmd=[%s]=====", tmp->cmdType.GetData());
  4252. m_currentTask.install_step.pop();//去除元素
  4253. delete tmp;//删除内存
  4254. }
  4255. }
  4256. return iRet;//返回处理结果
  4257. }
  4258. ErrorCodeEnum CUpgradeTaskFSM::CreateNewDepVersion(CSimpleStringA NewSoftwareVersion, CSimpleStringA& strErrInfo)
  4259. {
  4260. // 创建新适配器版本
  4261. CSimpleStringA rootDepPath;
  4262. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("DepBase", rootDepPath);//适配器根路径
  4263. if (rc != Error_Succeed) {
  4264. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail , get DepBase path is fail");
  4265. strErrInfo = CSimpleStringA::Format("Create new dep version fail , get DepBase path is fail");
  4266. return Error_Bug;
  4267. }
  4268. CSimpleStringA strCurDepPath;
  4269. rc = m_pEntity->GetFunction()->GetPath("Dep", strCurDepPath);//获取当前适配器根路径
  4270. if (rc != Error_Succeed) {
  4271. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail , get Dep path is fail");
  4272. strErrInfo = CSimpleStringA::Format("Create new dep version fail , get Dep path is fail");
  4273. return Error_Bug;
  4274. }
  4275. //新路径
  4276. CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootDepPath.GetData(), NewSoftwareVersion.GetData());
  4277. if (m_currentDepVersion == NewSoftwareVersion)
  4278. {
  4279. 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());
  4280. strErrInfo = CSimpleStringA::Format("new ver [%s] equals current ver [%s]", NewSoftwareVersion.GetData(), m_currentDepVersion.GetData());
  4281. return Error_Bug;
  4282. }
  4283. if (ExistsDirA(strNewVerPath.GetData()))
  4284. {
  4285. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new version dir [%s] already exist, delete it", strNewVerPath.GetData());
  4286. if (!RemoveDirRecursiveA(strNewVerPath.GetData())) {
  4287. #ifdef RVC_OS_WIN
  4288. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail, delete already exist new dep version is fail:%d", GetLastError());
  4289. strErrInfo = CSimpleStringA::Format("Create new dep version fail, delete already exist new dep version is fail:%d", (int)GetLastError());
  4290. #else
  4291. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail, delete already exist new dep version is fail:%d", errno);
  4292. strErrInfo = CSimpleStringA::Format("Create new dep version fail, delete already exist new dep version is fail:%d", errno);
  4293. #endif
  4294. return Error_Bug;
  4295. }
  4296. }
  4297. if (!CreateDirA(strNewVerPath.GetData(), TRUE))
  4298. {
  4299. #ifdef RVC_OS_WIN
  4300. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version dir fail: %d", GetLastError());
  4301. strErrInfo = CSimpleStringA::Format("create new dep version dir fail: %d", (int)GetLastError());
  4302. #else
  4303. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version dir fail: %d", errno);
  4304. strErrInfo = CSimpleStringA::Format("create new dep version dir fail: %d", errno);
  4305. #endif
  4306. return Error_Unexpect;
  4307. }
  4308. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create new dep version dir succ, dir = %s", strNewVerPath.GetData());
  4309. //增加错误信息字段,回传给上层应用
  4310. CSimpleStringA strErrMsg = "";
  4311. CSimpleStringA strSource = CSimpleStringA::Format("%s", strCurDepPath.GetData());
  4312. CSimpleStringA strDest = CSimpleStringA::Format("%s", strNewVerPath.GetData());
  4313. if (!RecursiveCopyDir(strSource, strDest, strErrMsg))
  4314. {
  4315. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
  4316. strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
  4317. return Error_Unexpect;
  4318. }
  4319. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
  4320. return Error_Succeed;
  4321. }
  4322. ErrorCodeEnum CUpgradeTaskFSM::CreateInstallDepVersion(CSimpleStringA NewSoftwareVersion, CSimpleStringA& strErrInfo)
  4323. {
  4324. LOG_FUNCTION();
  4325. CSimpleStringA strCurVerPath;
  4326. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Base", strCurVerPath);//获取当前应用version路径
  4327. if (rc != Error_Succeed) {
  4328. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new Install dep version fail , get Base path is fail");
  4329. strErrInfo = CSimpleStringA::Format("Create new Install dep version fail , get Base path is fail");
  4330. return Error_Bug;
  4331. }
  4332. CSimpleStringA strCurrDepPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strCurVerPath.GetData());
  4333. if (ExistsDirA(strCurrDepPath.GetData())) {
  4334. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new install common dep dir is exist, begin copy dir = %s", strCurrDepPath.GetData());
  4335. //存在则拷贝公共库dep文件
  4336. CSimpleStringA tempPath;
  4337. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\ /opt/Run/dep/
  4338. if (Error_Succeed == Error) {
  4339. CSimpleStringA strNewDepPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), NewSoftwareVersion.GetData());
  4340. CSimpleStringA strErrMsg = "";
  4341. if (!RecursiveCopyDir(strCurrDepPath.GetData(), strNewDepPath.GetData(), strErrMsg))
  4342. {
  4343. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
  4344. strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
  4345. return Error_Unexpect;
  4346. }
  4347. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
  4348. return Error_Succeed;
  4349. }
  4350. else {
  4351. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new Install dep version fail ,get DepBase path is fail");
  4352. strErrInfo = CSimpleStringA::Format("Create new Install dep version fail , get DepBase path is fail");
  4353. return Error_Bug;
  4354. }
  4355. }
  4356. else {
  4357. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new install common dep dir is not exist, default return true,dir=%s", strCurrDepPath.GetData());
  4358. return Error_Succeed;
  4359. }
  4360. }
  4361. ErrorCodeEnum CUpgradeTaskFSM::ClearUpgradeFailDepVersion(CSimpleStringA NewSoftwareVersion)
  4362. {
  4363. CSimpleStringA rootDepPath;
  4364. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootDepPath);//适配器根路径
  4365. if (rc != Error_Succeed) {
  4366. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion fail , get DepBase path is fail");
  4367. return Error_Bug;
  4368. }
  4369. //新路径
  4370. CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootDepPath.GetData(), NewSoftwareVersion.GetData());
  4371. if (ExistsDirA(strNewVerPath.GetData()))
  4372. {
  4373. if (!RemoveDirRecursiveA(strNewVerPath.GetData())) {
  4374. #ifdef RVC_OS_WIN
  4375. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), (int)GetLastError());
  4376. #else
  4377. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), errno);
  4378. #endif
  4379. return Error_Bug;
  4380. }
  4381. else {
  4382. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion succ, delete temp Version [%s] ", strNewVerPath.GetData());
  4383. return Error_Succeed;
  4384. }
  4385. }
  4386. else {
  4387. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion succ, delete temp Version [%s] is not exist ", strNewVerPath.GetData());
  4388. return Error_Succeed;
  4389. }
  4390. }
  4391. ErrorCodeEnum CUpgradeTaskFSM::UpgradeDepToNewVersion()
  4392. {
  4393. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin UpgradeToDepNewVersion");
  4394. //获取新版本号
  4395. if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
  4396. 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());
  4397. 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());
  4398. return Error_Unexpect;//这种情况有问题,需要清除此任务
  4399. }
  4400. else {
  4401. ErrorCodeEnum ec = Error_Exception;
  4402. if (isTerminalInstall()) {
  4403. //安装需要刷新适配器路径到框架。
  4404. ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(m_currentTask.depNewVersion, true);
  4405. }
  4406. else {
  4407. ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(m_currentTask.depNewVersion, false);
  4408. }
  4409. if (ec != Error_Succeed) {
  4410. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpgradeDepToNewVersion fail, RewriteDepVersion version %s return %s", m_currentTask.depNewVersion.GetData(),SpStrError(ec));
  4411. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion: get RootVer path is fail", m_currentTask.depNewVersion.GetData(), SpStrError(ec)));
  4412. }
  4413. return ec;
  4414. }
  4415. }
  4416. ErrorCodeEnum CUpgradeTaskFSM::SwitchUpgradeDepNow()
  4417. {
  4418. //根据重启策略类型去重启
  4419. //重启策略类型(0:不启动 1:重启框架 2:重启系统)
  4420. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin SwitchUpgradeDepNow");
  4421. if (m_currentTask.reboot_type == 0) {
  4422. 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());
  4423. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  4424. }
  4425. else if (m_currentTask.reboot_type == 1) {
  4426. if (m_currentTask.task_type.Compare("U") == 0) {
  4427. //适配器版本升级
  4428. LogEvent(Severity_Middle, Event_DeviceAdapterUpgrade_Framework_Restart,
  4429. CSimpleStringA::Format("upgrade to new dep version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  4430. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  4431. }
  4432. else if (m_currentTask.task_type.Compare("R") == 0) {
  4433. //适配器版本回退
  4434. LogEvent(Severity_Middle, Event_DeviceAdapterRollBack_Framework_Restart,
  4435. CSimpleStringA::Format("rollback to old dep version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  4436. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  4437. }
  4438. }
  4439. else if (m_currentTask.reboot_type == 2) {
  4440. if (m_currentTask.task_type.Compare("U") == 0) {
  4441. LogEvent(Severity_Middle, Event_DeviceAdapterUpgrade_OS_Restart,
  4442. CSimpleStringA::Format("upgrade to new dep version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  4443. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  4444. }
  4445. else {
  4446. LogEvent(Severity_Middle, Event_DeviceAdapterRollBack_OS_Restart,
  4447. CSimpleStringA::Format("rollback to old dep version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  4448. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  4449. }
  4450. }
  4451. else {
  4452. 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());
  4453. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  4454. }
  4455. // 强制刷新日志
  4456. m_pEntity->GetFunction()->FlushLogFile();
  4457. return Error_Succeed;
  4458. }
  4459. ErrorCodeEnum CUpgradeTaskFSM::RollBackDepVersionCheck(string& failReason, CSimpleStringA& strErrMsg)
  4460. {
  4461. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin RollBackDepVersionCheck");
  4462. //获取新版本号
  4463. CSimpleStringA rootVerPath;
  4464. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootVerPath);//获取version根路径
  4465. if (rc != Error_Succeed) {
  4466. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RollBackDepVersionCheck fail , get DepBase path is fail");
  4467. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "RollBackDepVersionCheck: get DepBase path is fail");
  4468. failReason = "C";
  4469. strErrMsg = "RollBackDepVersionCheck fail , get DepBase path is fail";
  4470. return Error_Bug;
  4471. }
  4472. CSimpleStringA strRollbackVersion = m_currentTask.pack_version;
  4473. CSimpleStringA curDepVer = m_currentDepVersion;//当前版本号
  4474. // 指定版本
  4475. m_currentTask.depNewVersion = strRollbackVersion;//赋值适配器回退版本号给内存变量
  4476. if (curDepVer == strRollbackVersion) {
  4477. //版本号相同,
  4478. strErrMsg = CSimpleStringA::Format("指定回退版本号与当前版本相同,无效(配置:%s, 当前:%s)", strRollbackVersion.GetData(), curDepVer.GetData());
  4479. failReason = "X";
  4480. return Error_Unexpect;
  4481. }
  4482. //回退版本是否存在
  4483. CSimpleStringA strRollbackVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.depNewVersion.GetData());
  4484. if (!ExistsDirA(strRollbackVerPath.GetData())) {
  4485. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("RollBackVersionCheck fail, strRollbackVerPath =%s is not exist,fail", strRollbackVerPath.GetData()).GetData());
  4486. strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", strRollbackVersion.GetData());
  4487. failReason = "X";
  4488. return Error_Unexpect;
  4489. }
  4490. return Error_Succeed;
  4491. }
  4492. ErrorCodeEnum CUpgradeTaskFSM::RollBackToHistoryDepVersion(CSimpleStringA historyDepVersion)
  4493. {
  4494. //判断是否为空
  4495. if (historyDepVersion.IsNullOrEmpty())
  4496. {
  4497. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryDepVersion fail , historyDepVersion is null");
  4498. return Error_Param;
  4499. }
  4500. // 判断目标版本是否等于当前版本
  4501. if (historyDepVersion == m_currentDepVersion) {
  4502. 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());
  4503. return Error_Param;
  4504. }
  4505. // 检查对应文件夹是否存在
  4506. CSimpleStringA rootVerPath;
  4507. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootVerPath);//获取version根路径
  4508. if (rc != Error_Succeed) {
  4509. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryDepVersion fail , get DepBase path is fail");
  4510. return Error_Bug;
  4511. }
  4512. CSimpleStringA strHisVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), historyDepVersion.GetData());
  4513. if (!ExistsDirA(strHisVerPath.GetData()))
  4514. {
  4515. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryDepVersion fail, history version dir [%s] not exists", strHisVerPath.GetData()).GetData());
  4516. return Error_NotExist;
  4517. }
  4518. ErrorCodeEnum ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(historyDepVersion, false);
  4519. if (ec != Error_Succeed) {
  4520. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackToHistoryDepVersion fail, RewriteDepVersion version %s return %s", strHisVerPath.GetData(), SpStrError(ec));
  4521. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryDepVersion fail, RewriteDepVersion version %s return %s", strHisVerPath.GetData(), SpStrError(ec)));
  4522. }
  4523. return ec;
  4524. }
  4525. int CUpgradeTaskFSM::ExecDepRunCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
  4526. {
  4527. CSimpleStringA destPath;//目的路径
  4528. if (ins->dstPathType == "0") {
  4529. CSimpleStringA rootPath;
  4530. if (GetDepRootTypePath(1, rootPath)) {
  4531. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
  4532. }
  4533. else {
  4534. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 1 is fail");
  4535. return false;
  4536. }
  4537. }
  4538. else if (ins->dstPathType == "1") {
  4539. destPath = ins->dstPath;//绝对路径
  4540. }
  4541. else if (ins->dstPathType == "2") {
  4542. CSimpleStringA rootPath;
  4543. if (GetDepRootTypePath(2, rootPath)) {
  4544. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
  4545. }
  4546. else {
  4547. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 2 is fail");
  4548. return false;
  4549. }
  4550. }
  4551. else if (ins->dstPathType == "3") {
  4552. CSimpleStringA rootPath;
  4553. if (GetDepRootTypePath(3, rootPath)) {
  4554. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
  4555. }
  4556. else {
  4557. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 3 is fail");
  4558. return false;
  4559. }
  4560. }
  4561. else if (ins->dstPathType == "4") {
  4562. CSimpleStringA rootPath;
  4563. if (GetDepRootTypePath(4, rootPath)) {
  4564. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级包相对路径
  4565. }
  4566. else {
  4567. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 4 is fail");
  4568. return false;
  4569. }
  4570. }
  4571. else {
  4572. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPathType is invalid %s", ins->dstPathType.GetData());
  4573. strErrMsg = CSimpleStringA::Format("ExecRunCmd destPathType is invalid %s", ins->dstPathType.GetData());
  4574. return false;//不支持的路径类型
  4575. }
  4576. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPath is %s", destPath.GetData());
  4577. // ToRun=install.bat
  4578. if (ExistsFileA(destPath.GetData()))
  4579. {
  4580. #ifdef RVC_OS_WIN
  4581. // window模式下 如果是Wow64模式,需屏蔽System32重定向
  4582. PVOID pRedirectOldValue(NULL);
  4583. bool bIsWow64 = IsWow64Process();
  4584. if (bIsWow64)
  4585. {
  4586. if (!Wow64DisableWow64FsRedirection(&pRedirectOldValue)) {
  4587. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64DisableWow64FsRedirection fail: %d", GetLastError());
  4588. }
  4589. else {
  4590. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64DisableWow64FsRedirection succ");
  4591. }
  4592. }
  4593. #endif
  4594. //system(strSourcePath);
  4595. string sysPathStr = destPath.GetData();
  4596. CSimpleStringA err = "";
  4597. int ret = system_on(sysPathStr, true, err);
  4598. #ifdef RVC_OS_WIN
  4599. // 如果是Wow64模式,恢复System32重定向
  4600. if (bIsWow64)
  4601. {
  4602. if (!Wow64RevertWow64FsRedirection(pRedirectOldValue)) {
  4603. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64RevertWow64FsRedirection fail: %d", GetLastError());
  4604. }
  4605. else {
  4606. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64RevertWow64FsRedirection succ");
  4607. }
  4608. }
  4609. #endif
  4610. if (ret != 0) {
  4611. //程序执行异常,结果未知
  4612. #ifdef RVC_OS_WIN
  4613. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown ,err=%s", err.GetData());
  4614. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ,err=%s", err.GetData());
  4615. #else
  4616. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown , ret=%d, err=%s", ret, strerror(errno));
  4617. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ret=%d, err=%s", ret, strerror(errno));
  4618. #endif
  4619. return -1;//未知结果返回
  4620. }
  4621. else {
  4622. //进一步看返回结果文件判断是否成功
  4623. CSimpleStringA strUnzipPath = GetFileDirectory(destPath.GetData());
  4624. #ifdef RVC_OS_WIN
  4625. CSimpleStringA strResultLog = strUnzipPath + "\\result.log";//结果文件
  4626. #else
  4627. CSimpleStringA strResultLog = strUnzipPath + "/result.log";//结果文件
  4628. #endif
  4629. CSimpleStringA eErrorCode = "";
  4630. //获取结果文件
  4631. if (!GetSysUpgradeResult(strResultLog, eErrorCode, strErrMsg))
  4632. {
  4633. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, get result from result.log fail, %s", strErrMsg.GetData());
  4634. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail ,get result from result.log fail, %s", strErrMsg.GetData());
  4635. return 0;//失败
  4636. }
  4637. if (eErrorCode == "0")
  4638. {
  4639. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is succ,[%s] ", destPath.GetData());
  4640. return 1;//成功
  4641. }
  4642. else {
  4643. #ifdef RVC_OS_WIN
  4644. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
  4645. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
  4646. #else
  4647. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
  4648. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
  4649. #endif
  4650. return 0;//失败
  4651. }
  4652. }
  4653. }
  4654. else
  4655. {
  4656. strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, run file [%s] is not Exist", destPath.GetData());
  4657. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, run file [%s] is not Exist", destPath.GetData());
  4658. return 0;//失败
  4659. }
  4660. }
  4661. bool CUpgradeTaskFSM::ExecDepDeleteCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
  4662. {
  4663. //只删除同一层目录下的文件和文件夹
  4664. CSimpleStringA destPath;//目的路径+通配符
  4665. if (ins->dstPathType == "0") {
  4666. CSimpleStringA rootPath;
  4667. if (GetDepRootTypePath(1, rootPath)) {
  4668. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
  4669. }
  4670. else {
  4671. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 1 is fail");
  4672. return false;
  4673. }
  4674. }
  4675. else if (ins->dstPathType == "1") {
  4676. destPath = ins->dstPath;//绝对路径
  4677. }
  4678. else if (ins->dstPathType == "2") {
  4679. CSimpleStringA rootPath;
  4680. if (GetDepRootTypePath(2, rootPath)) {
  4681. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
  4682. }
  4683. else {
  4684. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 2 is fail");
  4685. return false;
  4686. }
  4687. }
  4688. else if (ins->dstPathType == "3") {
  4689. CSimpleStringA rootPath;
  4690. if (GetDepRootTypePath(3, rootPath)) {
  4691. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
  4692. }
  4693. else {
  4694. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 3 is fail");
  4695. return false;
  4696. }
  4697. }
  4698. else {
  4699. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPathType is invalid %s", ins->dstPathType.GetData());
  4700. strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPathType is invalid %s", ins->dstPathType.GetData());
  4701. return false;//不支持的路径类型
  4702. }
  4703. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPath is %s", destPath.GetData());
  4704. if (destPath.IndexOf("*") > 0) {
  4705. CSimpleStringA strFileFilter = _GetFileName(destPath);
  4706. CSimpleStringA strDestDir = destPath.SubString(0, destPath.GetLength() - strFileFilter.GetLength() - 1);
  4707. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match filter name [%s] in dir [%s]", strFileFilter.GetData(), strDestDir.GetData());
  4708. // 删除所有匹配文件
  4709. bool bRet = true;
  4710. auto arr = fileutil_get_sub_files(strDestDir.GetData());
  4711. if (arr != NULL)
  4712. {
  4713. for (int i = 0; i < arr->nelts; ++i)
  4714. {
  4715. char* file = ARRAY_IDX(arr, i, char*);
  4716. if (IsFileMatch(strFileFilter, _GetFileName(file)))
  4717. {
  4718. if (RemoveFileA(file)) {
  4719. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", file);
  4720. }
  4721. else {
  4722. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", file);
  4723. strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", file);
  4724. bRet = false;
  4725. break;
  4726. }
  4727. }
  4728. else
  4729. {
  4730. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match file: [%s]", file);
  4731. }
  4732. }
  4733. toolkit_array_free2(arr);
  4734. if (!bRet) {
  4735. return bRet;
  4736. }
  4737. }
  4738. // 删除所有匹配子目录
  4739. auto subdirs = fileutil_get_sub_dirs(strDestDir.GetData());
  4740. if (subdirs != NULL)
  4741. {
  4742. for (int i = 0; i < subdirs->nelts; ++i)
  4743. {
  4744. const char* dir = ARRAY_IDX(subdirs, i, char*);
  4745. if (IsFileMatch(strFileFilter, _GetFileName(dir)))
  4746. {
  4747. if (RemoveDirRecursive(dir)) {
  4748. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", dir);
  4749. }
  4750. else {
  4751. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", dir);
  4752. strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", dir);
  4753. bRet = false;
  4754. break;
  4755. }
  4756. }
  4757. else
  4758. {
  4759. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match dir: [%s]", dir);
  4760. }
  4761. }
  4762. toolkit_array_free2(subdirs);
  4763. if (!bRet) {
  4764. return bRet;
  4765. }
  4766. }
  4767. return bRet;
  4768. }
  4769. else {
  4770. //直接删除文件
  4771. bool bRet = true;
  4772. if (ExistsFileA(destPath.GetData()))
  4773. {
  4774. if (RemoveFileA(destPath.GetData())) {
  4775. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", destPath.GetData());
  4776. }
  4777. else {
  4778. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", destPath.GetData());
  4779. strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", destPath.GetData());
  4780. bRet = false;
  4781. }
  4782. return bRet;
  4783. }
  4784. else if (ExistsDirA(destPath.GetData()))
  4785. {
  4786. if (RemoveDirRecursiveA(destPath.GetData())) {
  4787. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", destPath.GetData());
  4788. }
  4789. else {
  4790. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", destPath.GetData());
  4791. strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", destPath.GetData());
  4792. bRet = false;
  4793. }
  4794. return bRet;
  4795. }
  4796. else
  4797. {
  4798. //指定文件不再则忽略删除此文件
  4799. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file [%s] not exists,ignore delete file", destPath.GetData());
  4800. return bRet;
  4801. }
  4802. }
  4803. }
  4804. bool CUpgradeTaskFSM::ExecDepCpoyCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
  4805. {
  4806. CSimpleStringA sourcePath;//路径+通配符
  4807. if (ins->srcPathType == "0") {
  4808. CSimpleStringA rootPath = "";
  4809. if (GetDepRootTypePath(1, rootPath)) {
  4810. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//相对路径
  4811. }
  4812. else {
  4813. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 1 is fail");
  4814. return false;
  4815. }
  4816. }
  4817. else if (ins->srcPathType == "1") {
  4818. sourcePath = ins->srcPath;//绝对路径
  4819. }
  4820. else if (ins->srcPathType == "2") {
  4821. CSimpleStringA rootPath = "";
  4822. if (GetDepRootTypePath(2, rootPath)) {
  4823. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//当前版本相对路径
  4824. }
  4825. else {
  4826. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 2 is fail");
  4827. return false;
  4828. }
  4829. }
  4830. else if (ins->srcPathType == "3") {
  4831. CSimpleStringA rootPath = "";
  4832. if (GetDepRootTypePath(4, rootPath)) {
  4833. sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//升级包相对路径
  4834. }
  4835. else {
  4836. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 4 is fail");
  4837. return false;
  4838. }
  4839. }
  4840. else {
  4841. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd srcPathType is invalid %s", ins->srcPathType.GetData());
  4842. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd srcPathType is invalid %s", ins->srcPathType.GetData());
  4843. return false;//不支持的路径类型
  4844. }
  4845. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd sourcePath is %s", sourcePath.GetData());
  4846. CSimpleStringA destPath;//目的路径文件夹
  4847. if (ins->dstPathType == "0") {
  4848. CSimpleStringA rootPath = "";
  4849. if (GetDepRootTypePath(1, rootPath)) {
  4850. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
  4851. }
  4852. else {
  4853. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 1 is fail");
  4854. return false;
  4855. }
  4856. }
  4857. else if (ins->dstPathType == "1") {
  4858. destPath = ins->dstPath;//绝对路径
  4859. }
  4860. else if (ins->dstPathType == "2") {
  4861. CSimpleStringA rootPath = "";
  4862. if (GetDepRootTypePath(2, rootPath)) {
  4863. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
  4864. }
  4865. else {
  4866. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 2 is fail");
  4867. return false;
  4868. }
  4869. }
  4870. else if (ins->dstPathType == "3") {
  4871. CSimpleStringA rootPath = "";
  4872. if (GetDepRootTypePath(3, rootPath)) {
  4873. destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
  4874. }
  4875. else {
  4876. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 3 is fail");
  4877. return false;
  4878. }
  4879. }
  4880. else {
  4881. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd dstPathType is invalid %s", ins->dstPathType.GetData());
  4882. strErrMsg = CSimpleStringA::Format("ExecCpoyCmd dstPathType is invalid %s", ins->dstPathType.GetData());
  4883. return false;//不支持的路径类型
  4884. }
  4885. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd destPath is %s", destPath.GetData());
  4886. if (sourcePath.IndexOf("*") > 0) {
  4887. //循环匹配拷贝
  4888. //找到要扫描的文件夹
  4889. CSimpleStringA strFileDir = GetFileDirectory(sourcePath.GetData());
  4890. //过滤通配条件
  4891. CSimpleStringA strFileFilter = _GetFileName(sourcePath.GetData());
  4892. list<CSimpleStringA> fileList;
  4893. //获取所有根文件夹下的文件相对路径:如mod\test.dll
  4894. RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
  4895. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find fileList =%d", fileList.size());
  4896. for (auto it = fileList.begin(); it != fileList.end(); it++)
  4897. {
  4898. if (IsFileMatch(strFileFilter, _GetFileName((const char*)(*it))))
  4899. {
  4900. CSimpleStringA strSrcName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", GetFileDirectory(sourcePath.GetData()).GetData(), (const char*)(*it));//源文件路径
  4901. CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), (const char*)(*it));//目标文件路径
  4902. //匹配成功,开始拷贝文件
  4903. CSimpleStringA errMsg = "";
  4904. ErrorCodeEnum rc = CopyFileOperate(strSrcName.GetData(), strDestName.GetData(), 3, errMsg);
  4905. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] to [%s] %s", strSrcName.GetData(),strDestName.GetData(), rc == Error_Succeed ? "succeed" : "fail");
  4906. if (rc != Error_Succeed)
  4907. {
  4908. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail: %s", strSrcName.GetData(), errMsg.GetData());
  4909. strErrMsg = CSimpleStringA::Format("copy file [%s] fail: %s", strSrcName.GetData(), errMsg.GetData());
  4910. return false;//报错
  4911. }
  4912. }
  4913. }
  4914. }
  4915. else {
  4916. //直接拷贝文件:考虑有些文件因智能对比不一定下发,故如果文件不存在,则默认忽略此策略
  4917. CSimpleStringA errMsg = "";
  4918. CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), _GetFileName(sourcePath.GetData()));
  4919. if (ExistsFileA(sourcePath.GetData())) {
  4920. ErrorCodeEnum rc = CopyFileOperate(sourcePath.GetData(), strDestName.GetData(), 3, errMsg);
  4921. if (rc != Error_Succeed)
  4922. {
  4923. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:%s", sourcePath.GetData(), errMsg.GetData());
  4924. strErrMsg = CSimpleStringA::Format("copy file [%s] fail:%s", sourcePath.GetData(), errMsg.GetData());
  4925. return false;//报错
  4926. }
  4927. }
  4928. else {
  4929. if (ins->srcPathType == "3") {
  4930. //升级包因智能升级不一定有指定的文件存在
  4931. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("拷贝指定的文件[%s]不存在,因智能升级对比过滤,故忽略此文件拷贝", sourcePath.GetData());
  4932. }
  4933. else {
  4934. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:file to copy not exist", sourcePath.GetData());
  4935. strErrMsg = CSimpleStringA::Format("copy file [%s] fail:file to copy not exist", sourcePath.GetData());
  4936. return false;//报错
  4937. }
  4938. }
  4939. }
  4940. return true;
  4941. }
  4942. bool CUpgradeTaskFSM::GetDepRootTypePath(int rootType, CSimpleStringA& Path)
  4943. {
  4944. //适配器
  4945. CSimpleStringA tempPath;
  4946. if (isTerminalInstall() && (rootType == 2 || rootType == 3)) {
  4947. //当是安装状态时,此路径取pack_version值,如果为空,默认用0.0.0.1 版本号
  4948. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\4.9.1.1 /opt/Run/dep/4.9.1.1
  4949. if (Error_Succeed == Error) {
  4950. if (!tempPath.IsNullOrEmpty()) {
  4951. if (!m_currentTask.pack_version.IsNullOrEmpty()) {
  4952. Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
  4953. }
  4954. else {
  4955. Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), "0.0.0.1");
  4956. }
  4957. return true;
  4958. }
  4959. else {
  4960. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is null");
  4961. return false;
  4962. }
  4963. }
  4964. else {
  4965. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is error");
  4966. return false;
  4967. }
  4968. }
  4969. if (rootType == 1) {
  4970. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Root", tempPath);//例如:C:\Run /opt/Run
  4971. if (Error_Succeed == Error) {
  4972. if (!tempPath.IsNullOrEmpty()) {
  4973. string runPathStr = tempPath.GetData();
  4974. int pos = runPathStr.find_last_of(SPLIT_SLASH);
  4975. Path = runPathStr.substr(0, pos).c_str();
  4976. }
  4977. else {
  4978. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is null");
  4979. return false;
  4980. }
  4981. }
  4982. else {
  4983. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is error");
  4984. return false;
  4985. }
  4986. }
  4987. else if (rootType == 2) {
  4988. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Dep", tempPath);//例如:C:\Run\dep\4.8.1.1 /opt/Run/dep/4.8.1.1
  4989. if (Error_Succeed == Error) {
  4990. if (!tempPath.IsNullOrEmpty()) {
  4991. Path = tempPath;
  4992. }
  4993. else {
  4994. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is null");
  4995. return false;
  4996. }
  4997. }
  4998. else {
  4999. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is error");
  5000. return false;
  5001. }
  5002. }
  5003. else if (rootType == 3) {
  5004. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\4.9.1.1 /opt/Run/dep/4.9.1.1
  5005. if (Error_Succeed == Error) {
  5006. if (!tempPath.IsNullOrEmpty()) {
  5007. Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
  5008. }
  5009. else {
  5010. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradeVer path is null");
  5011. return false;
  5012. }
  5013. }
  5014. else {
  5015. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradeVer path is error");
  5016. return false;
  5017. }
  5018. }
  5019. else if (rootType == 4) {
  5020. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Downloads", tempPath);//例如:C:\rvc\Downloads\4.8.1.1 /opt/rvc/Downloads/4.8.1.1
  5021. if (Error_Succeed == Error) {
  5022. if (!tempPath.IsNullOrEmpty()) {
  5023. CSimpleStringA strUnzipDir;
  5024. strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_name.GetData());
  5025. //解压去除了.zip后缀
  5026. if (strUnzipDir.IsEndWith(".zip")) {
  5027. Path = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
  5028. }
  5029. else {
  5030. Path = strUnzipDir;
  5031. }
  5032. }
  5033. else {
  5034. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is null");
  5035. return false;
  5036. }
  5037. }
  5038. else {
  5039. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is error");
  5040. return false;
  5041. }
  5042. }
  5043. return true;
  5044. }
  5045. CSimpleStringA CUpgradeTaskFSM::getAlarmCurrVersion()
  5046. {
  5047. //一期因无法从策略获取适配器升级还是应用升级,默认返回当前应用版本数据,待二期再做区分
  5048. return m_currentVersion.ToString();
  5049. }
  5050. ErrorCodeEnum CUpgradeTaskFSM::SM3FileToStr(CSimpleStringA strFilePath, CSimpleStringA &strSM3,bool isSub)
  5051. {
  5052. if(strFilePath.IsNullOrEmpty()){
  5053. return Error_Null;
  5054. }
  5055. int nlen = strlen(strFilePath.GetData());
  5056. char* pchar = new char[nlen+1];
  5057. strcpy(pchar,strFilePath.GetData());
  5058. BYTE md5[32]={0};
  5059. try
  5060. {
  5061. if(SM3File(pchar,md5)){
  5062. delete[] pchar;
  5063. //获取16进制的字符串
  5064. if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
  5065. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 to hex str fail,file=%s",strFilePath.GetData());
  5066. return Error_Unexpect;
  5067. }
  5068. return Error_Succeed;
  5069. }else{
  5070. delete[] pchar;
  5071. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt fail ,file=%s",strFilePath.GetData());
  5072. return Error_Unexpect;
  5073. }
  5074. }
  5075. catch (...)
  5076. {
  5077. delete[] pchar;
  5078. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt exception ,file=%s",strFilePath.GetData());
  5079. return Error_Exception;
  5080. }
  5081. }
  5082. ErrorCodeEnum CUpgradeTaskFSM::SM3DataToStr(CSimpleStringA strData, CSimpleStringA &strSM3,bool isSub)
  5083. {
  5084. if(strData.IsNullOrEmpty()){
  5085. return Error_Null;
  5086. }
  5087. BYTE md5[32]={0};
  5088. try
  5089. {
  5090. if(SM3Hash((BYTE*)strData.GetData(),strlen(strData.GetData()),md5)){
  5091. //获取16进制的字符串
  5092. if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
  5093. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 to hex str fail");
  5094. return Error_Unexpect;
  5095. }
  5096. return Error_Succeed;
  5097. }else{
  5098. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt fail");
  5099. return Error_Unexpect;
  5100. }
  5101. }
  5102. catch (...)
  5103. {
  5104. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt exception");
  5105. return Error_Exception;
  5106. }
  5107. }
  5108. ErrorCodeEnum CUpgradeTaskFSM::SM3_Str(CSimpleStringA &strSM3,BYTE * SM3Byte,bool isSub)
  5109. {
  5110. if(SM3Byte == NULL){
  5111. return Error_Exception;
  5112. }
  5113. int SM3_len=64;
  5114. if(isSub){
  5115. SM3_len=32;
  5116. }
  5117. int i;
  5118. char* file_SM3 = (char*)malloc((SM3_len + 1) * sizeof(char));
  5119. if(file_SM3 == NULL)
  5120. {
  5121. fprintf(stderr, "SM3 malloc failed.\n");
  5122. return Error_Exception;
  5123. }
  5124. memset(file_SM3, 0, (SM3_len + 1));
  5125. if(SM3_len == 32)
  5126. {
  5127. for(i=0; i<16; i++)
  5128. { //SM3截取中间16位字节,8-24位字节数,小写
  5129. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i+8]);
  5130. }
  5131. }
  5132. else if(SM3_len == 64)
  5133. {
  5134. for(i=0; i<32; i++)
  5135. {
  5136. sprintf(&file_SM3[i*2], "%02x", SM3Byte[i]);
  5137. }
  5138. }
  5139. strSM3=file_SM3;
  5140. free(file_SM3);
  5141. return Error_Succeed;
  5142. }
  5143. bool CUpgradeTaskFSM::IsPackDownloaded(const char *packPath,const char* packHash,long packLen)
  5144. {
  5145. if(!ExistsFileA(packPath)){
  5146. return false;//文件不存在,下载
  5147. }
  5148. //计算hash值
  5149. CSimpleStringA strMD5Val;
  5150. ErrorCodeEnum rc = SM3FileToStr(packPath, strMD5Val,false);
  5151. if (Error_Succeed != rc)
  5152. {
  5153. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s get download pack sm3 fail ,error:%d", packPath, (int)rc);
  5154. return false;//获取hash码失败,下载
  5155. }
  5156. //不区分大小写比较文件hash
  5157. #ifdef RVC_OS_WIN
  5158. if(stricmp(strMD5Val.GetData(),packHash)==0){
  5159. #else
  5160. if(strcmp(strMD5Val.GetData(),packHash)==0){
  5161. #endif
  5162. return true;//相同,不下载
  5163. }else{
  5164. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s sm3[%s] is no equal upgrade sm3[%s], retry download.", packPath, strMD5Val.GetData(), packHash);
  5165. return false;//不相同,下载
  5166. }
  5167. }
  5168. bool CUpgradeTaskFSM::DownloadFileWrite(byte* content,long contentLen,const char* filePath)
  5169. {
  5170. if(contentLen==0){
  5171. return true;
  5172. }
  5173. FILE* tempFp = fopen(filePath,"ab");
  5174. if(tempFp==NULL){
  5175. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite open file fail");
  5176. return false;
  5177. }
  5178. int ret = fwrite(content,(size_t)contentLen,1,tempFp);
  5179. fclose(tempFp);
  5180. if(ret!=1){
  5181. #ifdef RVC_OS_WIN
  5182. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite write file fail,ret = %d,errno = %d",ret,(int)GetLastError());
  5183. return false;
  5184. #else
  5185. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite write file fail,ret = %d,errno = %d",ret, errno);
  5186. return false;
  5187. #endif
  5188. }
  5189. return true;
  5190. }
  5191. bool CUpgradeTaskFSM::CheckIfCanSwitchNow()
  5192. {
  5193. //对于终端初始化安装时,直接通过。
  5194. if (isTerminalInstall()) {
  5195. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow terminal new install,return true");
  5196. return true;
  5197. }
  5198. //非重启操作,则直接可以进行切换,不用等待时机
  5199. if(m_currentTask.reboot_type == 0){
  5200. return true;
  5201. }
  5202. CSimpleStringA strCustomerHandle;
  5203. CSimpleStringA strCallState;
  5204. // 无交互N、客户关注A、客户在控制终端C、柜员协助T、柜员代操作G
  5205. ErrorCodeEnum rc = m_pEntity->GetFunction()->GetSysVar("CustomerHandle", strCustomerHandle);
  5206. if(rc!=Error_Succeed){
  5207. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get CustomerHandle value is fail ,err=%d",(int)rc);
  5208. return false;
  5209. }
  5210. // 离线O、尝试连线柜员C、免提通话H、连线失败F、断线B
  5211. rc = m_pEntity->GetFunction()->GetSysVar("CallState", strCallState);
  5212. if(rc!=Error_Succeed){
  5213. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get CallState value is fail ,err=%d",(int)rc);
  5214. return false;
  5215. }
  5216. #ifdef RVC_OS_WIN
  5217. SYSTEMTIME st = {};
  5218. GetLocalTime(&st);
  5219. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("hour is %d",(int)st.wHour);
  5220. bool bOffworkTime = st.wHour < 8 || st.wHour >= 21;
  5221. 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);
  5222. #else
  5223. time_t nowTime = time(NULL);
  5224. tm nowTimeTm = { 0 };
  5225. localtime_r(&nowTime, &nowTimeTm);
  5226. //Dbg("hour is %d", (int)nowTimeTm.tm_hour);
  5227. bool bOffworkTime = nowTimeTm.tm_hour < 8 || nowTimeTm.tm_hour >= 21;
  5228. 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);
  5229. #endif
  5230. // 或者下班时间且非连线状态 @20151202
  5231. // 客户关注状态A,不允许切换 by zl 20191113
  5232. if (strCustomerHandle[0] == 'N' || (bOffworkTime && strCallState[0] == 'O')) {
  5233. return true;
  5234. }
  5235. else {
  5236. // 防止感知一直误报有人状态,加入以下特例:如果是一天当中首次从切换状态直接跳转过来的升级切换,并且当前是首页则进行切换
  5237. if (!bOffworkTime) {
  5238. CSimpleStringA strUIState;
  5239. // M 首页
  5240. rc = m_pEntity->GetFunction()->GetSysVar("UIState", strUIState);
  5241. if (rc != Error_Succeed) {
  5242. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get strUIState value is fail ,err=%d", (int)rc);
  5243. return false;
  5244. }
  5245. #ifdef RVC_OS_WIN
  5246. CSimpleStringA nowStr = CSimpleStringA::Format("%d-%d-%d", st.wYear, st.wMonth, st.wDay).GetData();
  5247. #else
  5248. CSimpleStringA nowStr = CSimpleStringA::Format("%d-%d-%d", nowTimeTm.tm_year+1900, nowTimeTm.tm_mon+1, nowTimeTm.tm_mday).GetData();
  5249. #endif
  5250. //读取强制切换的日期
  5251. CSimpleStringA ForceSwitchDateStr = "";
  5252. ErrorCodeEnum rc = GetRunConfigStrValue("upgradeTask", "ForceSwitchDate", ForceSwitchDateStr);
  5253. if (rc != Error_Succeed) {
  5254. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow read from run config, read [upgradeTask][ForceSwitchDate] fail ,err=%d", (int)rc);
  5255. return false;
  5256. }
  5257. //首页并且切换状态直接进入
  5258. if (strUIState.Compare("M") == 0 && m_bSwitchFlag) {
  5259. //当天是否切换过
  5260. if (ForceSwitchDateStr.Compare(nowStr.GetData()) == 0) {
  5261. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow is not ForceSwitch, ForceSwitchDate[%s]", ForceSwitchDateStr.GetData());
  5262. return false;
  5263. }
  5264. else {
  5265. //直接切换,并写入强制切换日期
  5266. if (SetRunConfigStrValue("upgradeTask", "ForceSwitchDate", nowStr.GetData()) != Error_Succeed) {
  5267. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow write run config, write [upgradeTask][ForceSwitchDate] fail[%s],err=%d", nowStr.GetData(), (int)rc);
  5268. }
  5269. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow ForceSwitch, ForceSwitchDate[%s]", nowStr.GetData());
  5270. return true;
  5271. }
  5272. }
  5273. else {
  5274. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow is not ForceSwitch, UIState=%s,m_bSwitchFlag=%d", strUIState.GetData(),(int)m_bSwitchFlag);
  5275. return false;
  5276. }
  5277. }
  5278. else {
  5279. return false;
  5280. }
  5281. }
  5282. }
  5283. ErrorCodeEnum CUpgradeTaskFSM::SwitchUpgradeNow()
  5284. {
  5285. //默认轻量包不重启系统和框架,体系外系统不重启系统,系统升级重启框架
  5286. //根据重启策略类型去重启
  5287. //重启策略类型(0:不启动 1:重启框架 2:重启系统)
  5288. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin SwitchUpgradeNow");
  5289. if (m_currentTask.reboot_type == 0) {
  5290. 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());
  5291. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  5292. }
  5293. else if (m_currentTask.reboot_type == 1) {
  5294. if (m_currentTask.NewVersion.IsNullOrEmpty()) {
  5295. //非版本升级
  5296. LogEvent(Severity_Middle, Event_Req_Framework_No_Upgrade_Restart,
  5297. CSimpleStringA::Format("upgrade to new version [%s] succeed, request to no upgrade restart framework , taskID=[%s]", m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData()));
  5298. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  5299. }
  5300. else {
  5301. if (m_currentTask.task_type.Compare("U") == 0) {
  5302. //版本升级,健康有后续回退处理
  5303. LogEvent(Severity_Middle, Event_Req_Framework_Restart,
  5304. CSimpleStringA::Format("upgrade to new version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  5305. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  5306. }
  5307. else if (m_currentTask.task_type.Compare("R") == 0) {
  5308. //版本回退,健康无后续回滚处理
  5309. LogEvent(Severity_Middle, Event_Req_Framework_Rollback_Restart,
  5310. CSimpleStringA::Format("rollback to old version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  5311. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  5312. }
  5313. }
  5314. }
  5315. else if (m_currentTask.reboot_type == 2) {
  5316. if (m_currentTask.NewVersion.IsNullOrEmpty()) {
  5317. //非版本升级
  5318. LogEvent(Severity_Middle, Event_Req_OS_Restart,
  5319. CSimpleStringA::Format("SysPackInstall upgrade to new version [%s] succeed, request to restart OS, taskID=[%s]", m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData()));
  5320. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  5321. }
  5322. else {
  5323. if (m_currentTask.task_type.Compare("U") == 0) {
  5324. LogEvent(Severity_Middle, Event_Req_OS_Upgrade_Restart,
  5325. CSimpleStringA::Format("upgrade to new version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  5326. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  5327. }
  5328. else {
  5329. LogEvent(Severity_Middle, Event_Req_OS_Restart,
  5330. CSimpleStringA::Format("rollback to old version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
  5331. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
  5332. }
  5333. }
  5334. }
  5335. else {
  5336. 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());
  5337. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  5338. }
  5339. // 强制刷新日志
  5340. m_pEntity->GetFunction()->FlushLogFile();
  5341. return Error_Succeed;
  5342. }
  5343. ErrorCodeEnum CUpgradeTaskFSM::DownloadProgress(long tempFileLen,long fileSumLen)
  5344. {
  5345. UpgradeDownloadProgress dProgress;
  5346. dProgress.currentFile = m_currentTask.pack_name;
  5347. dProgress.fileNum = 1;
  5348. dProgress.progress=0;
  5349. if(fileSumLen!=0){
  5350. //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("tempFileLen =%d , fileSumLen =%d",tempFileLen,fileSumLen);
  5351. dProgress.progress = (int)(tempFileLen/(fileSumLen/100));
  5352. if(dProgress.progress ==10||dProgress.progress ==20||dProgress.progress ==30||dProgress.progress ==40||dProgress.progress ==50
  5353. ||dProgress.progress ==60||dProgress.progress ==70||dProgress.progress ==80||dProgress.progress ==90)
  5354. {
  5355. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("download progress is %d ,tempFileLen =%d , fileSumLen =%d",dProgress.progress,tempFileLen,fileSumLen);
  5356. }
  5357. //Dbg("download file [%s] progress is %d",dProgress.currentFile.GetData(),dProgress.progress);
  5358. ErrorCodeEnum retError = SpSendBroadcast(GetEntityBase()->GetFunction(), SP_MSG_OF(UpgradeDownloadProgress), SP_MSG_SIG_OF(UpgradeDownloadProgress), dProgress);
  5359. return retError;
  5360. }else{
  5361. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("download file [%s] progress is fail,sumlen=0");
  5362. return Error_Exception;
  5363. }
  5364. }
  5365. char CUpgradeTaskFSM::GetInstallState(int nState)
  5366. {
  5367. if (nState == s4)
  5368. return 'U';
  5369. else if (nState == s5)
  5370. return 'I';
  5371. else if (nState == s6)
  5372. return 'S';
  5373. else
  5374. return 'N';
  5375. }
  5376. ErrorCodeEnum CUpgradeTaskFSM::GetUpgradeState(bool &bInstalling, CSimpleStringA &strPackFile, CSimpleStringA &strExecID, char &cInstallState, bool &bSysInstall, bool &bLightPack, CSimpleStringA &strNewVersion)
  5377. {
  5378. bInstalling = !m_currentTask.upgradeTaskId.IsNullOrEmpty();
  5379. if (bInstalling)
  5380. {
  5381. strPackFile = m_currentTask.pack_name;
  5382. strExecID = m_currentTask.upgradeTaskId;
  5383. cInstallState = GetInstallState(m_iState);
  5384. bSysInstall = false;
  5385. bLightPack = false;
  5386. //if(!m_currentTask.to_run.IsNullOrEmpty()){
  5387. // bSysInstall = true;
  5388. //}else{
  5389. // bSysInstall = false;
  5390. //}
  5391. //if(m_currentTask.pack_version.IsNullOrEmpty()){
  5392. // bLightPack = true;
  5393. //}else{
  5394. // bLightPack = false;
  5395. //}
  5396. strNewVersion = m_currentTask.NewVersion;
  5397. }
  5398. return Error_Succeed;
  5399. }
  5400. void CUpgradeTaskFSM::HttpsLogCallBack(const char* logtxt)
  5401. {
  5402. DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("http dbg: %s",logtxt);
  5403. }
  5404. bool CUpgradeTaskFSM::isWork()
  5405. {
  5406. //兜底方案是判断集中配置一个参数,去除其他变量的判断,但是容易出现任务状态更新不准的情况。
  5407. if(m_startFlag){
  5408. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade startFlag is true");
  5409. return true;
  5410. }
  5411. //判断是否在设备安装状态,不受一般升级影响
  5412. if (isTerminalInstall()) {
  5413. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("isTerminalInstall get TerminalStage is N");
  5414. return true;
  5415. }
  5416. else {
  5417. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("isTerminalInstall get TerminalStage is not N");
  5418. }
  5419. //判断升级实体是否工作
  5420. //1.当有版本升级任务时,判断是否处于Guardian升级回退过程,如果已经升级成功或者回退成功,则开始工作,否则等待中
  5421. //2.当无任务或者非版本升级任务时,判断TerminalStage这个变量,非X状态,当A状态并且进入首页,则开始工作
  5422. //升级任务
  5423. if((!m_currentTask.NewVersion.IsNullOrEmpty())&&(m_currentTask.cPendingState=="T"||m_currentTask.cPendingState=="C"||m_currentTask.cPendingState=="X")){
  5424. CSimpleStringA strRunInfo,strStartTime;
  5425. if (m_pEntity->GetFunction()->GetPath("RunInfo",strRunInfo) == Error_Succeed){
  5426. #ifdef RVC_OS_WIN
  5427. strStartTime = strRunInfo + "\\runcfg\\starttime.dat";
  5428. #else
  5429. strStartTime = strRunInfo + "/runcfg/starttime.dat";
  5430. #endif
  5431. if(!ExistsFileA(strStartTime.GetData())){
  5432. return true;//完成升级过程,通过
  5433. }else{
  5434. #ifdef RVC_OS_WIN
  5435. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade process is not end ,file \\runcfg\\starttime is exist");
  5436. #else
  5437. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade process is not end ,file /runcfg/starttime is exist");
  5438. #endif
  5439. return false;//继续等待
  5440. }
  5441. }else{
  5442. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade process is not end ,get runinfo path is error");
  5443. return false;//失败,继续等待
  5444. }
  5445. }
  5446. //适配器任务
  5447. if ((!m_currentTask.depNewVersion.IsNullOrEmpty()) && (m_currentTask.cPendingState == "T" || m_currentTask.cPendingState == "C" || m_currentTask.cPendingState == "X")) {
  5448. return true;//适配器无升级监护
  5449. }
  5450. //非升级任务和无任务
  5451. CSimpleStringA strValue;
  5452. if(m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed){
  5453. if(strValue.Compare("X")==0){
  5454. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("TerminalStage = X ,continue wait");
  5455. return false;//状态是x继续等待
  5456. }
  5457. if(strValue.Compare("A")==0){
  5458. if(((CUpgradeMgrEntity*)m_pEntity)->m_bStartUp){
  5459. return true;//通过
  5460. }else{
  5461. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("TerminalStage = A ,but UIState is not M , continue wait");
  5462. return false;//准入过,但进入首页,继续等待
  5463. }
  5464. }
  5465. return true;//剩余其他状态都可以通过
  5466. }else{
  5467. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("get TerminalStage is error , continue wait");
  5468. return false;//失败,继续等待
  5469. }
  5470. }
  5471. bool CUpgradeTaskFSM::isAuthSucc() {
  5472. CSimpleStringA strValue;
  5473. if (m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed) {
  5474. if (strValue.Compare("A") == 0) {
  5475. return true;
  5476. }
  5477. else {
  5478. return false;
  5479. }
  5480. }
  5481. else {
  5482. return false;
  5483. }
  5484. }
  5485. bool CUpgradeTaskFSM::isTerminalInstall() {
  5486. CSimpleStringA strValue;
  5487. if (m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed) {
  5488. if (strValue.Compare("N") == 0) {
  5489. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("isTerminalInstall get TerminalStage=N");
  5490. return true; //表示安装模式
  5491. }else{
  5492. return false;
  5493. }
  5494. }
  5495. else {
  5496. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("isTerminalInstall get TerminalStage is error , default return fasle");
  5497. return false;//默认认为在升级状态
  5498. }
  5499. }
  5500. void CUpgradeTaskFSM::upgradeSuccStateBroadCast() {
  5501. UpgradeStateEvent stateEvent;
  5502. stateEvent.strPackName = m_currentTask.pack_name.GetData();
  5503. stateEvent.strExecID = m_currentTask.upgradeTaskId.GetData();
  5504. stateEvent.cInstallState = 'A';//表示成功状态
  5505. stateEvent.bSysInstall = false;
  5506. stateEvent.bLightPack = false;
  5507. stateEvent.strNewVersion = m_currentTask.NewVersion;
  5508. SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
  5509. }
  5510. #ifdef RVC_OS_WIN
  5511. #else
  5512. int CUpgradeTaskFSM::changeFileAtt(const char* path)
  5513. {
  5514. struct stat attr_of_del;
  5515. if (lstat(path, &attr_of_del) == 0)
  5516. {
  5517. //修改为775属性
  5518. mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
  5519. if (chmod(path, f_attrib) != 0)
  5520. {
  5521. Dbg("set file attribute is fail,errno=%d, file=%s", errno, path);
  5522. return -1;
  5523. }
  5524. return 0;
  5525. }
  5526. else {
  5527. Dbg("get file attribute is fail,errno=%d, file=%s", errno, path);
  5528. return -1;
  5529. }
  5530. }
  5531. #endif
  5532. void CUpgradeTaskFSM::OnStateTrans(int iSrcState, int iDstState)
  5533. {
  5534. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
  5535. if (iSrcState >= s4 && iDstState <= s3)
  5536. {
  5537. // 发送状态广播(通知业务界面清除状态)
  5538. UpgradeStateEvent stateEvent;
  5539. stateEvent.strPackName = "";
  5540. stateEvent.strExecID = "";
  5541. stateEvent.cInstallState = 'N';
  5542. stateEvent.bSysInstall = false;
  5543. stateEvent.bLightPack = false;
  5544. stateEvent.strNewVersion = "";
  5545. SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
  5546. }
  5547. else if (iDstState >= s4)
  5548. {
  5549. //assert(HasRunningUpdate());
  5550. //SetRunConfigStrValue("Install", "Pack", m_strIntallingPack);
  5551. //if (iDstState == s3)
  5552. // SetRunConfigStrValue("Install", "PendingState", "U");
  5553. //else if (iDstState == s4)
  5554. // SetRunConfigStrValue("Install", "PendingState", "I");
  5555. //else if (iDstState == s5)
  5556. // SetRunConfigStrValue("Install", "PendingState", "C");
  5557. //else if (iDstState == s6)
  5558. // SetRunConfigStrValue("Install", "PendingState", "S");
  5559. // 发送状态广播
  5560. UpgradeStateEvent stateEvent;
  5561. stateEvent.strPackName = m_currentTask.pack_name.GetData();
  5562. stateEvent.strExecID = m_currentTask.upgradeTaskId.GetData();
  5563. stateEvent.cInstallState = GetInstallState(iDstState);
  5564. stateEvent.bSysInstall = false;
  5565. stateEvent.bLightPack = false;
  5566. stateEvent.strNewVersion = m_currentTask.NewVersion;
  5567. SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
  5568. }
  5569. }
  5570. void CUpgradeTaskFSM::OnSysVarEvent(const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName)
  5571. {
  5572. //监听系统变量状态
  5573. if(strcmp("CallState",pszKey)==0){
  5574. if (pszValue[0] == 'O') {
  5575. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("m_bDownloadIdle is false ");
  5576. m_bDownloadIdle = false;//可以下载
  5577. } else {
  5578. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("m_bDownloadIdle is true");
  5579. m_bDownloadIdle = true;//不能下载
  5580. }
  5581. }
  5582. }
  5583. ErrorCodeEnum CUpgradeTaskFSM::OnInit()
  5584. {
  5585. //初始化
  5586. ErrorCodeEnum rc = LoadPersistTaskInfo();//加载运行时文件
  5587. if(rc!=Error_Succeed){
  5588. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("LoadPersistTaskInfo fail");
  5589. return rc;
  5590. }
  5591. rc = loadCenterCfgInfo();//加载集中配置文件
  5592. if(rc!=Error_Succeed){
  5593. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("loadCenterCfgInfo fail");
  5594. return rc;
  5595. }
  5596. //加载终端启动的版本号
  5597. CSystemStaticInfo info;
  5598. rc = m_pEntity->GetFunction()->GetSystemStaticInfo(info);
  5599. if(rc!=Error_Succeed){
  5600. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("load GetSystemStaticInfo fail ");
  5601. return rc;
  5602. }else{
  5603. m_currentVersion = info.InstallVersion;//当前版本号赋值
  5604. m_currentDepVersion = info.CurrDepVersion.GetData();//当前适配器版本号,有可能为空
  5605. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("App version:%s , Dep version:%s", m_currentVersion.ToString().GetData(),m_currentDepVersion.GetData());
  5606. }
  5607. //注册callstate变量监控
  5608. rc = m_pEntity->GetFunction()->RegistSysVarEvent("CallState", this);
  5609. if(rc!=Error_Succeed){
  5610. LogWarn(Severity_Middle, rc, ERR_WRAN_REGIST_SYS_VAR_FAIL, CSimpleStringA::Format("RegistSysVarEvent CallState is fail,%d",(int)rc).GetData());
  5611. return rc;//自检失败
  5612. }else{
  5613. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("RegistSysVarEvent UIState succ");
  5614. }
  5615. AddStateHooker(this);
  5616. ((CUpgradeMgrEntity*)m_pEntity)->testActive();//添加测试active文件是否被占用的方法
  5617. return Error_Succeed;
  5618. }
  5619. ErrorCodeEnum CUpgradeTaskFSM::OnExit()
  5620. {
  5621. m_pEntity->GetFunction()->UnregistSysVarEvent("CallState");
  5622. RemoveStateHooker(this);
  5623. return Error_Succeed;
  5624. }
  5625. void CUpgradeTaskFSM::s1_on_entry()
  5626. {
  5627. //判断是否进入了首页
  5628. CSimpleStringA strValue;
  5629. if(isWork()&&((CUpgradeMgrEntity*)m_pEntity)->m_initSucc){
  5630. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("====upgrade is start up ====");
  5631. ScheduleTimer(2,10*1000);//首次进入等待hash时间
  5632. }else{
  5633. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("last upgrade progress is not end or is not initSucc,wait 10s ");
  5634. ScheduleTimer(1, 10*1000);//等待一段时间再判断是否进入首页
  5635. }
  5636. }
  5637. void CUpgradeTaskFSM::s1_on_exit()
  5638. {
  5639. CancelTimer(1);//等待进入首页计时器
  5640. CancelTimer(2);//等待hash计算计时器
  5641. }
  5642. unsigned int CUpgradeTaskFSM::s1_on_event(FSMEvent* event)
  5643. {
  5644. if (event->iEvt == EVT_TIMER)
  5645. {
  5646. if(event->param1 == 1){
  5647. CSimpleStringA strValue;
  5648. if(isWork()&&((CUpgradeMgrEntity*)m_pEntity)->m_initSucc){
  5649. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("====upgrade is start up ====");
  5650. ScheduleTimer(2,10*1000);//首次进入等待hash时间
  5651. }else{
  5652. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("last upgrade progress is not end or is not initSucc,wait 10s ");
  5653. ScheduleTimer(1, 10*1000);//等待一段时间再判断是否进入首页
  5654. }
  5655. }else if(event->param1 ==2){
  5656. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入s2
  5657. }
  5658. }
  5659. return 0;
  5660. }
  5661. void CUpgradeTaskFSM::s2_on_entry()
  5662. {
  5663. //判断是否存在残留任务
  5664. if(m_currentTask.upgradeTaskId.IsNullOrEmpty()&&m_currentTask.cPendingState.IsNullOrEmpty()){
  5665. //直接进入查询新任务
  5666. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  5667. }else{
  5668. //处理上个任务
  5669. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));
  5670. }
  5671. }
  5672. void CUpgradeTaskFSM::s2_on_exit()
  5673. {
  5674. CancelTimer(1);//更新任务状态计时器
  5675. CancelTimer(2);//查询当前任务计时器
  5676. }
  5677. unsigned int CUpgradeTaskFSM::s2_on_event(FSMEvent* event)
  5678. {
  5679. if (event->iEvt == EVT_TIMER){
  5680. if(event->param1 == 1){
  5681. Task::UpdateTaskStatus* uTask = new Task::UpdateTaskStatus(this);
  5682. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(uTask);
  5683. if(Error_Succeed!=rc){
  5684. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create UpdateTaskStatus is fail,%d",(int)rc);
  5685. ScheduleTimer(1,60*1000);//继续更新任务状态
  5686. }
  5687. }else if(event->param1 == 2){
  5688. Task::QueryCurrTask* qTask = new Task::QueryCurrTask(this);
  5689. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
  5690. if(Error_Succeed!=rc){
  5691. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create QueryCurrTask is fail,%d",(int)rc);
  5692. ScheduleTimer(2,4*60*1000);//继续查询当前任务
  5693. }
  5694. }
  5695. }else if (event->iEvt == Event_DealCurrTask)
  5696. {
  5697. //处理运行时文件异常记录的情况
  5698. if (m_currentTask.task_type.IsNullOrEmpty()) {
  5699. m_currentTask.task_type = "U";//兼容旧版本字段无值的情况,默认是升级模式
  5700. }
  5701. if (m_currentTask.task_type.Compare("U") == 0) {
  5702. if (m_currentTask.upgradeTaskId.IsNullOrEmpty() || m_currentTask.createTaskVersion.IsNullOrEmpty()
  5703. || m_currentTask.cPendingState.IsNullOrEmpty() || m_currentTask.pack_name.IsNullOrEmpty()) {
  5704. //有任务时,则4个字段不能为空,否则任务有问题
  5705. CSimpleStringA errStr = CSimpleStringA::Format("current Task param is null, clear this task, upgradeTaskId=[%s],createTaskVersion=[%s],cPendingState=[%s],PackName=[%s]",
  5706. m_currentTask.upgradeTaskId.GetData(), m_currentTask.createTaskVersion.GetData(), m_currentTask.cPendingState.GetData(), m_currentTask.pack_name.GetData());
  5707. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK, errStr.GetData());
  5708. if (ClearCurrTaskInfo()) {
  5709. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  5710. }
  5711. else {
  5712. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
  5713. Sleep(5 * 1000);//等待五秒,继续清理
  5714. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
  5715. }
  5716. }
  5717. }
  5718. else if (m_currentTask.task_type.Compare("R") == 0) {
  5719. if (m_currentTask.upgradeTaskId.IsNullOrEmpty() || m_currentTask.createTaskVersion.IsNullOrEmpty()
  5720. || m_currentTask.cPendingState.IsNullOrEmpty()) {
  5721. //有任务时,则3个字段不能为空,否则任务有问题
  5722. CSimpleStringA errStr = CSimpleStringA::Format("current Task param is null, clear this task, upgradeTaskId=[%s],createTaskVersion=[%s],cPendingState=[%s]",
  5723. m_currentTask.upgradeTaskId.GetData(), m_currentTask.createTaskVersion.GetData(), m_currentTask.cPendingState.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 {
  5736. CSimpleStringA errStr = CSimpleStringA::Format("current Task param task_type=[%s], param is Not Supported, clear this task",m_currentTask.task_type.GetData());
  5737. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK, errStr.GetData());
  5738. if (ClearCurrTaskInfo()) {
  5739. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  5740. }
  5741. else {
  5742. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
  5743. Sleep(5 * 1000);//等待五秒,继续清理
  5744. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
  5745. }
  5746. }
  5747. //任务已到最终状态
  5748. if(m_currentTask.cPendingState=="T"||m_currentTask.cPendingState=="C"||m_currentTask.cPendingState=="X"){
  5749. //取消任务C和切换任务T时,更新任务状态
  5750. Task::UpdateTaskStatus* uTask = new Task::UpdateTaskStatus(this);
  5751. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(uTask);
  5752. if(Error_Succeed!=rc){
  5753. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create UpdateTaskStatus is fail,%d",(int)rc);
  5754. ScheduleTimer(1,60*1000);//继续更新任务状态
  5755. }
  5756. }else{
  5757. //当前任务
  5758. if(m_currentTask.createTaskVersion!=m_currentVersion.ToString()){
  5759. //比较遗留任务的创建版本号是否和现在版本一致,不一致,则可能出现拷贝别的终端文件或者已经手工改了别的版本引发,这种情况下自动清理此次任务。
  5760. 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());
  5761. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK,errStr.GetData());
  5762. if(ClearCurrTaskInfo()){
  5763. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  5764. }else{
  5765. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 2,retry int 5's");
  5766. Sleep(5 * 1000);//等待五秒,继续清理
  5767. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
  5768. }
  5769. }else{
  5770. Task::QueryCurrTask* qTask = new Task::QueryCurrTask(this);
  5771. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
  5772. if(Error_Succeed!=rc){
  5773. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create QueryCurrTask is fail,%d",(int)rc);
  5774. ScheduleTimer(2,4*60*1000);//继续查询当前任务
  5775. }
  5776. }
  5777. }
  5778. }else if(event->iEvt == Event_EndUpdateTask){
  5779. //更新任务状态返回结果
  5780. UpdateTaskStatusEvent* pEvent = (UpdateTaskStatusEvent*)event;
  5781. if(pEvent->isSucc){
  5782. //告警回滚和升级成功
  5783. if(m_currentTask.cPendingState=="T"){
  5784. if (isTerminalInstall()) {
  5785. //安装情况
  5786. struct CTaskProcess up;
  5787. up.strPackName = m_currentTask.pack_name;//安装包名
  5788. if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
  5789. up.installVersion = m_currentVersion.ToString();//当前的版本
  5790. up.CurrentVersion = m_currentVersion.ToString();//当前的版本
  5791. }
  5792. else {
  5793. up.installVersion = m_currentDepVersion.GetData();//安装适配器版本
  5794. up.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
  5795. }
  5796. up.cInstallState = "A";
  5797. up.strInstallComment = "启动成功";
  5798. SendUpgradeTaskProgress(up, UpgradeMgr_START_ID);
  5799. upgradeSuccStateBroadCast();//广播告知升级成功
  5800. }
  5801. else {
  5802. //非安装情况
  5803. if (m_currentTask.NewVersion == m_currentVersion.ToString() ||
  5804. m_currentTask.depNewVersion == m_currentDepVersion ||
  5805. (m_currentTask.NewVersion == "" && m_currentTask.depNewVersion == "")) {
  5806. //安装成功
  5807. struct CTaskProcess up;
  5808. up.strPackName = m_currentTask.pack_name;//安装包名
  5809. if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
  5810. up.installVersion = m_currentVersion.ToString();//当前的版本
  5811. up.CurrentVersion = m_currentVersion.ToString();//当前的版本
  5812. }
  5813. else {
  5814. up.installVersion = m_currentDepVersion.GetData();//安装适配器版本
  5815. up.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
  5816. }
  5817. up.cInstallState = "A";
  5818. up.strInstallComment = "启动成功";
  5819. if (m_currentTask.task_type.Compare("U") == 0) {
  5820. SendUpgradeTaskProgress(up, UpgradeMgr_START_ID);
  5821. }
  5822. else {
  5823. SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_START_ID);
  5824. }
  5825. upgradeSuccStateBroadCast();//广播告知升级成功
  5826. }
  5827. else {
  5828. //回滚
  5829. struct CTaskProcess upRoll;
  5830. upRoll.strPackName = m_currentTask.pack_name;//安装包名
  5831. if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
  5832. upRoll.installVersion = m_currentTask.NewVersion.GetData();//任务升级后的版本号
  5833. upRoll.CurrentVersion = m_currentVersion.ToString();//当前的版本
  5834. }
  5835. else {
  5836. upRoll.installVersion = m_currentTask.depNewVersion.GetData();//安装适配器版本
  5837. upRoll.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
  5838. }
  5839. upRoll.cInstallState = "R";
  5840. upRoll.strInstallComment = "自动倒回";
  5841. if (m_currentTask.task_type.Compare("U") == 0) {
  5842. SendUpgradeTaskProgress(upRoll, UpgradeMgr_START_ID, " RTA5667");
  5843. }
  5844. else {
  5845. SendUpgradeTaskProgress(upRoll, UpgradeMgr_ROLLBACK_START_ID, " RTA5672");
  5846. }
  5847. }
  5848. }
  5849. ErrorCodeEnum rc = SetRunSucceed(m_currentTask.pack_name.GetData());
  5850. if (rc != Error_Succeed) {
  5851. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetRunSucceed is fail: %d", (int)rc);
  5852. }
  5853. }
  5854. //清除运行时文件和内存任务,跳转到S3
  5855. if(ClearCurrTaskInfo()){
  5856. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  5857. }else{
  5858. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndUpdateTask clear current task is fail,retry int 5's");
  5859. Sleep(5 * 1000);//等待五秒,继续清理
  5860. PostEventFIFO(new UpdateTaskStatusEvent(true));//继续更新任务状态
  5861. }
  5862. }else{
  5863. ScheduleTimer(1,60*1000);//继续更新任务状态
  5864. }
  5865. }else if(event->iEvt == Event_EndQueryCurrTask){
  5866. //查询当前任务返回结果
  5867. QueryCurrTaskEvent* pEvent = (QueryCurrTaskEvent*)event;
  5868. if(pEvent->isSucc){
  5869. if(pEvent->isTask_valid){
  5870. //根据不同任务状态值,进入不同阶段。U:下载阶段,I:安装阶段,回退检查,S切换阶段
  5871. if(m_currentTask.cPendingState=="U"){
  5872. return 4;//下载
  5873. }else if(m_currentTask.cPendingState=="I"){
  5874. if (m_currentTask.task_type.Compare("R") == 0) {
  5875. //因回退不进入S阶段,故加入切换标志。
  5876. m_bSwitchFlag = true;
  5877. }
  5878. return 5;//安装,回退检查
  5879. }else if(m_currentTask.cPendingState=="S"){
  5880. //加入切换标志,用于切换时判断是否是切换进入的流程。
  5881. m_bSwitchFlag = true;
  5882. return 6;//切换
  5883. }else{
  5884. //无效状态
  5885. LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_STATUS_FAIL,CSimpleStringA::Format("invalid pending state : %s",m_currentTask.cPendingState.GetData()).GetData());
  5886. //任务无效,清理任务
  5887. if(ClearCurrTaskInfo()){
  5888. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  5889. }else{
  5890. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndQueryCurrTask clear current task is fail 2,retry int 5's");
  5891. Sleep(5 * 1000);//等待五秒,继续清理
  5892. PostEventFIFO(new QueryCurrTaskEvent(true,true));//继续清理当前任务
  5893. }
  5894. }
  5895. }else{
  5896. 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());
  5897. //任务无效,清理任务
  5898. if(ClearCurrTaskInfo()){
  5899. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  5900. }else{
  5901. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndQueryCurrTask clear current task is fail 1,retry int 5's");
  5902. Sleep(5 * 1000);//等待五秒,继续清理
  5903. PostEventFIFO(new QueryCurrTaskEvent(true,false));//继续清理当前任务
  5904. }
  5905. }
  5906. }else{
  5907. ScheduleTimer(2,4*60*1000);//继续查询当前任务
  5908. }
  5909. }
  5910. return 0;
  5911. }
  5912. void CUpgradeTaskFSM::s3_on_entry()
  5913. {
  5914. //查询新任务:先预查询任务,传送hash,接着查询任务
  5915. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("entery S3");
  5916. m_queryNewTaskCount = 0;
  5917. m_strPreTaskId = "";
  5918. m_bNeedHash=0;
  5919. m_fileSM3List="";
  5920. m_fileSM3ListHash="";
  5921. isSendHash=false;
  5922. //预查询任务
  5923. Task::QueryNewPreTask* qTask = new Task::QueryNewPreTask(this);
  5924. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
  5925. if(rc!=Error_Succeed){
  5926. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewPreTask fail,wait 4 min retry ,err=%d",(int)rc);
  5927. ScheduleTimer(1, m_queryNewTaskInterval*1000);//等待4分钟后再次查询是否有新任务
  5928. }
  5929. }
  5930. void CUpgradeTaskFSM::s3_on_exit()
  5931. {
  5932. CancelTimer(1);//预查询任务计时器
  5933. CancelTimer(2);//上传hash计时器
  5934. CancelTimer(3);//继续任务计时器
  5935. m_queryNewTaskCount =0;
  5936. m_strPreTaskId = "";
  5937. m_bNeedHash=0;
  5938. m_fileSM3List="";
  5939. m_fileSM3ListHash="";
  5940. isSendHash=false;
  5941. }
  5942. unsigned int CUpgradeTaskFSM::s3_on_event(FSMEvent* event)
  5943. {
  5944. if(event->iEvt == EVT_TIMER){
  5945. if(event->param1 == 1){
  5946. //发起预查询任务
  5947. Task::QueryNewPreTask* nTask = new Task::QueryNewPreTask(this);
  5948. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  5949. if(rc!=Error_Succeed){
  5950. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewPreTask fail,wait [%d]s retry ,err=%d", m_queryNewTaskInterval, (int)rc);
  5951. ScheduleTimer(1, m_queryNewTaskInterval *1000);//等待4分钟后再次查询是否有新任务
  5952. }
  5953. }else if(event->param1 == 2){
  5954. //上传hash
  5955. Task::SendSM3Task* SM3Task = new Task::SendSM3Task(this);
  5956. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(SM3Task);
  5957. if(rc!=Error_Succeed){
  5958. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create SendSM3Task fail,err=%d",(int)rc);
  5959. ScheduleTimer(2, 60*1000);//等待1分钟过后再次发送
  5960. }
  5961. }else if(event->param1 == 3){
  5962. //继续任务
  5963. Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
  5964. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  5965. if(rc!=Error_Succeed){
  5966. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
  5967. ScheduleTimer(3, m_queryNewTaskInterval *1000);//等待4分钟过后再次发送
  5968. }
  5969. }
  5970. }
  5971. else if(event->iEvt == Event_EndPrePoll){
  5972. QueryNewPreTaskEvent* pEvent = (QueryNewPreTaskEvent*)event;
  5973. if(pEvent->isSucc){
  5974. if(m_strPreTaskId.IsNullOrEmpty()){
  5975. m_queryNewTaskCount++;
  5976. if(m_queryNewTaskCount>=QUERY_NO_TASK_WARN_LIMIT){
  5977. LogWarn(Severity_Low, Error_Exception, ERR_TASK_QUERY_NO_TASK,"QueryNewPreTask 15 times succ,no new task");
  5978. m_queryNewTaskCount=0;
  5979. }
  5980. if (isAuthSucc()) {
  5981. ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次查询是否有新任务
  5982. }
  5983. else {
  5984. ScheduleTimer(1, 30 * 1000);//等待30s后再次查询是否有新任务
  5985. }
  5986. }else{
  5987. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewPreTask succ, task_id=%s",m_strPreTaskId.GetData());
  5988. if(m_bNeedHash){
  5989. //预查询成功
  5990. if(isSendHash){
  5991. //之前发送hash成功,直接开始继续任务查询线程
  5992. Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
  5993. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  5994. if(rc!=Error_Succeed){
  5995. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
  5996. ScheduleTimer(3, 60*1000);//再次查询是否有新任务
  5997. }
  5998. }else{
  5999. //之前未发送hash成功,开始计算hash线程
  6000. Task::SendSM3Task* SM3Task = new Task::SendSM3Task(this);
  6001. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(SM3Task);
  6002. if(rc!=Error_Succeed){
  6003. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create SendSM3Task fail,err=%d",(int)rc);
  6004. ScheduleTimer(2, 60*1000);//等待一分钟过后再次发送
  6005. }
  6006. }
  6007. }else{
  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);//等待4分钟后再次查询是否有新任务
  6014. }
  6015. }
  6016. }
  6017. }else{
  6018. //预查询失败
  6019. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewPreTask fail,wait 4 min retry");
  6020. if (isAuthSucc()) {
  6021. ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次预查询是否有新任务
  6022. }
  6023. else {
  6024. ScheduleTimer(1, 30 * 1000);//等待30s后再次查询是否有新任务
  6025. }
  6026. }
  6027. }
  6028. else if(event->iEvt == Event_EndSendSM3Task){
  6029. Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
  6030. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  6031. if(rc!=Error_Succeed){
  6032. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
  6033. ScheduleTimer(3, 60*1000);//等待4分钟后再次查询是否有新任务
  6034. }
  6035. }
  6036. else if(event->iEvt == Event_EndContinuePoll){
  6037. QueryNewContinueTaskEvent* pEvent = (QueryNewContinueTaskEvent*)event;
  6038. if(pEvent->retParam == 0){
  6039. //查询失败,继续查询
  6040. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask fail,wait [%d]s retry",m_queryNewTaskInterval);
  6041. if (isAuthSucc()) {
  6042. ScheduleTimer(3, m_queryNewTaskInterval * 1000);//等待4分钟后再次查询继续新任务
  6043. }
  6044. else {
  6045. ScheduleTimer(3, 30 * 1000);//等待30s后再次查询继续新任务
  6046. }
  6047. }else if(pEvent->retParam == 1){
  6048. //查询成功,跳到下一个状态,写入运行时文件
  6049. bool isWriteOk=false;
  6050. while(true){
  6051. if(SetRunConfigStrValue("upgradeTask","NewVersion","")!=Error_Succeed){
  6052. break;
  6053. }
  6054. if (SetRunConfigStrValue("upgradeTask", "depNewVersion", "") != Error_Succeed) {
  6055. break;
  6056. }
  6057. if (SetRunConfigStrValue("upgradeTask", "CreateTaskVersion", m_currentTask.createTaskVersion.GetData()) != Error_Succeed) {
  6058. break;
  6059. }
  6060. if (SetRunConfigStrValue("upgradeTask", "UpgradeTaskId", m_currentTask.upgradeTaskId.GetData()) != Error_Succeed) {
  6061. break;
  6062. }
  6063. if (SetRunConfigStrValue("upgradeTask", "taskType", m_currentTask.task_type.GetData()) != Error_Succeed) {
  6064. break;
  6065. }
  6066. if (m_currentTask.task_type.Compare("U") == 0) {
  6067. if (SetRunConfigStrValue("upgradeTask", "PendingState", "U") != Error_Succeed) {
  6068. break;
  6069. }
  6070. if (SetRunConfigStrValue("upgradeTask", "PackName", m_currentTask.pack_name.GetData()) != Error_Succeed) {
  6071. break;
  6072. }
  6073. }else if(m_currentTask.task_type.Compare("R") == 0){
  6074. if (SetRunConfigStrValue("upgradeTask", "PendingState", "I") != Error_Succeed) {
  6075. break;
  6076. }
  6077. if (SetRunConfigStrValue("upgradeTask", "PackName", "") != Error_Succeed) {
  6078. break;
  6079. }
  6080. }
  6081. isWriteOk=true;
  6082. break;
  6083. }
  6084. if(isWriteOk){
  6085. if (m_currentTask.task_type.Compare("U") == 0) {
  6086. //升级下载
  6087. struct CTaskProcess up;
  6088. up.strPackName = m_currentTask.pack_name;//安装包名
  6089. up.installVersion = m_currentTask.pack_version;//安装的版本
  6090. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6091. up.cInstallState = "D";
  6092. up.strInstallComment = "正在下载";
  6093. SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID);
  6094. m_currentTask.cPendingState = "U";//改变内存变量为U
  6095. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDownload));//进入S4
  6096. }
  6097. else {
  6098. //回退
  6099. struct CTaskProcess up;
  6100. up.strPackName = m_currentTask.pack_name;//安装包名
  6101. up.installVersion = m_currentTask.pack_version;//安装的版本
  6102. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6103. up.cInstallState = "B";
  6104. up.strInstallComment = "正在回退";
  6105. SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID);
  6106. m_currentTask.cPendingState = "I";//改变内存变量为I
  6107. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartInstall));//进入S5
  6108. }
  6109. }else{
  6110. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndPoll write runinfo is fail,retry int 5's");
  6111. Sleep(5 * 1000);//等待五秒,继续创建
  6112. PostEventFIFO(new QueryNewContinueTaskEvent(1));//继续创建任务
  6113. }
  6114. }else{
  6115. //跳出,重新预检查任务
  6116. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask fail,jump to PreTask");
  6117. if (isAuthSucc()) {
  6118. ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次预查询是否有新任务
  6119. }
  6120. else {
  6121. ScheduleTimer(1, 30 * 1000);//等待30s后再次预查询是否有新任务
  6122. }
  6123. }
  6124. }
  6125. return 0;
  6126. }
  6127. void CUpgradeTaskFSM::s4_on_entry()
  6128. {
  6129. //下载升级包
  6130. m_bTaskCancel = false;//默认任务非取消
  6131. if(m_bDownloadIdle){
  6132. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//进入不可下载状态
  6133. }else{
  6134. Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
  6135. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  6136. if(rc!=Error_Succeed){
  6137. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
  6138. ScheduleTimer(1, 15*1000);//等待15秒再试
  6139. }
  6140. }
  6141. ScheduleTimer(2, 30*1000);//启动查询任务是否有效
  6142. }
  6143. void CUpgradeTaskFSM::s4_on_exit()
  6144. {
  6145. CancelTimer(1);//正常下载计时器
  6146. CancelTimer(2);//查询任务是否取消计时器
  6147. CancelTimer(3);//外部状态中止下载计时器
  6148. }
  6149. unsigned int CUpgradeTaskFSM::s4_on_event(FSMEvent* event)
  6150. {
  6151. if (event->iEvt == EVT_TIMER)
  6152. {
  6153. if(event->param1 == 1){
  6154. Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
  6155. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  6156. if(rc!=Error_Succeed){
  6157. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
  6158. ScheduleTimer(1, 15*1000);//再次下载升级包
  6159. }
  6160. }else if(event->param1 == 2){
  6161. Task::QueryTaskStatus* dTask = new Task::QueryTaskStatus(this);
  6162. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  6163. if(rc!=Error_Succeed){
  6164. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create QueryTaskStatus fail,err=%d",(int)rc);
  6165. ScheduleTimer(2, 30*1000);//再次查询任务是否有效
  6166. }
  6167. }else if(event->param1 == 3){
  6168. //无效状态
  6169. if(m_bDownloadIdle){
  6170. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask download entry idle 10s");
  6171. ScheduleTimer(3,10*1000);//等待下次是否空闲
  6172. }else{
  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(3, 10*1000);//等待下次是否空闲
  6178. }
  6179. }
  6180. }
  6181. }else if (event->iEvt == Event_EndQueryTaskStatus){
  6182. QueryTaskStatusEvent* pEvent = (QueryTaskStatusEvent*)event;
  6183. if(pEvent->isSucc){
  6184. if(pEvent->isTask_valid){
  6185. ScheduleTimer(2, 30*1000);//有效,再次查询任务是否有效
  6186. m_bTaskCancel = false;
  6187. }else{
  6188. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("query upgradeTask is cancel,set m_bTaskCancel=true");
  6189. m_bTaskCancel = true;//取消下载,结束查询任务是否有效计时器
  6190. }
  6191. }else{
  6192. ScheduleTimer(2, 30*1000);//通讯失败,再次查询任务是否有效
  6193. }
  6194. }else if (event->iEvt == Event_EndDownload){
  6195. DownloadPackTaskEvent* pEvent = (DownloadPackTaskEvent*)event;
  6196. if(pEvent->isSucc){
  6197. if(SetRunConfigStrValue("upgradeTask","PendingState","I")==Error_Succeed){
  6198. //下载成功
  6199. m_currentTask.cPendingState = "I";//改变内存变量为I
  6200. if(m_currentTask.pack_version.IsNullOrEmpty()){
  6201. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID)("体系外下载成功");
  6202. }else{
  6203. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID)("终端版本下载成功");
  6204. }
  6205. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartInstall));//进入S5
  6206. }else{
  6207. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndDownload write runinfo is fail,retry in 5's");
  6208. Sleep(5 * 1000);//等待五秒
  6209. PostEventFIFO(new DownloadPackTaskEvent(true));//继续写运行时文件
  6210. }
  6211. }else{
  6212. if (m_currentTask.pack_version.IsNullOrEmpty()) {
  6213. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID).setResultCode("RTA5634")("体系外下载失败,通讯报错");
  6214. }
  6215. else {
  6216. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID).setResultCode("RTA5633")("终端版本下载失败,通讯报错");
  6217. }
  6218. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("download pack is fail , wait for 2 min retry download");
  6219. ScheduleTimer(1, 120*1000);//下载失败,等2分钟,再次下载任务
  6220. }
  6221. }else if (event->iEvt == Event_Download_Fail){
  6222. DownloadPackTaskFailEvent* pEvent = (DownloadPackTaskFailEvent*)event;
  6223. //写入运行时文件,状态为C
  6224. if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
  6225. //告警下载失败
  6226. struct CTaskProcess up;
  6227. up.strPackName = m_currentTask.pack_name;//安装包名
  6228. up.installVersion = m_currentTask.pack_version;//安装的版本
  6229. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6230. up.cInstallState = "C";
  6231. up.strInstallComment = pEvent->errMsg.c_str();
  6232. SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID,"RTA5660");
  6233. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask download is fail ,prepare to s2");
  6234. m_currentTask.cPendingState = "C";//改变内存变量C
  6235. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  6236. }else{
  6237. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_Download_Fail write runinfo is fail,retry in 5's");
  6238. Sleep(5 * 1000);//等待五秒
  6239. PostEventFIFO(new DownloadPackTaskFailEvent(pEvent->errMsg));//继续写运行时文件
  6240. }
  6241. }else if (event->iEvt == Event_Download_Idle){
  6242. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask download entry idle 10s");
  6243. ScheduleTimer(3,10*1000);//等待下次是否空闲
  6244. }else if (event->iEvt == Event_CancelTask){
  6245. //取消任务,清理任务
  6246. if(ClearCurrTaskInfo()){
  6247. //告警下载取消
  6248. struct CTaskProcess up;
  6249. up.strPackName = m_currentTask.pack_name;//安装包名
  6250. up.installVersion = m_currentTask.pack_version;//安装的版本
  6251. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6252. up.cInstallState = "C";
  6253. up.strInstallComment = "任务策略已取消";
  6254. SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID,"RTA5661");
  6255. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask is cancel,prepare to s3");
  6256. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  6257. }else{
  6258. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry in 5's");
  6259. Sleep(5 * 1000);//等待五秒,继续清理
  6260. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//继续取消任务
  6261. }
  6262. }
  6263. return 0;
  6264. }
  6265. void CUpgradeTaskFSM::s5_on_entry()
  6266. {
  6267. //停止播放广告和音频
  6268. Task::StopMediaPlayTask* nTask = new Task::StopMediaPlayTask(this);
  6269. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  6270. if(rc!=Error_Succeed){
  6271. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create StopMediaPlayTask fail,err=%d",(int)rc);
  6272. ScheduleTimer(1, 30*1000);//等待30秒再试
  6273. }
  6274. }
  6275. void CUpgradeTaskFSM::s5_on_exit()
  6276. {
  6277. CancelTimer(1);//停止广播和声音计时器
  6278. CancelTimer(2);//解压计时器
  6279. CancelTimer(3);//安装计时器
  6280. CancelTimer(4);//等待跳转切换计时器
  6281. CancelTimer(5);//回退检查计时器
  6282. }
  6283. unsigned int CUpgradeTaskFSM::s5_on_event(FSMEvent* event)
  6284. {
  6285. if(event->iEvt == EVT_TIMER){
  6286. if(event->param1 == 1){
  6287. //再次发起任务查询
  6288. Task::StopMediaPlayTask* nTask = new Task::StopMediaPlayTask(this);
  6289. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
  6290. if(rc!=Error_Succeed){
  6291. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create StopMediaPlayTask fail,err=%d",(int)rc);
  6292. ScheduleTimer(1, 30*1000);//等待30秒再停止播放广告和音频
  6293. }
  6294. }else if(event->param1 == 2){
  6295. Task::UnzipPackTask* iTask = new Task::UnzipPackTask(this);
  6296. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  6297. if(rc!=Error_Succeed){
  6298. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create UnzipPackTask fail,err=%d",(int)rc);
  6299. ScheduleTimer(2, 30*1000);//等待30秒再解压包
  6300. }
  6301. }else if(event->param1 == 3){
  6302. BOOL doInstall = true;
  6303. if(!m_startFlag) //非强制安装
  6304. {
  6305. if (m_currentTask.pack_version.GetLength() == 0) //体系外升级
  6306. {
  6307. CSimpleStringA strState;
  6308. ErrorCodeEnum err = m_pEntity->GetFunction()->GetSysVar("UIState", strState);
  6309. if (err == Error_Succeed && strState != CSimpleStringA("M")) //非主界面不安装
  6310. {
  6311. doInstall = false;
  6312. }
  6313. }
  6314. }
  6315. //对于终端初始化安装时,直接通过。
  6316. if (isTerminalInstall()) {
  6317. doInstall = true;
  6318. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask terminal new install");
  6319. }
  6320. if (doInstall)
  6321. {
  6322. //解压后判断是什么类型升级
  6323. judgeTaskClass();
  6324. Task::InstallPackTask* iTask = new Task::InstallPackTask(this);
  6325. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  6326. if (rc != Error_Succeed) {
  6327. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask fail,err=%d", (int)rc);
  6328. ScheduleTimer(3, 30 * 1000);//等待30秒再安装
  6329. }
  6330. }
  6331. else {
  6332. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 UIState is not M , create InstallPackTask wait for the next time");
  6333. ScheduleTimer(3, 30 * 1000);//等待30秒再安装
  6334. }
  6335. }
  6336. else if (event->param1 == 4) {
  6337. //已安装成功,直接进入切换状态
  6338. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask succ, enter into S6");
  6339. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
  6340. }
  6341. else if (event->param1 == 5) {
  6342. Task::RollBackCheckTask* iTask = new Task::RollBackCheckTask(this);
  6343. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  6344. if (rc != Error_Succeed) {
  6345. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create RollBackCheckTask fail,err=%d", (int)rc);
  6346. ScheduleTimer(5, 30 * 1000);//等待30秒再次检查
  6347. }
  6348. }
  6349. }
  6350. else if(event->iEvt == Event_EndStopMediaPlayTask){
  6351. StopMediaPlayTaskEvent* pEvent = (StopMediaPlayTaskEvent*)event;
  6352. if(pEvent->isSucc){
  6353. if (m_currentTask.task_type.Compare("U") == 0) {
  6354. //开始解压
  6355. Task::UnzipPackTask* iTask = new Task::UnzipPackTask(this);
  6356. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  6357. if (rc != Error_Succeed) {
  6358. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create UnzipPackTask fail,err=%d", (int)rc);
  6359. ScheduleTimer(2, 30 * 1000);//等待30秒再解压包
  6360. }
  6361. }
  6362. else if (m_currentTask.task_type.Compare("R") == 0) {
  6363. //回退检查
  6364. Task::RollBackCheckTask* iTask = new Task::RollBackCheckTask(this);
  6365. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  6366. if (rc != Error_Succeed) {
  6367. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create RollBackCheckTask fail,err=%d", (int)rc);
  6368. ScheduleTimer(5, 30 * 1000);//等待30秒再检查
  6369. }
  6370. }
  6371. }else{
  6372. ScheduleTimer(1, 30*1000);//等待30秒再停止播放广告和音频
  6373. }
  6374. }
  6375. else if (event->iEvt == Event_EndUnzipPackTask){
  6376. UnzipPackTaskEvent* pEvent = (UnzipPackTaskEvent*)event;
  6377. if(pEvent->isSucc){
  6378. //开始安装
  6379. BOOL doInstall = true;
  6380. if (!m_startFlag) //非强制安装
  6381. {
  6382. if (m_currentTask.pack_version.GetLength() == 0) //体系外升级
  6383. {
  6384. CSimpleStringA strState;
  6385. ErrorCodeEnum err = m_pEntity->GetFunction()->GetSysVar("UIState", strState);
  6386. if (err == Error_Succeed && strState != CSimpleStringA("M")) //非主界面不安装
  6387. {
  6388. doInstall = false;
  6389. }
  6390. }
  6391. }
  6392. //对于终端初始化安装时,直接通过。
  6393. if (isTerminalInstall()) {
  6394. doInstall = true;
  6395. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask terminal new install");
  6396. }
  6397. if (doInstall)
  6398. {
  6399. //解压后判断是什么类型升级
  6400. judgeTaskClass();
  6401. Task::InstallPackTask* iTask = new Task::InstallPackTask(this);
  6402. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
  6403. if (rc != Error_Succeed) {
  6404. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask fail,err=%d", (int)rc);
  6405. ScheduleTimer(3, 30 * 1000);//等待30秒再安装
  6406. }
  6407. }
  6408. else{
  6409. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 UIState is not M , create InstallPackTask wait for the next time");
  6410. ScheduleTimer(3, 30 * 1000);//等待30秒再安装
  6411. }
  6412. }else{
  6413. if(m_currentTask.stop_media_play){
  6414. //恢复广告和音频播放
  6415. ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
  6416. if(Error_Succeed != rc){
  6417. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("unzip fail set UpdateState to 0 fail, err=%d",(int)rc);
  6418. }
  6419. }
  6420. //解压失败,写入运行时文件,状态为C
  6421. if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
  6422. //告警下载取消
  6423. struct CTaskProcess up;
  6424. up.strPackName = m_currentTask.pack_name;//安装包名
  6425. up.installVersion = m_currentTask.pack_version;//安装的版本
  6426. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6427. up.cInstallState = "C";
  6428. up.strInstallComment = "解压失败";
  6429. SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5662");
  6430. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("unzip pack is fail ,prepare to s2");
  6431. m_currentTask.cPendingState = "C";//改变内存变量C
  6432. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  6433. }else{
  6434. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndUnzipPackTask write runinfo is fail,retry int 5's");
  6435. Sleep(5 * 1000);//等待五秒
  6436. PostEventFIFO(new UnzipPackTaskEvent(false));//继续写运行时文件
  6437. }
  6438. }
  6439. }
  6440. else if (event->iEvt == Event_EndInstallPackTask){
  6441. if(m_currentTask.stop_media_play){
  6442. //恢复广告和音频播放
  6443. ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
  6444. if(Error_Succeed != rc){
  6445. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("EndInstallPackTask set UpdateState to 0 fail, err=%d",(int)rc);
  6446. }
  6447. }
  6448. InstallPackTaskEvent* pEvent = (InstallPackTaskEvent*)event;
  6449. if(pEvent->isSucc){
  6450. //安装成功进入切换,设置状态为S和新版本号
  6451. //写入运行时文件
  6452. bool isWriteOk=false;
  6453. while(true){
  6454. if (!m_TempDepUpgradeFlag) {
  6455. if (SetRunConfigStrValue("upgradeTask", "NewVersion", m_currentTask.NewVersion.GetData()) != Error_Succeed) {
  6456. break;
  6457. }
  6458. }
  6459. else {
  6460. if (SetRunConfigStrValue("upgradeTask", "depNewVersion", m_currentTask.depNewVersion.GetData()) != Error_Succeed) {
  6461. break;
  6462. }
  6463. }
  6464. if(SetRunConfigStrValue("upgradeTask","PendingState","S")!=Error_Succeed){
  6465. break;
  6466. }
  6467. isWriteOk=true;
  6468. break;
  6469. }
  6470. if(isWriteOk){
  6471. //告警安装
  6472. struct CTaskProcess up;
  6473. up.strPackName = m_currentTask.pack_name;//安装包名
  6474. if(!m_currentTask.NewVersion.IsNullOrEmpty()){
  6475. up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
  6476. }else if(!m_currentTask.depNewVersion.IsNullOrEmpty()){
  6477. up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
  6478. }else {
  6479. up.installVersion = m_currentVersion.ToString();//当前版本号
  6480. }
  6481. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6482. up.cInstallState = "W";
  6483. up.strInstallComment = "安装成功";
  6484. SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID);
  6485. m_currentTask.cPendingState = "S";//改变内存变量S
  6486. //modify by lwt 修改为非兜底升级时等待一段时间再进入切换状态。
  6487. if (m_startFlag) {
  6488. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
  6489. }
  6490. else {
  6491. ScheduleTimer(4, 20 * 1000);//等待20秒再进入切换状态
  6492. }
  6493. }else{
  6494. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
  6495. Sleep(5 * 1000);//等待五秒
  6496. PostEventFIFO(new InstallPackTaskEvent(true,"",0));//继续写运行时文件
  6497. }
  6498. }else{
  6499. if(pEvent->failStatus==0){
  6500. //安装失败,设置状态为C
  6501. if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
  6502. //告警下载取消
  6503. struct CTaskProcess up;
  6504. up.strPackName = m_currentTask.pack_name;//安装包名
  6505. up.installVersion = m_currentTask.pack_version;//安装的版本
  6506. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6507. up.cInstallState = "C";
  6508. up.strInstallComment = pEvent->errMsg;//错误信息
  6509. SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5663");
  6510. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("install pack is fail ,prepare to s2");
  6511. m_currentTask.cPendingState = "C";//改变内存变量C
  6512. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  6513. }else{
  6514. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
  6515. Sleep(5 * 1000);//等待五秒
  6516. PostEventFIFO(new InstallPackTaskEvent(false,pEvent->errMsg,0));//继续写运行时文件
  6517. }
  6518. }else if(pEvent->failStatus==-1){
  6519. //安装失败,设置状态为X 未知
  6520. if(SetRunConfigStrValue("upgradeTask","PendingState","X")==Error_Succeed){
  6521. //告警下载取消
  6522. struct CTaskProcess up;
  6523. up.strPackName = m_currentTask.pack_name;//安装包名
  6524. up.installVersion = m_currentTask.pack_version;//安装的版本
  6525. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6526. up.cInstallState = "X";
  6527. up.strInstallComment = pEvent->errMsg;//错误信息
  6528. SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5664");
  6529. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("install pack is fail ,prepare to s2");
  6530. m_currentTask.cPendingState = "X";//改变内存变量X
  6531. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  6532. }else{
  6533. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
  6534. Sleep(5 * 1000);//等待五秒
  6535. PostEventFIFO(new InstallPackTaskEvent(false,pEvent->errMsg,-1));//继续写运行时文件
  6536. }
  6537. }
  6538. }
  6539. }
  6540. else if (event->iEvt == Event_EndRollBackCheckTask) {
  6541. if (m_currentTask.stop_media_play) {
  6542. //恢复广告和音频播放
  6543. ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
  6544. if (Error_Succeed != rc) {
  6545. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EndInstallPackTask set UpdateState to 0 fail, err=%d", (int)rc);
  6546. }
  6547. }
  6548. RollBackCheckTaskEvent* pEvent = (RollBackCheckTaskEvent*)event;
  6549. if (pEvent->isSucc) {
  6550. bool isWriteOk = false;
  6551. while (true) {
  6552. if (!m_TempDepUpgradeFlag) {
  6553. if (SetRunConfigStrValue("upgradeTask", "NewVersion", m_currentTask.NewVersion.GetData()) != Error_Succeed) {
  6554. break;
  6555. }
  6556. }
  6557. else {
  6558. if (SetRunConfigStrValue("upgradeTask", "depNewVersion", m_currentTask.depNewVersion.GetData()) != Error_Succeed) {
  6559. break;
  6560. }
  6561. }
  6562. isWriteOk = true;
  6563. break;
  6564. }
  6565. if (isWriteOk) {
  6566. m_currentTask.cPendingState = "S";//改变内存变量S
  6567. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查成功");
  6568. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
  6569. }
  6570. else {
  6571. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_EndRollBackCheckTask write runinfo is fail,retry int 5's");
  6572. Sleep(5 * 1000);//等待五秒
  6573. PostEventFIFO(new RollBackCheckTaskEvent(true, "", ""));//继续写运行时文件
  6574. }
  6575. }
  6576. else {
  6577. //失败
  6578. if (pEvent->failReason.compare("X") != 0) {
  6579. //回退失败,设置状态为C
  6580. if (SetRunConfigStrValue("upgradeTask", "PendingState", "C") == Error_Succeed) {
  6581. //回滚失败取消
  6582. struct CTaskProcess up;
  6583. up.strPackName = "";//安装包名
  6584. up.installVersion = m_currentTask.pack_version;//回退的版本
  6585. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6586. up.cInstallState = "C";
  6587. up.strInstallComment = pEvent->errMsg.GetData();//错误信息
  6588. SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID,"RTA5668");
  6589. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackCheck is fail ,prepare to s2");
  6590. m_currentTask.cPendingState = "C";//改变内存变量C
  6591. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查失败");
  6592. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  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(false, pEvent->errMsg, "C"));//继续写运行时文件
  6598. }
  6599. }
  6600. else if (pEvent->failReason.compare("X")==0) {
  6601. //安装失败,设置状态为X 未知
  6602. if (SetRunConfigStrValue("upgradeTask", "PendingState", "X") == Error_Succeed) {
  6603. //告警下载取消
  6604. struct CTaskProcess up;
  6605. up.strPackName = "";//安装包名
  6606. up.installVersion = m_currentTask.pack_version;//回退的版本
  6607. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6608. up.cInstallState = "X";
  6609. up.strInstallComment = pEvent->errMsg.GetData();//错误信息
  6610. SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID,"RTA5669");
  6611. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackCheck is fail ,prepare to s2");
  6612. m_currentTask.cPendingState = "X";//改变内存变量X
  6613. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查失败");
  6614. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  6615. }
  6616. else {
  6617. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_EndRollBackCheckTask write runinfo is fail,retry int 5's");
  6618. Sleep(5 * 1000);//等待五秒
  6619. PostEventFIFO(new RollBackCheckTaskEvent(false, pEvent->errMsg, "X"));//继续写运行时文件
  6620. }
  6621. }
  6622. }
  6623. }
  6624. return 0;
  6625. }
  6626. void CUpgradeTaskFSM::s6_on_entry()
  6627. {
  6628. //进入切换处理流程:不同类型包判断不同
  6629. //时间长,需要判断后台是否取消任务
  6630. if (CheckIfCanSwitchNow())
  6631. {
  6632. ScheduleTimer(2,1000);//进行版本切换操作
  6633. }else{
  6634. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("not applicable time to switch, retry in 20's");
  6635. ScheduleTimer(1, 20*1000);//继续等待
  6636. }
  6637. ScheduleTimer(3, 30*1000);//启动查询任务是否有效
  6638. }
  6639. void CUpgradeTaskFSM::s6_on_exit()
  6640. {
  6641. CancelTimer(1);//判断是否切换时间计时器
  6642. CancelTimer(2);//切换运行时文件写入计时器
  6643. CancelTimer(3);//任务取消计时器
  6644. CancelTimer(4);//切换重启写入active文件计时器
  6645. CancelTimer(5);//active文件写入失败写运行时计时器
  6646. m_bSwitchFlag = false;//切换标志重置。
  6647. }
  6648. unsigned int CUpgradeTaskFSM::s6_on_event(FSMEvent* event)
  6649. {
  6650. if (event->iEvt == EVT_TIMER)
  6651. {
  6652. if(event->param1==1)
  6653. {
  6654. //进入切换处理流程:不同类型包判断不同
  6655. if (CheckIfCanSwitchNow())
  6656. {
  6657. ScheduleTimer(2,1000);//进行版本切换操作
  6658. }else{
  6659. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("not applicable time to switch, retry in 20's");
  6660. ScheduleTimer(1, 20*1000);//继续等待切换时机
  6661. }
  6662. }else if(event->param1==2){
  6663. //修改运行时文件状态T
  6664. if(SetRunConfigStrValue("upgradeTask","PendingState","T")==Error_Succeed){
  6665. //告警切换
  6666. struct CTaskProcess up;
  6667. up.strPackName = m_currentTask.pack_name;//安装包名
  6668. if (!m_currentTask.NewVersion.IsNullOrEmpty()) {
  6669. up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
  6670. }else if (!m_currentTask.depNewVersion.IsNullOrEmpty()) {
  6671. up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
  6672. }else {
  6673. up.installVersion = m_currentVersion.ToString();//当前版本号
  6674. }
  6675. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6676. up.cInstallState = "S";
  6677. up.strInstallComment = "已设为启动版本";
  6678. if (m_currentTask.task_type.Compare("U")==0) {
  6679. SendUpgradeTaskProgress(up,UpgradeMgr_SWTICH_ID);
  6680. }
  6681. else{
  6682. SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_SWTICH_ID);
  6683. }
  6684. m_currentTask.cPendingState = "T";//改变内存变量
  6685. ScheduleTimer(4,5*1000);//等待告警上报,准备修改active文件,进行切换
  6686. }else{
  6687. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("switch write runinfo is fail,retry in 10's");
  6688. ScheduleTimer(1, 10*1000);//继续等待下次切换机会再重试
  6689. }
  6690. }else if(event->param1==3){
  6691. Task::QueryTaskStatus* dTask = new Task::QueryTaskStatus(this);
  6692. ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
  6693. if(rc!=Error_Succeed){
  6694. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s6 create QueryTaskStatus fail,err=%d",(int)rc);
  6695. ScheduleTimer(3, 30*1000);//再次查询任务是否有效
  6696. }
  6697. }else if(event->param1==4){
  6698. //修改active文件
  6699. if (!m_TempDepUpgradeFlag) {
  6700. if (UpgradeToNewVersion() == Error_Succeed) {
  6701. SwitchUpgradeNow();//切换版本
  6702. }
  6703. else {
  6704. ScheduleTimer(5, 3 * 1000);//UpgradeToNewVersion执行失败后写运行时计时器
  6705. }
  6706. }
  6707. else {
  6708. if (UpgradeDepToNewVersion() == Error_Succeed) {
  6709. SwitchUpgradeDepNow();//适配器切换版本
  6710. }
  6711. else {
  6712. ScheduleTimer(5, 3 * 1000);//UpgradeToDepNewVersion执行失败后写运行时计时器
  6713. }
  6714. }
  6715. }else if(event->param1==5){
  6716. if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
  6717. //告警切换失败
  6718. struct CTaskProcess up;
  6719. up.strPackName = m_currentTask.pack_name;//安装包名
  6720. if (!m_currentTask.NewVersion.IsNullOrEmpty()) {
  6721. up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
  6722. }else if (!m_currentTask.depNewVersion.IsNullOrEmpty()) {
  6723. up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
  6724. }else {
  6725. up.installVersion = m_currentVersion.ToString();//当前版本号
  6726. }
  6727. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6728. up.cInstallState = "C";
  6729. up.strInstallComment = "更新active文件失败";//错误信息
  6730. if (m_currentTask.task_type.Compare("U")==0) {
  6731. SendUpgradeTaskProgress(up,UpgradeMgr_SWTICH_ID,"RTA5665");
  6732. }
  6733. else {
  6734. SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_SWTICH_ID, "RTA5670");
  6735. }
  6736. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("UpgradeToNewVersion is fail ,prepare to s2");
  6737. m_currentTask.cPendingState = "C";//改变内存变量C
  6738. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
  6739. }else{
  6740. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("UpgradeToNewVersion fail, write runinfo is fail,retry in 10's");
  6741. ScheduleTimer(5,10*1000);//继续重试写入运行时
  6742. }
  6743. }
  6744. }else if (event->iEvt == Event_EndQueryTaskStatus){
  6745. QueryTaskStatusEvent* pEvent = (QueryTaskStatusEvent*)event;
  6746. if(pEvent->isSucc){
  6747. if(pEvent->isTask_valid){
  6748. ScheduleTimer(3, 30*1000);//有效,再次查询任务是否有效
  6749. }else{
  6750. //无效,清理任务
  6751. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("query upgradeTask is cancel");
  6752. if(ClearCurrTaskInfo()){
  6753. //告警下载取消
  6754. struct CTaskProcess up;
  6755. up.strPackName = m_currentTask.pack_name;//安装包名
  6756. up.installVersion = m_currentTask.pack_version;//安装的版本
  6757. up.CurrentVersion = getAlarmCurrVersion();//当前的版本
  6758. up.cInstallState = "C";
  6759. up.strInstallComment = "任务策略已取消";
  6760. if (m_currentTask.task_type.Compare("U")==0) {
  6761. SendUpgradeTaskProgress(up, UpgradeMgr_SWTICH_ID,"RTA5666");
  6762. }
  6763. else {
  6764. SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_SWTICH_ID, "RTA5671");
  6765. }
  6766. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask is cancel,prepare to s3");
  6767. PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
  6768. }else{
  6769. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry in 5's");
  6770. Sleep(5 * 1000);//等待五秒,继续清理
  6771. PostEventFIFO(new QueryTaskStatusEvent(true,false));//继续取消任务
  6772. }
  6773. }
  6774. }else{
  6775. ScheduleTimer(3, 30*1000);//通讯失败,再次查询任务是否有效
  6776. }
  6777. }
  6778. return 0;
  6779. }
  6780. void CUpgradeTaskFSM::s7_on_entry()
  6781. {
  6782. DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("enter disable state , wait framework restart or OS restart");
  6783. }
  6784. void CUpgradeTaskFSM::s7_on_exit()
  6785. {
  6786. }
  6787. unsigned int CUpgradeTaskFSM::s7_on_event(FSMEvent* event)
  6788. {
  6789. return 0;
  6790. }