UpgradeTaskFSM.cpp 290 KB

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