UpgradeTaskFSM.cpp 288 KB

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