UpgradeTaskFSM.cpp 290 KB

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