1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501 |
- #include "UpgradeTaskFSM.h"
- #include "fileutil.h"
- #include "iniutil.h"
- #include "memutil.h"
- #include "RVCComm.h"
- #include <regex>
- #include "mod_UpgradeMgr.h"
- #include "UpgradeManager_msg_g.h"
- #ifdef RVC_OS_WIN
- #include <WinBase.h>
- #include <io.h>
- #include "XUnzip.h"
- #include <ShellAPI.h>
- #else
- #include <sys/utsname.h>
- #include "XUnZipZilb.h"
- #endif
- #include "EventCode.h"
- #include "json/json.h"
- namespace Task
- {
- //计算和发送文件hash
- struct SendSM3Task : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit SendSM3Task(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- int tryCount=3;//总共3次机会
- bool SendHashOK= false;
- while(tryCount>0){
- //计算hash
- if(m_fsm->m_fileSM3ListHash.IsNullOrEmpty()){
- if(getSM3Hash()){
- 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());
- }else{
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_GET_SM3_HASH_FAIL, "get SM3 list fail");
- tryCount--;
- Sleep(60*1000);//等待60s再计算
- continue;
- }
- }
- //发送hash
- if(sendSM3Hash()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("GetSM3Task")("send SM3 list succ");
- m_fsm->isSendHash=true;
- SendHashOK = true;
- break;
- }else{
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_SEND_SM3_HASH_FAIL, "send SM3 list fail");
- m_fsm->isSendHash=false;
- Sleep(60*1000);//等待60s再上传
- tryCount--;
- continue;
- }
- }
-
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::SendSM3TaskEvent(SendHashOK));//返回处理结果
- }
- bool getSM3Hash(){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin get SM3 list");
- CSmallDateTime beginT = CSmallDateTime::GetNow();
- CSimpleStringA tempSM3ListStr = "";
- ErrorCodeEnum rc = m_fsm->GetSM3List(tempSM3ListStr);
- CSmallDateTime endT = CSmallDateTime::GetNow();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get SM3 list 耗时%d秒",(DWORD)(endT-beginT));
- if (rc != Error_Succeed)
- {
- LogWarn(Severity_Low, rc, ERR_TASK_GET_SM3_HASH_FAIL, "get SM3 list fail");
- return false;
- }
- else
- {
- //tempSM3ListStr 这个值有可能因为配置的文件夹下面没有文件,故为空
- if(tempSM3ListStr.IsNullOrEmpty()){
- m_fsm->m_fileSM3ListHash = "TerminalTempHash";
- return true;
- }else{
- CSimpleStringA tempSM3HashStr = "";
- if(Error_Succeed==m_fsm->SM3DataToStr(tempSM3ListStr,tempSM3HashStr,false)){
- m_fsm->m_fileSM3ListHash = tempSM3HashStr;
- return true;
- }else{
- LogWarn(Severity_Low, rc, ERR_TASK_GET_SM3_HASH_FAIL, "get SM3 list hash fail");
- return false;
- }
- }
- }
- }
- bool sendSM3Hash(){
- //LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- //发送hash
- bool bRet = SendSM3TaskImpl(client);
- client->Destory();
- return bRet;
- }
- bool SendSM3TaskImpl(IHttpFunc* client){
- HttpStruct::SendSM3TaskReq qTempReq;
- HttpStruct::SendSM3TaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SendSM3Task get CSystemStaticInfo fail");
- return false;
- }
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["software_version"] = m_fsm->m_currentVersion.ToString().GetData();
- rootReq["file_hash_list"] = m_fsm->m_fileSM3List.GetData();//hash集合
- rootReq["list_hash"] = m_fsm->m_fileSM3ListHash.GetData();//64位
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.sendSM3TaskUrl;//访问地址
- qTempReq.m_timeOut = 60;//设置传送超时时间为60s
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- if(!client->Post(qTempReq, qTempRet)){
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- if(rootRet["data"].asBool()){
- return true;//写入成功
- }else{
- return false;//写入失败
- }
- }else{
- return false;//写入失败
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("SendSM3Task [success] is false");
- return false;//写入失败
- }
- }
- };
- //更新任务状态
- struct UpdateTaskStatus : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit UpdateTaskStatus(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- bool isSendSucc=false;//更新是否成功标志
- if(UpdateTaskStatusImpl(client)){
- isSendSucc = true;
- }else{
- isSendSucc = false;
- }
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::UpdateTaskStatusEvent(isSendSucc));//返回处理结果
- }
- bool UpdateTaskStatusImpl(IHttpFunc* client){
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus get CSystemStaticInfo fail,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- return false;
- }
- HttpStruct::UpdateTaskStatusReq qTempReq;
- HttpStruct::UpdateTaskStatusRet qTempRet;
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
- //状态为C时,为X时,或者T,版本不一致,则是回退,否则是成功
- //返回任务结果给服务器
- if(m_fsm->m_currentTask.cPendingState=="C"){
- rootReq["upgrade_status"] = "F";//失败
- }else if(m_fsm->m_currentTask.cPendingState=="X"){
- rootReq["upgrade_status"] = "X";//未知状态
- }else if(m_fsm->m_currentTask.cPendingState=="T"){
- if (m_fsm->m_currentTask.task_type.Compare("U") == 0) {
- if (m_fsm->isTerminalInstall()) {
- //安装状态时,达到终态就算成功
- rootReq["upgrade_status"] = "S";//成功
- }
- else {
- if (m_fsm->m_currentTask.NewVersion == m_fsm->m_currentVersion.ToString() ||
- m_fsm->m_currentTask.depNewVersion == m_fsm->m_currentDepVersion ||
- (m_fsm->m_currentTask.NewVersion == "" && m_fsm->m_currentTask.depNewVersion == "")) {
- //升级成功
- rootReq["upgrade_status"] = "S";//成功
- }
- else {
- //升级失败,回滚版本导致
- rootReq["upgrade_status"] = "F";//失败
- }
- }
- }
- else if (m_fsm->m_currentTask.task_type.Compare("R") == 0) {
- if (m_fsm->m_currentTask.NewVersion == m_fsm->m_currentVersion.ToString()||
- m_fsm->m_currentTask.depNewVersion == m_fsm->m_currentDepVersion) {
- //升级成功
- rootReq["upgrade_status"] = "S";//成功
- }
- else {
- //升级失败,回滚版本导致
- rootReq["upgrade_status"] = "F";//失败
- }
- }
- else {
- //不支持此类型,任务执行失败
- rootReq["upgrade_status"] = "X";//失败
- }
- }
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
-
- qTempReq.m_url=m_fsm->m_centerUrl.updateTaskUrl;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus req=%s",qTempReq.m_reqStr.c_str());
- if(!client->Post(qTempReq, qTempRet)){
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- int isUpdate =rootRet["data"].asInt();
- //0:更新失败 1:更新成功 2:任务不属于此终端等异常情况,默认成功
- if(isUpdate==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus update fail: upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- return false;//更新失败
- }else if(isUpdate==1){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus update succ: upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- return true;//更新成功
- }else if(isUpdate==2){
- 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());
- return true;//任务异常,更新成功
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus update fail: upgradeTaskId=%s, ret=%d",m_fsm->m_currentTask.upgradeTaskId.GetData(),isUpdate);
- return false;//更新失败
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus update fail: [data] is not exist ,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- return false;//更新失败
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpdateTaskStatus update fail: [success] is false,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- return false;//更新失败
- }
- }
- };
- //查询当前任务
- struct QueryCurrTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit QueryCurrTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //根据任务ID查询任务当前的策略。
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- bool isSendSucc=false;//查询是否成功标志
- bool isTask_valid=false;//任务是否有效
- if(QueryCurrTaskImpl(client,isTask_valid)){
- isSendSucc = true;
- }else{
- isSendSucc = false;
- }
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryCurrTaskEvent(isSendSucc,isTask_valid));//返回处理结果
- }
- bool QueryCurrTaskImpl(IHttpFunc* client,bool &isValid){
- HttpStruct::QueryCurrTaskReq qTempReq;
- HttpStruct::QueryCurrTaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewTask get CSystemStaticInfo fail");
- return false;
- }
- //机器版本
- CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
- //框架版本
- CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
- //适配器版本
- CSimpleStringA strDepVersion = m_fsm->m_currentDepVersion;
- // OS版本
- #ifdef RVC_OS_WIN
- OSVERSIONINFO osvi;
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osvi);
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d",osvi.dwMajorVersion,osvi.dwMinorVersion,osvi.dwBuildNumber);
- #else
- DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
- struct utsname kernel_info;
- int ret = uname(&kernel_info);
- if (ret == 0) {
- int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
- }
- else {
- Dbg("get linux kernel version fail: %s", strerror(errno));
- }
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
- #endif
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
- rootReq["machine_type"] = info.strMachineType.GetData();
- rootReq["software_version"] = strInstallVersion.GetData();
- rootReq["os_version"] = strOSVersion.GetData();
- rootReq["machine_version"] = strMachineVersion.GetData();
- rootReq["dep_version"] = strDepVersion.GetData();//适配器版本
-
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.queryCurrTaskUrl;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- if(!client->Post(qTempReq, qTempRet)){
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- if(rootRet["data"]["task_status"].asBool()){
- isValid = true;//任务有效
- if (rootRet["data"].isMember("task_type")) {
- m_fsm->m_currentTask.task_type = rootRet["data"]["task_type"].asString().c_str();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask query task_type=%s", m_fsm->m_currentTask.task_type.GetData());
- }
- else {
- m_fsm->m_currentTask.task_type = "U";//兼容旧服务端程序,无字段值时默认是升级模式
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask query task_type is not exist , use default value task_type = U");
- }
- if (m_fsm->m_currentTask.task_type.Compare("U") == 0) {
- //升级任务
- if (!ParamCheck(rootRet)) {
- 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());
- return false;//查询失败 升级任务参数效验失败,无法进行升级
- }
- else {
- CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
- if (m_fsm->m_currentTask.pack_name != packNameStr) {
- //异常情况
- CSimpleStringA errmsg = CSimpleStringA::Format("runinfo packName[%s] is not equal server packName[%s]", m_fsm->m_currentTask.pack_name.GetData(), packNameStr.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_PACKNAME_NOT_EQUAL, errmsg.GetData());
- }
- m_fsm->m_currentTask.pack_name = packNameStr;//用最新的包名进行后面的安装和下载
- m_fsm->m_currentTask.file_path = rootRet["data"]["file_path"].asString().c_str();
- m_fsm->m_currentTask.download_url = rootRet["data"]["download_url"].asString().c_str();
- m_fsm->m_currentTask.pack_hash = rootRet["data"]["pack_hash"].asString().c_str();
- m_fsm->m_currentTask.pack_length = (long)rootRet["data"]["pack_length"].asInt();
- m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
- m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
- m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
- //解析step json
- if (!ParseInstallStep(rootRet)) {
- m_fsm->ClearInstallStep();
- 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());
- return false;//解析安装步骤失败
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("current task id =%s", m_fsm->m_currentTask.upgradeTaskId.GetData());
- return true;//查询成功
- }
- }
- else if (m_fsm->m_currentTask.task_type.Compare("R") == 0) {
- //回退任务
- if (!rollbackParamCheck(rootRet)) {
- 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());
- return false;//查询失败 回退任务参数效验失败,无法进行回退
- }
- else {
- m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
- m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
- m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("current task id =%s", m_fsm->m_currentTask.upgradeTaskId.GetData());
- return true;//查询成功
- }
- }
- else {
- 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());
- return false;//查询失败
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask query task is invalid, taskid=%s",m_fsm->m_currentTask.upgradeTaskId.GetData());
- isValid = false;//任务无效
- return true;//查询成功
- }
- }else{
- 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());
- return false;//查询失败
- }
- }else{
- 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());
- return false;//查询失败
- }
- }
- bool ParamCheck(Json::Value rootRet){
- CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_name] is %s",packNameStr.GetData());
- if(packNameStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_name] is null");
- return false;
- }
- CSimpleStringA filePathStr = rootRet["data"]["file_path"].asString().c_str();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [file_path] is %s",filePathStr.GetData());
- if(filePathStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [file_path] is null");
- return false;
- }
- CSimpleStringA downloadUrlStr = rootRet["data"]["download_url"].asString().c_str();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [download_url] is %s",downloadUrlStr.GetData());
- if(downloadUrlStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [download_url] is null");
- return false;
- }
- CSimpleStringA packHashStr = rootRet["data"]["pack_hash"].asString().c_str();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_hash] is %s",packHashStr.GetData());
- if(packHashStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_hash] is null");
- return false;
- }
- long packLengthLong = (long)rootRet["data"]["pack_length"].asInt();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_length] is %d",packLengthLong);
- int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [reboot_type] is %d",rebootTypeInt);
- if(rebootTypeInt!=1 && rebootTypeInt!=2 && rebootTypeInt!=0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [reboot_type] is invalid ,reboot_type=%d",rebootTypeInt);
- return false;
- }
- CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_version] is %s",packVersionStr.GetData());
- if(!packVersionStr.IsNullOrEmpty()){
- int rebootType = rootRet["data"]["reboot_type"].asInt();
- if(rebootType == 1 || rebootType == 2){
- return true;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_version] is not null ,[reboot_type] is not equal 1 or 2");
- return false;
- }
- }
- return true;
- }
- bool rollbackParamCheck(Json::Value rootRet) {
- int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
- if (rebootTypeInt != 1 && rebootTypeInt != 2) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [reboot_type] is invalid ,reboot_type=%d", rebootTypeInt);
- return false;
- }
- CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
- if (packVersionStr.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask paramCheck [pack_version] is null");
- return false;
- }
- return true;
- }
- bool ParseInstallStep(Json::Value rootRet){
- //清理以前的遗留的安装步骤
- m_fsm->ClearInstallStep();
- string cmdstr = rootRet["data"]["cmd"].asString();
- if(cmdstr.empty()){
- return true;//为空则直接不解析
- }
- Json::Reader reader;
- Json::Value InstallRet;
- if (!reader.parse(cmdstr, InstallRet, false))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CURR_TASK_FAIL,CSimpleStringA::Format("QueryCurrTask parse cmd fail,cmdstr=%s",cmdstr.c_str()).GetData());
- return false;//解析失败
- }
- //install_step
- for(int i=0;i<InstallRet.size();i++){
- if(!InstallRet[i]["seq"].isInt()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][seq] is not int");
- return false;
- }
- int stepSeq = InstallRet[i]["seq"].asInt();
- if(!InstallRet[i]["cmdType"].isString()&&!InstallRet[i]["cmdType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][cmdType] is not string");
- return false;
- }
- CSimpleStringA cmdType = InstallRet[i]["cmdType"].asString().c_str();
- if(cmdType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][cmdType] is null");
- return false;
- }
- if(!InstallRet[i]["cmdFail"].isInt()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][cmdFail] is not int");
- return false;
- }
- int cmdFail = InstallRet[i]["cmdFail"].asInt();
- if(!InstallRet[i]["srcPathType"].isString()&&!InstallRet[i]["srcPathType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][srcPathType] is not string");
- return false;
- }
- CSimpleStringA srcPathType = InstallRet[i]["srcPathType"].asString().c_str();
- if(cmdType=="Copy"){
- //复制指令时,不为空
- if(srcPathType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][srcPathType] is null");
- return false;
- }
- }
- if(!InstallRet[i]["srcPath"].isString()&&!InstallRet[i]["srcPath"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][srcPath] is not string");
- return false;
- }
- CSimpleStringA srcPath = InstallRet[i]["srcPath"].asString().c_str();
- if(cmdType=="Copy"){
- //复制指令时,不为空
- if(srcPath.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][srcPath] is null");
- return false;
- }
- }
- if(!InstallRet[i]["dstPathType"].isString()&&!InstallRet[i]["dstPathType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][dstPathType] is not string");
- return false;
- }
- CSimpleStringA dstPathType = InstallRet[i]["dstPathType"].asString().c_str();
- if(cmdType=="Copy"||cmdType=="Delete"||cmdType=="Run"){
- if(dstPathType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][dstPathType] is null");
- return false;
- }
- }
- if(!InstallRet[i]["dstPath"].isString()&&!InstallRet[i]["dstPath"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][dstPath] is not string");
- return false;
- }
- CSimpleStringA dstPath = InstallRet[i]["dstPath"].asString().c_str();
- if(cmdType=="Delete"||cmdType=="Run"){
- if(dstPath.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryCurrTask ParseInstallStep [cmd][dstPath] is null");
- return false;
- }
- }
- CUpgradeTaskFSM::CInstallStep* iStep= new CUpgradeTaskFSM::CInstallStep();
- iStep->stepSeq = stepSeq;
- iStep->cmdType = cmdType;
- iStep->cmdFail = cmdFail;
- iStep->srcPathType = srcPathType;
- iStep->srcPath = srcPath;
- iStep->dstPathType =dstPathType;
- iStep->dstPath =dstPath;
- m_fsm->m_currentTask.install_step.push(iStep);//加入队尾
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d",InstallRet.size());
- return true;
- }
- };
- //预查询新任务
- struct QueryNewPreTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit QueryNewPreTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- //LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- //查询新任务
- bool isSendSucc=false;////查询是否成功标志
- if(QueryNewPreTaskImpl(client)){
- isSendSucc = true;
- }else{
- isSendSucc = false;
- }
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryNewPreTaskEvent(isSendSucc));//返回处理结果
- }
- bool QueryNewPreTaskImpl(IHttpFunc* client){
- HttpStruct::QueryNewTaskReq qTempReq;
- HttpStruct::QueryNewTaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewPreTask get CSystemStaticInfo fail");
- return false;
- }
- //机器版本
- CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
- //框架版本
- CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
- //适配器版本
- CSimpleStringA strDepVersion = m_fsm->m_currentDepVersion;
- // OS版本
- #ifdef RVC_OS_WIN
- OSVERSIONINFO osvi;
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osvi);
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber);
- #else
- DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
- struct utsname kernel_info;
- int ret = uname(&kernel_info);
- if (ret == 0) {
- int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
- }
- else {
- Dbg("get linux kernel version fail: %s", strerror(errno));
- }
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
- #endif
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["machine_type"] = info.strMachineType.GetData();
- rootReq["software_version"] = strInstallVersion.GetData();
- rootReq["os_version"] = strOSVersion.GetData();
- rootReq["machine_version"] = strMachineVersion.GetData();
- rootReq["dep_version"] = strDepVersion.GetData();//适配器版本
- //预查询判断加入查询何种任务。
- if (m_fsm->isTerminalInstall()) {
- rootReq["task_type"] = "I";//安装任务
- }
- else {
- rootReq["task_type"] = "U";//升级任务
- }
- #ifdef RVC_OS_WIN
- rootReq["system_type"] = "W";//表示是windows类型的机器
- #else
- rootReq["system_type"] = "L";//表示是uos类型的机器
- #endif
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.queryPreTaskUrl;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- if(!client->Post(qTempReq, qTempRet)){
- if (qTempRet.m_sysCode == 6) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5651")("终端查询任务域名解析失败");
- }else if(qTempRet.m_sysCode == 28){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5652")("终端查询任务连接总行服务超时");
- }else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_PerTask_HTTP_ERR).setResultCode("RTA5653")("终端查询任务失败:%s", qTempRet.m_errMsg.c_str());
- }
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false)){
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- //解析任务,可能不存在任务
- if(rootRet["data"]["task_id"].asString()!=""){
- m_fsm->m_strPreTaskId = rootRet["data"]["task_id"].asString().c_str();
- int need_hash = rootRet["data"]["need_hash"].asInt();
- if(need_hash==0){
- m_fsm->m_bNeedHash = false;
- }else{
- m_fsm->m_bNeedHash = true;
- }
- return true;//查询成功
- }else{
- //无任务
- m_fsm->m_strPreTaskId = "";
- m_fsm->m_bNeedHash =false;
- return true;//查询成功
- }
- }else{
- 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());
- return false;//查询失败
- }
- }else{
- 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());
- return false;//查询失败
- }
- }
- };
- //继续查询新任务
- struct QueryNewContinueTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit QueryNewContinueTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- //查询新任务
- int retParm=QueryNewContinueTaskImpl(client);
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryNewContinueTaskEvent(retParm));//返回处理结果
- }
- // 0:重试 1:成功 2:跳出
- int QueryNewContinueTaskImpl(IHttpFunc* client){
- HttpStruct::QueryNewTaskReq qTempReq;
- HttpStruct::QueryNewTaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask get CSystemStaticInfo fail");
- return 0;//查询失败,继续查询
- }
- //机器版本
- CSimpleStringA strMachineVersion = CSimpleStringA::Format("%d.%d",info.MachineVersion.GetMajor(),info.MachineVersion.GetMinor());
- //框架版本
- CSimpleStringA strInstallVersion = m_fsm->m_currentVersion.ToString();
- //适配器版本
- CSimpleStringA strDepVersion = m_fsm->m_currentDepVersion;
-
- // OS版本
- #ifdef RVC_OS_WIN
- OSVERSIONINFO osvi;
- ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
- osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osvi);
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.%d", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber);
- #else
- DWORD dwMajorVersion(0), dwMinorVersion(0), dwBuildNumber(0);
- struct utsname kernel_info;
- int ret = uname(&kernel_info);
- if (ret == 0) {
- int n = sscanf((const char*)kernel_info.release, "%d.%d", &dwMajorVersion, &dwMinorVersion);
- }
- else {
- Dbg("get linux kernel version fail: %s", strerror(errno));
- }
- CSimpleStringA strOSVersion = CSimpleStringA::Format("%d.%d.0", dwMajorVersion, dwMinorVersion);
- #endif
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["task_id"] = m_fsm->m_strPreTaskId.GetData();
- rootReq["machine_type"] = info.strMachineType.GetData();
- rootReq["software_version"] = strInstallVersion.GetData();
- rootReq["os_version"] = strOSVersion.GetData();
- rootReq["machine_version"] = strMachineVersion.GetData();
- rootReq["dep_version"] = strDepVersion.GetData();//适配器版本
- #ifdef RVC_OS_WIN
- rootReq["system_type"] = "W";//表示是windows类型的机器
- #else
- rootReq["system_type"] = "L";//表示是uos类型的机器
- #endif
- if(m_fsm->m_bNeedHash&&m_fsm->isSendHash){
- //是否发送hash码并且发送成功了
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask with hash");
- rootReq["list_hash"] = m_fsm->m_fileSM3ListHash.GetData();
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask with no hash");
- rootReq["list_hash"] = "";
- }
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.queryContinueTaskUrl;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- if(!client->Post(qTempReq, qTempRet)){
- 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());
- return 0;//查询失败,继续查询
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return 0;//查询失败,继续查询
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- //解析任务,可能不存在任务,task_id为空,则表示无此任务。
- if(rootRet["data"]["task_id"].asString()!=""){
- //task_status 0-无效 1-有效 2-对比不通过 3-hash内容为空
- int task_status = rootRet["data"]["task_status"].asInt();
- if(task_status ==1){
- if (rootRet["data"].isMember("task_type")) {
- m_fsm->m_currentTask.task_type = rootRet["data"]["task_type"].asString().c_str();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask query task_type=%s", m_fsm->m_currentTask.task_type.GetData());
- }
- else {
- m_fsm->m_currentTask.task_type = "U";//兼容旧服务端程序,无字段值时默认是升级模式
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask query task_type is not exist , use default value task_type = U");
- }
- if (m_fsm->m_currentTask.task_type.Compare("U") == 0) {
- //pack_status 0-准备中 1-已就绪
- int status = rootRet["data"]["pack_status"].asInt();
- if (status == 1) {
- if (!ParamCheck(rootRet)) {
- 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());
- return 0;//查询失败 升级任务参数效验失败,告警码不同
- }
- else {
- m_fsm->m_currentTask.upgradeTaskId = rootRet["data"]["task_id"].asString().c_str();
- m_fsm->m_currentTask.pack_name = rootRet["data"]["pack_name"].asString().c_str();
- m_fsm->m_currentTask.file_path = rootRet["data"]["file_path"].asString().c_str();
- m_fsm->m_currentTask.download_url = rootRet["data"]["download_url"].asString().c_str();
- m_fsm->m_currentTask.pack_hash = rootRet["data"]["pack_hash"].asString().c_str();
- m_fsm->m_currentTask.pack_length = (long)rootRet["data"]["pack_length"].asInt();
- m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
- m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
- m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
- //解析step json
- if (!ParseInstallStep(rootRet)) {
- m_fsm->ClearInstallStep();
- 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());
- return 0;//查询失败 解析安装步骤失败,告警码不同
- }
- m_fsm->m_currentTask.createTaskVersion = m_fsm->m_currentVersion.ToString();//新策略,查询到包后,用当前版本值赋值
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new task id =%s", m_fsm->m_currentTask.upgradeTaskId.GetData());
- return 1;//查询成功
- }
- }
- else {
- //任务未准备好
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask query pack is not create ,please next query,status=%d", status);
- m_fsm->m_currentTask.upgradeTaskId = "";
- return 0;//查询成功,继续查询
- }
- }
- else if (m_fsm->m_currentTask.task_type.Compare("R") == 0) {
- //回退任务
- if (!rollbackParamCheck(rootRet)) {
- 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());
- return 0;//查询失败 升级任务参数效验失败,告警码不同
- }
- else {
- m_fsm->m_currentTask.upgradeTaskId = rootRet["data"]["task_id"].asString().c_str();
- m_fsm->m_currentTask.pack_version = rootRet["data"]["pack_version"].asString().c_str();
- m_fsm->m_currentTask.reboot_type = rootRet["data"]["reboot_type"].asInt();
- m_fsm->m_currentTask.stop_media_play = rootRet["data"]["stop_media_play"].asBool();
- m_fsm->m_currentTask.createTaskVersion = m_fsm->m_currentVersion.ToString();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new task id =%s", m_fsm->m_currentTask.upgradeTaskId.GetData());
- return 1;//查询成功
- }
- }
- else {
- 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());
- return 0;//查询失败,taskType 不支持处理,告警码不同
- }
- }else{
- //任务状态无效,对比不通过,hash内容为空
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask query fail ,task_status=%d",task_status).GetData());
- return 2;//查询成功,但任务不再,跳出来
- }
- }else{
- //返回任务为空
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask return [task id] is null").GetData());
- return 2;//查询成功,但任务不再,跳出来
- }
- }else{
- 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());
- return 0;//查询失败,继续查询,告警码不同
- }
- }else{
- 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());
- return 0;//查询失败,继续查询
- }
- }
- bool ParamCheck(Json::Value rootRet){
- CSimpleStringA upgradeTaskIdStr = rootRet["data"]["task_id"].asString().c_str();
- if(upgradeTaskIdStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [task_id] is null");
- return false;
- }
- CSimpleStringA packNameStr = rootRet["data"]["pack_name"].asString().c_str();
- if(packNameStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [pack_name] is null");
- return false;
- }
- CSimpleStringA filePathStr = rootRet["data"]["file_path"].asString().c_str();
- if(filePathStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [file_path] is null");
- return false;
- }
- CSimpleStringA downloadUrlStr = rootRet["data"]["download_url"].asString().c_str();
- if(downloadUrlStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [download_url] is null");
- return false;
- }
- CSimpleStringA packHashStr = rootRet["data"]["pack_hash"].asString().c_str();
- if(packHashStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [pack_hash] is null");
- return false;
- }
- long packLengthStr = (long)rootRet["data"]["pack_length"].asInt();
-
- int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
- if(rebootTypeInt!=1 && rebootTypeInt!=2 && rebootTypeInt!=0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [reboot_type] is invalid ,reboot_type=%d",rebootTypeInt);
- return false;
- }
- //CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
- //if(!packVersionStr.IsNullOrEmpty()){
- // int rebootType = rootRet["data"]["reboot_type"].asInt();
- // if(rebootType == 1 || rebootType == 2){
- // return true;
- // }else{
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask paramCheck [pack_version] is not null ,[reboot_type] is not equal 1 or 2");
- // return false;
- // }
- //}
- return true;
- }
- bool rollbackParamCheck(Json::Value rootRet) {
- CSimpleStringA upgradeTaskIdStr = rootRet["data"]["task_id"].asString().c_str();
- if(upgradeTaskIdStr.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [task_id] is null");
- return false;
- }
- int rebootTypeInt = rootRet["data"]["reboot_type"].asInt();
- if(rebootTypeInt!=1 && rebootTypeInt!=2){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [reboot_type] is invalid ,reboot_type=%d",rebootTypeInt);
- return false;
- }
- CSimpleStringA packVersionStr = rootRet["data"]["pack_version"].asString().c_str();
- if (packVersionStr.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask paramCheck [pack_version] is null");
- return false;
- }
- return true;
- }
- bool ParseInstallStep(Json::Value rootRet){
- //清理以前的遗留的安装步骤
- m_fsm->ClearInstallStep();
- string cmdstr = rootRet["data"]["cmd"].asString();
- if(cmdstr.empty()){
- return true;//为空则直接不解析
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cmdstr =%s",cmdstr.c_str());
- Json::Reader reader;
- Json::Value InstallRet;
- if (!reader.parse(cmdstr, InstallRet, false))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_QUERY_CONTINUE_NEW_TASK_FAIL,CSimpleStringA::Format("QueryNewContinueTask parse cmd fail,cmdstr=%s",cmdstr.c_str()).GetData());
- return false;//解析失败
- }
- for(int i=0;i<InstallRet.size();i++){
- if(!InstallRet[i]["seq"].isInt()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][seq] is not int");
- return false;
- }
- int stepSeq = InstallRet[i]["seq"].asInt();
-
- if(!InstallRet[i]["cmdType"].isString()&&!InstallRet[i]["cmdType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][cmdType] is not string");
- return false;
- }
- CSimpleStringA cmdType = InstallRet[i]["cmdType"].asString().c_str();
- if(cmdType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][cmdType] is null");
- return false;
- }
-
- if(!InstallRet[i]["cmdFail"].isInt()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][cmdFail] is not int");
- return false;
- }
- int cmdFail = InstallRet[i]["cmdFail"].asInt();
-
- if(!InstallRet[i]["srcPathType"].isString()&&!InstallRet[i]["srcPathType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][srcPathType] is not string");
- return false;
- }
- CSimpleStringA srcPathType = InstallRet[i]["srcPathType"].asString().c_str();
- if(cmdType=="Copy"){
- //复制指令时,不为空
- if(srcPathType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][srcPathType] is null");
- return false;
- }
- }
-
- if(!InstallRet[i]["srcPath"].isString()&&!InstallRet[i]["srcPath"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][srcPath] is not string");
- return false;
- }
- CSimpleStringA srcPath = InstallRet[i]["srcPath"].asString().c_str();
- if(cmdType=="Copy"){
- //复制指令时,不为空
- if(srcPath.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][srcPath] is null");
- return false;
- }
- }
-
- if(!InstallRet[i]["dstPathType"].isString()&&!InstallRet[i]["dstPathType"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][dstPathType] is not string");
- return false;
- }
- CSimpleStringA dstPathType = InstallRet[i]["dstPathType"].asString().c_str();
- if(cmdType=="Copy"||cmdType=="Delete"||cmdType=="Run"){
- if(dstPathType.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][dstPathType] is null");
- return false;
- }
- }
-
- if(!InstallRet[i]["dstPath"].isString()&&!InstallRet[i]["dstPath"].isNull()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][dstPath] is not string");
- return false;
- }
- CSimpleStringA dstPath = InstallRet[i]["dstPath"].asString().c_str();
- if(cmdType=="Delete"||cmdType=="Run"){
- if(dstPath.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryNewContinueTask ParseInstallStep [cmd][dstPath] is null");
- return false;
- }
- }
-
- CUpgradeTaskFSM::CInstallStep* iStep= new CUpgradeTaskFSM::CInstallStep();
- iStep->stepSeq = stepSeq;
- iStep->cmdType = cmdType;
- iStep->cmdFail = cmdFail;
- iStep->srcPathType = srcPathType;
- iStep->srcPath = srcPath;
- iStep->dstPathType =dstPathType;
- iStep->dstPath =dstPath;
- m_fsm->m_currentTask.install_step.push(iStep);//加入队尾
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d",InstallRet.size());
- return true;
- }
- };
- //查询任务状态
- struct QueryTaskStatus : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit QueryTaskStatus(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- //LOG_FUNCTION();
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- //查询新任务
- bool isSendSucc=false;////查询是否成功标志
- bool isValid=false;//任务是否有效
- if(QueryTaskStatusImpl(client,isValid)){
- isSendSucc = true;
- }else{
- isSendSucc = false;
- }
- client->Destory();
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::QueryTaskStatusEvent(isSendSucc,isValid));//返回处理结果
- }
- bool QueryTaskStatusImpl(IHttpFunc* client,bool &isValid){
- HttpStruct::QueryCurrTaskReq qTempReq;
- HttpStruct::QueryCurrTaskRet qTempRet;
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryTaskStatus get CSystemStaticInfo fail");
- return false;
- }
-
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["task_id"] = m_fsm->m_currentTask.upgradeTaskId.GetData();
- string jsonReq = writer.write(rootReq);
- qTempReq.m_reqStr = jsonReq;//请求参数
- qTempReq.m_url=m_fsm->m_centerUrl.queryTaskStatus;//访问地址
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- qTempReq.m_printDbg = true;
- }
- if(!client->Post(qTempReq, qTempRet)){
- 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());
- return false;//失败
- }
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet=%s",qTempRet.m_retStr.c_str());
- }
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(qTempRet.m_retStr, rootRet, false))
- {
- 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());
- return false;//失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- if(rootRet.isMember("data")){
- isValid =rootRet["data"].asBool();
- return true;//查询成功
- }else{
- return false;//查询失败
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("QueryTaskStatus [success] is false");
- return false;//查询失败
- }
- }
- };
- //下载升级包
- struct DownloadPackTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit DownloadPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //下载升级包
- if(m_fsm->m_currentTask.pack_name.IsNullOrEmpty()||m_fsm->m_currentTask.pack_hash.IsNullOrEmpty()){
- string errMsg = CSimpleStringA::Format("DownloadPackTask fail,pack_name or pack_hash is null,upgradeTaskId=%s",m_fsm->m_currentTask.upgradeTaskId.GetData()).GetData();
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.c_str());
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskFailEvent(errMsg));//下载失败,返回结果,这种情况下无法继续下载
- return;
- }
- CSimpleStringA dPackName = m_fsm->m_currentTask.pack_name;
- CSimpleStringA dPakchash = m_fsm->m_currentTask.pack_hash;
- long lpacklen = m_fsm->m_currentTask.pack_length;
-
- //判断是否已经下载完成
- CSimpleStringA strPath;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetPath("Downloads", strPath);
- if(Error_Succeed != rc){
- 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());
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(false));//返回失败结果
- return;
- }
- CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strPath.GetData(), dPackName.GetData());
- if(m_fsm->IsPackDownloaded(strZipFile.GetData(),dPakchash.GetData(),lpacklen)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("download pack [%s] sm3[%s] is exist ,do not download.", strZipFile.GetData(),dPakchash.GetData());
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(true));//下载完成,返回成功结果
- return;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("download pack [%s] sm3[%s] is not exist ,prepare download.", strZipFile.GetData(),dPakchash.GetData());
- }
- //提前判断是否任务取消
- if(m_fsm->m_bTaskCancel){
- m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//取消下载任务,返回结果
- return;
- }
- if(m_fsm->m_bDownloadIdle){
- m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//下载中断,返回结果
- return;
- }
- //接着下载未完成的升级包
- IHttpFunc* client;
- client = create_http(m_fsm->HttpsLogCallBack);
- bool isDownloadSucc=false;//是否下载成功
- CSimpleStringA errMsg ;//下载失败错误信息
- int ret = DownloadPack(client,strZipFile.GetData(),dPakchash,errMsg);
- if(ret==0){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(false));//返回通讯失败结果
- }else if(ret ==1){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskEvent(true));//返回成功结果
- }else if(ret ==2){
- m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//下载中断,返回结果
- }else if(ret ==3){
- m_fsm->PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//取消下载任务,返回结果
- }else if(ret ==4){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::DownloadPackTaskFailEvent(errMsg.GetData()));//下载失败,任务中止
- }
- client->Destory();
- }
- //返回值 0:下载通讯失败 1:下载成功 2:下载中断 3:任务取消 4:下载失败
- int DownloadPack(IHttpFunc* client,const char* dPackPath,const char* dPackHash,CSimpleStringA &errMsg){
- bool isDownloadSucc = false;
- CSimpleStringA dPackPathTemp = CSimpleStringA::Format("%s%s",dPackPath,".tmp");//默认临时文件是.tmp后缀
- long dPackTempLen = 0;
- if(ExistsFileA(dPackPathTemp)){
- if(!m_fsm->GetFileLength(dPackPathTemp.GetData(),dPackTempLen)){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("%s get download temp pack fileLen is fail", dPackPathTemp.GetData()).GetData());
- errMsg = "get download temp pack fileLen is fail";
- return 4;//下载失败,计算临时文件长度失败
- }
- }
- byte* content = new byte[m_fsm->m_newEachDownloadLen];
- memset(content, 0, m_fsm->m_newEachDownloadLen);
- bool isContinue = true;
- while(isContinue){
- if(m_fsm->m_bTaskCancel){
- //任务取消
- delete[] content;
- return 3;
- }
- if(m_fsm->m_bDownloadIdle){
- //状态中断
- delete[] content;
- return 2;
- }
- HttpStruct::DownloadPackTaskRet resp;
- resp.bfinish= false;//默认是未下载完
- resp.sm3 = "";//默认是空串
- if(DownloadPackTaskImpl(client,dPackTempLen,content,resp)){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("download succ, %d , begin write %d",(int)resp.bfinish,dPackTempLen);
- //成功通讯
- if(!m_fsm->DownloadFileWrite(content,resp.content_length,dPackPathTemp)){
- 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());
- errMsg = "DownloadFileWrite write temp file fail";
- delete[] content;
- return 4;//下载失败,写文件失败
- }else{
- m_fsm->DownloadProgress(dPackTempLen+resp.content_length,resp.origin_file_length);//广播下载进度
- }
- if(resp.bfinish){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("最后一次下载");
- //最后一次
- CSimpleStringA strMD5Val;
- ErrorCodeEnum rc = m_fsm->SM3FileToStr(dPackPathTemp, strMD5Val,false);
- if (Error_Succeed != rc)
- {
- 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());
- errMsg = "get download temp pack sm3 fail";
- delete[] content;
- return 4;//下载失败,算hash失败
- }
- //不区分大小写比较文件hash
- #ifdef RVC_OS_WIN
- if(stricmp(strMD5Val.GetData(),resp.sm3.c_str())==0){
- #else
- if(strcmp(strMD5Val.GetData(),resp.sm3.c_str())==0){
- #endif
- //移动文件到正式目录
- if(ExistsFileA(dPackPath)){
- if(remove(dPackPath)==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete download old pack succ ", dPackPath);
- if(rename(dPackPathTemp.GetData(),dPackPath)!=0){
- #ifdef RVC_OS_WIN
- errMsg = CSimpleStringA::Format("exist old file,remove temp file fail, error=%d",(int)GetLastError()).GetData();
- #else
- errMsg = CSimpleStringA::Format("exist old file,remove temp file fail, error=%d", errno).GetData();
- #endif
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
- delete[] content;
- return 4;//下载失败,移动文件失败
- }else{
- delete[] content;
- return 1;//成功返回
- }
- }else{
- #ifdef RVC_OS_WIN
- errMsg = CSimpleStringA::Format("delete download old pack fail ,error:%d",(int)GetLastError()).GetData();
- #else
- errMsg = CSimpleStringA::Format("delete download old pack fail ,error:%d", errno).GetData();
- #endif
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
- delete[] content;
- return 4;//下载失败,删除旧文件失败
- }
- }else{
- if(rename(dPackPathTemp.GetData(),dPackPath)!=0){
- #ifdef RVC_OS_WIN
- errMsg = CSimpleStringA::Format("not exist old file,remove temp file fail, error=%d",(int)GetLastError()).GetData();
- #else
- errMsg = CSimpleStringA::Format("not exist old file,remove temp file fail, error=%d", errno).GetData();
- #endif
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,errMsg.GetData());
- delete[] content;
- return 4;//移动文件失败
- }else{
- delete[] content;
- return 1;//成功返回
- }
- }
- }else{
- errMsg = CSimpleStringA::Format("download file sm3 is not equal,local file [%s],resp [%s]",strMD5Val.GetData(),resp.sm3.c_str()).GetData();
- 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());
- //删除临时文件,重新下载
- if(remove(dPackPathTemp.GetData())==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete download temp pack succ ,%s", dPackPathTemp.GetData());
- }else{
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete download temp pack fail ,%s error:%d", dPackPathTemp.GetData(), GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete download temp pack fail ,%s error:%d", dPackPathTemp.GetData(), errno);
- #endif
- }
- delete[] content;
- return 4;//下载失败,hash不对
- }
- }else{
- if(resp.content_length==0){
- errMsg = "DownloadFile server content_length = 0 ,bfinish = false ,DownloadFile server return param fail";
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"DownloadFile server content_length = 0 ,bfinish = false ,DownloadFile server return param fail");
- delete[] content;
- return 4;//传回零字节,但是又未结束,下载失败,等待一段时间下载
- }
- //继续下一次续传
- dPackTempLen =dPackTempLen+resp.content_length;
- memset(content, 0, m_fsm->m_newEachDownloadLen);
- isContinue = true;
- }
- }else{
- delete[] content;
- return 0;//下载通讯失败,等待一段时间下载
- }
- }
- }
- bool DownloadPackTaskImpl(IHttpFunc* client,long downloaded_len,byte* respContent,HttpStruct::DownloadPackTaskRet &resp){
- //注意传入参数和传出参数进行转码
- CSystemStaticInfo info;
- ErrorCodeEnum rc = m_fsm->GetEntityBase()->GetFunction()->GetSystemStaticInfo(info);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadPackTask get CSystemStaticInfo fail");
- return false;//失败
- }
- Json::Value rootReq;
- Json::FastWriter writer;
- rootReq["terminal_no"] = info.strTerminalID.GetData();
- rootReq["pack_name"] = m_fsm->m_currentTask.pack_name.GetData();
- rootReq["downloaded_length"] = downloaded_len;
- rootReq["limit_length"] = m_fsm->m_newEachDownloadLen;
- rootReq["file_path"] = m_fsm->m_currentTask.file_path.GetData();
- string jsonReq = writer.write(rootReq);
- CSimpleStringA downloadUrl = m_fsm->m_currentTask.download_url;
- //转码
- m_fsm->ConvertGBKToUtf8(jsonReq);
- //打印发送请求
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("jsonStr is %s",jsonReq.c_str());
- }
- long httpCode =0;
- unordered_map<string, string> responseHeaders;
- int time_out = DOWNLOAD_TIMEOUT;
- fileContentArray content;
- content.copyPtr = respContent;
- content.maxLen = m_fsm->m_newEachDownloadLen;
- int retlen = 0;
- content.curLen = &retlen;
- if(!client->DownloadFileBlock(downloadUrl.GetData(),jsonReq.c_str(), content,httpCode,responseHeaders,time_out)){
- if (retlen > m_fsm->m_newEachDownloadLen) {
- CSimpleStringA errMsg = CSimpleStringA::Format("retlen is over limit_length ,retlen= %d", retlen).GetData();
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL, CSimpleStringA::Format("DownloadPackTask http req fail, %s, url=%s", errMsg.GetData(), downloadUrl.GetData()).GetData());
- }
- else {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL, CSimpleStringA::Format("DownloadPackTask http req fail,url=%s", downloadUrl.GetData()).GetData());
- }
- return false;//失败
- }
- //判断httpCode
- if(httpCode!=200){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("DownloadPackTask http req fail, url=%s, retHttpCode=%d",downloadUrl.GetData(),httpCode).GetData());
- return false;//失败
- }
- //解析head值
- unordered_map<string, string>::const_iterator iter = responseHeaders.find("Result");
- if(iter==responseHeaders.end()){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"resp head result is null");
- return false;//无params 失败
- }else{
- string respStr = iter->second;
- //转码:
- m_fsm->ConvertUtf8ToGBK(respStr);
- //打印回应报文
- if(m_fsm->m_PrintHttpLog){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("qTempRet Result=%s",respStr.c_str());
- }
- //解析json值
- Json::Reader reader;
- Json::Value rootRet;
- if (!reader.parse(respStr, rootRet, false))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,"DownloadPackTask head params parse resp is fail");
- return false;//解析失败
- }
- bool isSucc = rootRet["success"].asBool();
- if(isSucc){
- resp.content_length = (long)rootRet["content_length"].asInt();
- resp.origin_file_length = (long)rootRet["origin_file_length"].asInt();
- resp.bfinish = rootRet["finish"].asBool();//是否传送完毕
- resp.sm3 = rootRet["sm3"].asString();//包hash码
- return true;//查询成功
- }else{
- CSimpleStringA msg = rootRet["message"].asString().c_str();
- if(msg.IsNullOrEmpty()){
- msg = "";
- }
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_DOWNLOAD_PACK_FAIL,CSimpleStringA::Format("DownloadPackTask [success] is false, err=%s",msg.GetData()).GetData());
- return false;//查询失败
- }
- }
- }
- };
- //停止播放广告和提示音
- struct StopMediaPlayTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit StopMediaPlayTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //判断是否需要停止广播和提示音
- if(!m_fsm->m_currentTask.stop_media_play){
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(true));//返回处理结果
- }else{
- //停止广告、提示音播放
- // 终端置为升级状态。1:升级状态,0:非升级状态。处于升级状态时调用播放接口不生效
- ErrorCodeEnum rc = ((CUpgradeMgrEntity*)m_fsm->GetEntityBase())->NewStopMediaPlay();
- if(rc==Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("StopMediaPlayTask stop media play succ");
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("StopMediaPlayTask stop media play fail");
- //m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(false));//返回处理结果
- }
- // 终端置为升级状态。1:升级状态,0:非升级状态。处于升级状态时调用播放接口不生效
- rc = m_fsm->GetEntityBase()->GetFunction()->SetSysVar("UpdateState", "1", false);
- if(rc==Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("StopMediaPlayTask set UpdateState to 1 succ");
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("StopMediaPlayTask set UpdateState to 1 fail");
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(false));//返回处理结果
- return;
- }
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::StopMediaPlayTaskEvent(true));//返回处理结果
- }
- }
- };
- //解压安装包
- struct UnzipPackTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit UnzipPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //解压安装包
- bool isUnzipSucc;//是否解压成功
- if(m_fsm->UnzipPack(m_fsm->m_currentTask.pack_name.GetData())==Error_Succeed){
- isUnzipSucc = true;
- }else{
- isUnzipSucc = false;
- }
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::UnzipPackTaskEvent(isUnzipSucc));//返回处理结果
- }
- };
- //升级包安装
- struct InstallPackTask : public ITaskSp{
- CUpgradeTaskFSM* m_fsm;
- explicit InstallPackTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process(){
- LOG_FUNCTION();
- //升级包安装
- bool isInstallSucc=false;//是否安装成功
- int failStatus=0;//安装失败状态:0:失败,1:成功,-1:未知
- string packName = m_fsm->m_currentTask.pack_name.GetData();
- CSimpleStringA errMsg ="";
- if (!m_fsm->m_TempDepUpgradeFlag) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("======begin ExecInstall======");
- failStatus = m_fsm->ExecInstall(errMsg);
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("======begin dep ExecInstall======");
- failStatus = m_fsm->ExecDepInstall(errMsg);
- }
- if(failStatus == 1){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("======end ExecInstall:succ======");
- isInstallSucc =true;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("======end ExecInstall:fail======");
- isInstallSucc =false;
- }
- //清理临时解压包
- if(Error_Succeed==m_fsm->DeleteUnzipDir()){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DeleteUnzipDir succ");
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DeleteUnzipDir fail");
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("安装完成:failStatus=%d",failStatus);
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::InstallPackTaskEvent(isInstallSucc,errMsg,failStatus));//返回处理结果
- }
- };
- //回退版本检查
- struct RollBackCheckTask : public ITaskSp {
- CUpgradeTaskFSM* m_fsm;
- explicit RollBackCheckTask(CUpgradeTaskFSM* f) : m_fsm(f) {}
- void Process() {
- LOG_FUNCTION();
- //回退版本检查
- string failReason = "";
- CSimpleStringA strErrMsg = "";
- //判定是适配器or应用回退
- CSimpleStringA verDirName = m_fsm->m_currentTask.pack_version.GetData();
- if(m_fsm->judgeRollbackTaskClass(verDirName,failReason,strErrMsg)==Error_Succeed)
- {
- if (!m_fsm->m_TempDepUpgradeFlag) {
- //升级回退
- if (m_fsm->RollBackVersionCheck(failReason, strErrMsg) == Error_Succeed) {
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(true, "", ""));
- }
- else {
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(false, strErrMsg, failReason));
- }
- }
- else {
- //适配器回退
- if (m_fsm->RollBackDepVersionCheck(failReason, strErrMsg) == Error_Succeed) {
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(true, "", ""));
- }
- else {
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(false, strErrMsg, failReason));
- }
- }
- }else{
- m_fsm->PostEventFIFO(new CUpgradeTaskFSM::RollBackCheckTaskEvent(false, strErrMsg, failReason));
- }
- }
- };
- }
- //完成
- // 创建新版本目录,拷贝当前版本bin、cfg、dep、mod、imdep、res
- ErrorCodeEnum CUpgradeTaskFSM::CreateNewVersion(CVersion NewSoftwareVersion,CSimpleStringA &strErrInfo)
- {
- // 创建安装包日志文件
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version fail , get RootVer path is fail");
- strErrInfo = CSimpleStringA::Format("Create new version fail , get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strCurVerPath;
- rc = m_pEntity->GetFunction()->GetPath("Base",strCurVerPath);//获取当前version路径
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version fail , get Base path is fail");
- strErrInfo = CSimpleStringA::Format("Create new version fail , get Base path is fail");
- return Error_Bug;
- }
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), NewSoftwareVersion.ToString().GetData());
- //auto &v = cfg->install_ini->install_version;//获取当前版本
- //CVersion v;//获取当前版本
- CVersion curVersion(m_currentVersion.GetMajor(), m_currentVersion.GetMinor(), m_currentVersion.GetRevision(), m_currentVersion.GetBuild());
- if (curVersion == NewSoftwareVersion)
- {
- 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());
- strErrInfo = CSimpleStringA::Format("new ver [%s] equals current ver [%s]", NewSoftwareVersion.ToString().GetData(), curVersion.ToString().GetData());
- return Error_Bug;
- }
- if (ExistsDirA(strNewVerPath.GetData()))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new version dir [%s] already exist, delete it", strNewVerPath.GetData());
- if(!RemoveDirRecursiveA(strNewVerPath.GetData())){
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version fail, delete already exist new version is fail:%d",GetLastError());
- strErrInfo = CSimpleStringA::Format("Create new version fail, delete already exist new version is fail:%d",(int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version fail, delete already exist new version is fail:%d", errno);
- strErrInfo = CSimpleStringA::Format("Create new version fail, delete already exist new version is fail:%d", errno);
- #endif
- return Error_Bug;
- }
- }
- if (!CreateDirA(strNewVerPath.GetData(), TRUE))
- {
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version dir fail: %d", GetLastError());
- strErrInfo = CSimpleStringA::Format("create new version dir fail: %d", (int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new version dir fail: %d", errno);
- strErrInfo = CSimpleStringA::Format("create new version dir fail: %d", errno);
- #endif
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create new version dir succ, dir = %s",strNewVerPath.GetData());
- //增加错误信息字段,回传给上层应用
- CSimpleStringA strErrMsg ="";
- CSimpleStringA strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "bin", strCurVerPath.GetData());
- CSimpleStringA strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "bin", strNewVerPath.GetData());
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy bin dir fail");
- strErrInfo = CSimpleStringA::Format("copy bin dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy bin dir succ");
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "cfg", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "cfg", strNewVerPath.GetData());
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy cfg dir fail");
- strErrInfo = CSimpleStringA::Format("copy cfg dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy cfg dir succ");
- //strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strCurVerPath.GetData());
- //strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strNewVerPath.GetData());
- //if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- //{
- // DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
- // strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
- // return Error_Unexpect;
- //}
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "mod", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "mod", strNewVerPath.GetData());
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy mod dir fail");
- strErrInfo = CSimpleStringA::Format("copy mod dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy mod dir succ");
-
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strNewVerPath.GetData());
- // 检测dep目录是否存在
- if (ExistsDirA(strSource))
- {
- if (!RecursiveCopyDir(strSource, strDest, strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
- strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("dep dir is not exist,ignore copy");
- }
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "res", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "res", strNewVerPath.GetData());
- // 检测res目录是否存在
- if (ExistsDirA(strSource))
- {
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy res dir fail");
- strErrInfo = CSimpleStringA::Format("copy res dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy res dir succ");
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("res dir is not exist,ignore copy");
- }
- strSource = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "imdep", strCurVerPath.GetData());
- strDest = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "imdep", strNewVerPath.GetData());
- // 检测imdep目录是否存在
- if (ExistsDirA(strSource))
- {
- if (!RecursiveCopyDir(strSource, strDest,strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy imdep dir fail");
- strErrInfo = CSimpleStringA::Format("copy imdep dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy imdep dir succ");
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("imdep dir is not exist,ignore copy");
- }
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::ClearUpgradeFailVersion(CVersion NewSoftwareVersion)
- {
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion fail , get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), NewSoftwareVersion.ToString().GetData());
- if (ExistsDirA(strNewVerPath.GetData()))
- {
- if(!RemoveDirRecursiveA(strNewVerPath.GetData())){
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion fail, delete temp Version [%s] is fail:%d",strNewVerPath.GetData(),(int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), errno);
- #endif
- return Error_Bug;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion succ, delete temp Version [%s] ", strNewVerPath.GetData());
- return Error_Succeed;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailVersion succ, delete temp Version [%s] is not exsit ", strNewVerPath.GetData());
- return Error_Succeed;
- }
- }
- // result.log 文件内容: result=0&msg=install ok
- bool CUpgradeTaskFSM::GetSysUpgradeResult(const char *pszResultLog, CSimpleStringA &eErrorCode, CSimpleStringA &strErrMsg)
- {
- // 设置初始值
- //eErrorCode = Error_Succeed;
- strErrMsg = "";
- if (!ExistsFileA(pszResultLog))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult result log [%s] not exist", pszResultLog);
- strErrMsg = "result.log not exist";
- eErrorCode = "0";
- return true;//???有些外部程序不一定会产生日志文件,故默认不产生文件,认为是成功
- }
- FILE *pResultLog = fopen(pszResultLog, "r");
- if (pResultLog == NULL)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult open result log [%s] fail", pszResultLog);
- strErrMsg = "open result.log fail";
- return false;
- }
- char szTmp[4096] = {};
- int nRead = fread_s(szTmp, sizeof(szTmp), 1, sizeof(szTmp), pResultLog);
- CSimpleStringA strResult = szTmp;
- fclose(pResultLog);
- pResultLog = NULL;
- auto arr = strResult.Split('&');
- if(arr.GetCount()!=2){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetSysUpgradeResult read result log format fail,[%s]", strResult.GetData());
- strErrMsg = "read result.log format fail,eg result=0&msg=install ok";
- return false;
- }
- for (int i = 0; i < arr.GetCount(); i++)
- {
- auto arr2 = arr[i].Split('=');
- if (arr2.GetCount() == 2)
- {
- #ifdef RVC_OS_WIN
- if (stricmp(arr2[0], "result") == 0)
- eErrorCode = arr2[1];
- else if (stricmp(arr2[0], "msg") == 0)
- strErrMsg = arr2[1];
- #else
- if (strcmp(arr2[0], "result") == 0)
- eErrorCode = arr2[1];
- else if (strcmp(arr2[0], "msg") == 0)
- strErrMsg = arr2[1];
- #endif
- }
- }
- return true;
- }
- int CUpgradeTaskFSM::ExecInstall(CSimpleStringA &strErrMsg)
- {
- //判断是否需要生成新版本
- if(!m_currentTask.pack_version.IsNullOrEmpty()){
- CSimpleStringA strUpgradeVersion = m_currentTask.pack_version;
- CVersion latterVersion;//要更新到的版本号
- CVersion curVer = m_currentVersion;//当前版本号
- // 指定版本
- DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
- int n = sscanf(strUpgradeVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
- if (n != 4)
- {
- strErrMsg = CSimpleStringA::Format("指定升级版本号无效(%s)", strUpgradeVersion.GetData());
- LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_INSTALL_VERSION_FAIL, CSimpleStringA::Format("specified software version is invalid: [%s]", strUpgradeVersion.GetData()).GetData());
- return 0;
- }else{
- latterVersion = CVersion(dwMajor, dwMinor, dwRevision, dwBuild);
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("latterVersion :%s",latterVersion.ToString().GetData());
- if(curVer.ToString()==strUpgradeVersion){
- //版本号相同,
- strErrMsg = CSimpleStringA::Format("指定升级版本号与当前版本相同,无效(配置:%s, 当前:%s)", strUpgradeVersion.GetData(),curVer.ToString().GetData());
- return 0;
- //}else if(m_currentVersion.ToString().Compare(strUpgradeVersion)==1){
- //字符串比较版本号大小改为整形数字对比
- }else if(dwMajor < curVer.GetMajor()
- || (dwMajor == curVer.GetMajor() && dwMinor < curVer.GetMinor())
- || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision < curVer.GetRevision())
- || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision == curVer.GetRevision() && dwBuild < curVer.GetBuild())){
- //升级版本小于当前版本
- strErrMsg = CSimpleStringA::Format("指定升级版本号无效(配置:%s,解析:%s,当前:%s)", strUpgradeVersion.GetData(),latterVersion.ToString().GetData(),curVer.ToString().GetData());
- return 0;
- }
- //判断是否需要创建新版本
-
- CSimpleStringA strErrInfo = "";
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateNewVersion,version[%s],pack[%s]",strUpgradeVersion.GetData(),m_currentTask.pack_name.GetData());
- ErrorCodeEnum rc = CreateNewVersion(latterVersion,strErrInfo);
- if (rc != Error_Succeed)
- {
- strErrMsg = CSimpleStringA::Format("CreateNewVersion fail:%s",strErrInfo.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewVersion,version[%s] fail:%s",strUpgradeVersion.GetData(),strErrInfo.GetData());
- //清理临时版本文件夹
- ClearUpgradeFailVersion(latterVersion);
- return 0;
- }else{
- m_currentTask.NewVersion = strUpgradeVersion;//赋值升级版本号给内存变量
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewVersion,version[%s] succ",strUpgradeVersion.GetData());
- }
- }
- //循环执行安装命令
- int iRet=1;//默认是成功
- if(!m_currentTask.install_step.empty()){
-
- int iCount = m_currentTask.install_step.size();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d",iCount);
- for (int j = 0; j < iCount; j++){
- CInstallStep* tmp = m_currentTask.install_step.front();
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====begin cmd=[%s]=====",tmp->cmdType.GetData());
- //开始处理具体命令
- if(tmp->cmdType=="Delete"){
- bool ret = ExecDeleteCmd(strErrMsg,tmp);
- if(!ret){
- //报错才判断
- if(tmp->cmdFail == 0 ){
- iRet = 0;
- break;//出错直接退出
- }else if(tmp->cmdFail == 1 ){
- //继续
- }else{
- iRet = 0;
- break;//其他值也退出
- }
- }
- }else if(tmp->cmdType=="Copy"){
- bool ret = ExecCpoyCmd(strErrMsg,tmp);
- if(!ret){
- //报错才判断
- if(tmp->cmdFail == 0){
- iRet = 0;
- break;//出错直接退出
- }else if(tmp->cmdFail == 1){
- //继续
- }else{
- iRet = 0;
- break;//其他值也退出
- }
- }
- }else if(tmp->cmdType=="Run"){
- int retInt = ExecRunCmd(strErrMsg,tmp);
- if(retInt==0||retInt==-1){
- //报错才判断
- if(tmp->cmdFail == 0 ){
- iRet = retInt;//会有0,-1值
- break;//出错直接退出,并返回体系外结果
- }else if(tmp->cmdFail == 1 ){
- //继续
- }else{
- iRet = 0;
- break;//其他值也退出
- }
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cmd=[%s] is invalid",tmp->cmdType.GetData());
- iRet = 0;
- break;//命令无效直接退出
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====end cmd=[%s]=====",tmp->cmdType.GetData());
- m_currentTask.install_step.pop();//去除元素
- delete tmp;//删除内存
- }
- }
- return iRet;//返回处理结果
- }
- int CUpgradeTaskFSM::ExecRunCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
- {
- CSimpleStringA destPath ;//目的路径
- if(ins->dstPathType=="0"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(1,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }else if(ins->dstPathType=="1"){
- destPath = ins->dstPath;//绝对路径
- }else if(ins->dstPathType=="2"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(2,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }else if(ins->dstPathType=="3"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(3,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }else if(ins->dstPathType=="4"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(4,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级包相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 4 is fail");
- return false;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPathType is invalid %s",ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPathType is invalid %s",ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPath is %s",destPath.GetData());
- // ToRun=install.bat
- if (ExistsFileA(destPath.GetData()))
- {
- #ifdef RVC_OS_WIN
- // window模式下 如果是Wow64模式,需屏蔽System32重定向
- PVOID pRedirectOldValue(NULL);
- bool bIsWow64 = IsWow64Process();
- if (bIsWow64)
- {
- if (!Wow64DisableWow64FsRedirection(&pRedirectOldValue)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64DisableWow64FsRedirection fail: %d", GetLastError());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64DisableWow64FsRedirection succ");
- }
- }
- #endif
- //system(strSourcePath);
- string sysPathStr = destPath.GetData();
- CSimpleStringA err ="";
- int ret = system_on(sysPathStr,true,err);
- #ifdef RVC_OS_WIN
- // 如果是Wow64模式,恢复System32重定向
- if (bIsWow64)
- {
- if (!Wow64RevertWow64FsRedirection(pRedirectOldValue)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64RevertWow64FsRedirection fail: %d", GetLastError());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64RevertWow64FsRedirection succ");
- }
- }
- #endif
- if(ret!=0){
- //程序执行异常,结果未知
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown ,err=%s",err.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ,err=%s",err.GetData());
- #else
- DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown , ret=%d, err=%s",ret, strerror(errno));
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ret=%d, err=%s", ret, strerror(errno));
- #endif
- return -1;//未知结果返回
- }else{
- //进一步看返回结果文件判断是否成功
- CSimpleStringA strUnzipPath = GetFileDirectory(destPath.GetData());
- #ifdef RVC_OS_WIN
- CSimpleStringA strResultLog = strUnzipPath + "\\result.log";//结果文件
- #else
- CSimpleStringA strResultLog = strUnzipPath + "/result.log";//结果文件
- #endif
- CSimpleStringA eErrorCode = "";
- //获取结果文件
- if (!GetSysUpgradeResult(strResultLog, eErrorCode, strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, get result from result.log fail, %s", strErrMsg.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail ,get result from result.log fail, %s", strErrMsg.GetData());
- return 0;//失败
- }
- if (eErrorCode == "0")
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is succ,[%s] ", destPath.GetData());
- return 1;//成功
- }else{
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
- #else
- DbgWithLink(LOG_LEVEL_ERROR,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
- #endif
- return 0;//失败
- }
- }
- }
- else
- {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, run file [%s] is not Exist",destPath.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, run file [%s] is not Exist",destPath.GetData());
- return 0;//失败
- }
- }
- bool CUpgradeTaskFSM::ExecDeleteCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
- {
- //只删除同一层目录下的文件和文件夹
- CSimpleStringA destPath ;//目的路径+通配符
- if(ins->dstPathType=="0"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(1,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }else if(ins->dstPathType=="1"){
- destPath = ins->dstPath;//绝对路径
- }else if(ins->dstPathType=="2"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(2,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
-
- }else if(ins->dstPathType=="3"){
- CSimpleStringA rootPath;
- if(GetRootTypePath(3,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPathType is invalid %s",ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPathType is invalid %s",ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPath is %s",destPath.GetData());
- if(destPath.IndexOf("*")>0){
- CSimpleStringA strFileFilter = _GetFileName(destPath);
- CSimpleStringA strDestDir = destPath.SubString(0, destPath.GetLength()-strFileFilter.GetLength()-1);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match filter name [%s] in dir [%s]", strFileFilter.GetData(), strDestDir.GetData());
- // 删除所有匹配文件
- bool bRet = true;
- auto arr = fileutil_get_sub_files(strDestDir.GetData());
- if (arr != NULL)
- {
- for (int i = 0; i < arr->nelts; ++i)
- {
- char *file = ARRAY_IDX(arr, i, char*);
- if (IsFileMatch(strFileFilter, _GetFileName(file)))
- {
- if(RemoveFileA(file)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", file);
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", file);
- strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", file);
- bRet = false;
- break;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match file: [%s]", file);
- }
-
- }
- toolkit_array_free2(arr);
- if(!bRet){
- return bRet;
- }
- }
- // 删除所有匹配子目录
- auto subdirs = fileutil_get_sub_dirs(strDestDir.GetData());
- if (subdirs != NULL)
- {
- for (int i = 0; i < subdirs->nelts; ++i)
- {
- const char *dir = ARRAY_IDX(subdirs, i, char*);
- if (IsFileMatch(strFileFilter, _GetFileName(dir)))
- {
- if(RemoveDirRecursive(dir)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", dir);
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", dir);
- strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", dir);
- bRet = false;
- break;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match dir: [%s]", dir);
- }
- }
- toolkit_array_free2(subdirs);
- if(!bRet){
- return bRet;
- }
- }
- return bRet;
- }else{
- //直接删除文件
- bool bRet = true;
- if (ExistsFileA(destPath.GetData()))
- {
- if(RemoveFileA(destPath.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", destPath.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", destPath.GetData());
- strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", destPath.GetData());
- bRet = false;
- }
- return bRet;
- }
- else if (ExistsDirA(destPath.GetData()))
- {
- if(RemoveDirRecursiveA(destPath.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", destPath.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", destPath.GetData());
- strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", destPath.GetData());
- bRet = false;
- }
- return bRet;
- }
- else
- {
- //指定文件不再则忽略删除此文件
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file [%s] not exists,ignore delete file", destPath.GetData());
- return bRet;
- }
- }
- }
- bool CUpgradeTaskFSM::ExecCpoyCmd(CSimpleStringA &strErrMsg,CInstallStep* ins)
- {
- CSimpleStringA sourcePath ;//路径+通配符
- if(ins->srcPathType=="0"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(1,rootPath)){
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 1 is fail");
- return false;
- }
- }else if(ins->srcPathType=="1"){
- sourcePath = ins->srcPath;//绝对路径
- }else if(ins->srcPathType=="2"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(2,rootPath)){
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//当前版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 2 is fail");
- return false;
- }
- }else if(ins->srcPathType=="3"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(4,rootPath)){
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->srcPath.GetData());//升级包相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 4 is fail");
- return false;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd srcPathType is invalid %s",ins->srcPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd srcPathType is invalid %s",ins->srcPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd sourcePath is %s",sourcePath.GetData());
- CSimpleStringA destPath ;//目的路径文件夹
- if(ins->dstPathType=="0"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(1,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }else if(ins->dstPathType=="1"){
- destPath = ins->dstPath;//绝对路径
- }else if(ins->dstPathType=="2"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(2,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//当前版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }else if(ins->dstPathType=="3"){
- CSimpleStringA rootPath="";
- if(GetRootTypePath(3,rootPath)){
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),ins->dstPath.GetData());//升级版本相对路径
- }else{
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- //}else if(ins->dstPathType=="4"){
- // CSimpleStringA rootPath="";
- // if(GetRootTypePath(4,rootPath)){
- // destPath = CSimpleStringA::Format("%s\\%s",rootPath.GetData(),ins->dstPath.GetData());//升级包相对路径
- // }else{
- // strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 4 is fail");
- // return false;
- // }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd dstPathType is invalid %s",ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd dstPathType is invalid %s",ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd destPath is %s",destPath.GetData());
- if(sourcePath.IndexOf("*")>0){
- //循环匹配拷贝
- //找到要扫描的文件夹
- CSimpleStringA strFileDir = GetFileDirectory(sourcePath.GetData());
- //过滤通配条件
- CSimpleStringA strFileFilter = _GetFileName(sourcePath.GetData());
- list<CSimpleStringA> fileList;
- //获取所有根文件夹下的文件相对路径:如mod\test.dll
- RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find fileList =%d",fileList.size());
- if(fileList.size()==0){
- //判断mod文件夹未空则报错
- if(sourcePath.IndexOf("mod")!=-1){
- LogWarn(Severity_Low, Error_Exception, WARN_TASK_COPY_FILE_ZERO,CSimpleStringA::Format("ExecCpoyCmd sourcePath is [%s] file is 0",sourcePath.GetData()));
- }
- }
- for(auto it = fileList.begin(); it != fileList.end(); it++)
- {
- if (IsFileMatch(strFileFilter, _GetFileName((const char*)(*it))))
- {
- CSimpleStringA strSrcName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", GetFileDirectory(sourcePath.GetData()).GetData(), (const char*)(*it));//源文件路径
- CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(),(const char*)(*it));//目标文件路径
- //匹配成功,开始拷贝文件
- CSimpleStringA errMsg = "";
- ErrorCodeEnum rc = CopyFileOperate(strSrcName.GetData(),strDestName.GetData(),3,errMsg);
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] to [%s] %s", strSrcName.GetData(),strDestName.GetData(), rc == Error_Succeed ? "succeed" : "fail");
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail: %s",strSrcName.GetData(),errMsg.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail: %s",strSrcName.GetData(),errMsg.GetData());
- return false;//报错
- }
- }
- }
-
- }else{
- //直接拷贝文件:考虑有些文件因智能对比不一定下发,故如果文件不存在,则默认忽略此策略
- CSimpleStringA errMsg = "";
- CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), _GetFileName(sourcePath.GetData()));
- if(ExistsFileA(sourcePath.GetData())){
- ErrorCodeEnum rc = CopyFileOperate(sourcePath.GetData(),strDestName.GetData(),3,errMsg);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:%s",sourcePath.GetData(),errMsg.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail:%s",sourcePath.GetData(),errMsg.GetData());
- return false;//报错
- }
- }else{
- if(ins->srcPathType=="3"){
- //升级包因智能升级不一定有指定的文件存在
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("拷贝指定的文件[%s]不存在,因智能升级对比过滤,故忽略此文件拷贝",sourcePath.GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:file to copy not exist",sourcePath.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail:file to copy not exist",sourcePath.GetData());
- return false;//报错
- }
-
- }
- }
- return true;
- }
- bool CUpgradeTaskFSM::GetRootTypePath(int rootType,CSimpleStringA &Path)
- {
- CSimpleStringA tempPath;
- if (rootType == 1) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Root", tempPath);//例如:C:\Run /opt/Run
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- string runPathStr = tempPath.GetData();
- int pos = runPathStr.find_last_of(SPLIT_SLASH);
- Path = runPathStr.substr(0, pos).c_str();
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is error");
- return false;
- }
- }
- else if (rootType == 2) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Base", tempPath);//例如:C:\Run\version\4.8.1.1 /opt/Run/version/4.8.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- Path = tempPath;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currVer path is error");
- return false;
- }
- }
- else if (rootType == 3) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", tempPath);//例如:C:\Run\version\4.9.1.1 /opt/Run/version/4.9.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradeVer path is error");
- return false;
- }
- }
- else if (rootType == 4) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Downloads", tempPath);//例如:C:\rvc\Downloads\4.8.1.1 /opt/rvc/Downloads/4.8.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- CSimpleStringA strUnzipDir;
- strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_name.GetData());
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")) {
- Path = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
- }
- else {
- Path = strUnzipDir;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is error");
- return false;
- }
- }
- return true;
- }
- ErrorCodeEnum CUpgradeTaskFSM::CopyFileOperate(const char* srcPath, const char* destPath, int nCopyMode, CSimpleStringA &strErrMsg)
- {
- //源文件是否存在
- if (!ExistsFileA(srcPath))
- {
- strErrMsg = CSimpleStringA::Format("CopyFileOperate file [%s] to copy not exist", srcPath);
- return Error_NotExist;
- }
- //目标文件夹是否存在
- CSimpleStringA strDestDir = GetFileDirectory(destPath);
- if (!ExistsDirA(strDestDir.GetData())){
- if(!CreateDirA(strDestDir.GetData(), TRUE)){
- strErrMsg = CSimpleStringA::Format("CopyFileOperate create strDestDir[%s] fail", strDestDir.GetData());
- return Error_Exception;
- }
- }
- //目标文件是否存在
- BOOL bDestFileExists = ExistsFileA(destPath);
- if (bDestFileExists){
- RemoveFileReadOnlyAttributeA(destPath);
- }
- BOOL bRet = TRUE;
- switch (nCopyMode)
- {
- case 1:
- {
- if (bDestFileExists) {
- #ifdef RVC_OS_WIN
- bRet = CopyFileA(srcPath, destPath, FALSE);
- #else
- if (fileutil_copy_file(destPath, srcPath) == 0) {
- bRet = TRUE;
- }
- else {
- bRet = FALSE;
- }
- #endif
- }
- else {
- LOG_TRACE("ignore file [%s] copy for dest file not exists", srcPath);
- }
- }
- break;
- case 2:
- {
- if (!bDestFileExists)
- #ifdef RVC_OS_WIN
- bRet = CopyFileA(srcPath, destPath, TRUE);
- #else
- if (fileutil_copy_file(destPath, srcPath) == 0) {
- bRet = TRUE;
- }
- else {
- bRet = FALSE;
- }
- #endif
- else
- LOG_TRACE("ignore file [%s] copy for dest file exists", srcPath);
- }
- break;
- case 3:
- #ifdef RVC_OS_WIN
- bRet = CopyFileA(srcPath, destPath, FALSE);
- #else
- if (fileutil_copy_file(destPath, srcPath) == 0) {
- bRet = TRUE;
- }
- else {
- bRet = FALSE;
- }
- #endif
- break;
- case 4:
- {
- // 不发生拷贝,只进行判断
- if(bDestFileExists)
- LOG_TRACE("file [%s] exist", srcPath);
- else
- LOG_TRACE("file [%s] not exist", srcPath);
- }
- break;
- }
- if (bRet){
- RemoveFileReadOnlyAttributeA(destPath);
- }else{
- #ifdef RVC_OS_WIN
- strErrMsg = CSimpleStringA::Format("CopyFileOperate copy file fail:%d", GetLastError());
- #else
- strErrMsg = CSimpleStringA::Format("CopyFileOperate copy file fail:%d", errno);
- #endif
- }
- ErrorCodeEnum rc = bRet ? Error_Succeed : Error_Unexpect;
- return rc;
- }
- ErrorCodeEnum CUpgradeTaskFSM::SetRunSucceed(const char* pPackFile)
- {
- // 拷贝升级包到Upgraded目录
- CSimpleStringA strDownloadPath, strUpgradedPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadPath);
- if(rc!=Error_Succeed){
- return rc;
- }
- rc = m_pEntity->GetFunction()->GetPath("Upgraded", strUpgradedPath);
- if(rc!=Error_Succeed){
- return rc;
- }
- CSimpleStringA strSourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strDownloadPath, pPackFile);
- CSimpleStringA strDestPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", (const char*)strUpgradedPath, pPackFile);
- #ifdef RVC_OS_WIN
- CopyFileA(strSourcePath.GetData(), strDestPath.GetData(), FALSE);
- #else
- fileutil_copy_file(strDestPath.GetData(), strSourcePath.GetData());
- #endif
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::UpgradeToNewVersion()
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin UpgradeToNewVersion");
- //获取新版本号
- if(m_currentTask.NewVersion.IsNullOrEmpty()){
- if(m_currentTask.pack_version.IsNullOrEmpty()){
- return Error_Succeed;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("NewVersion is null, pack_version=[%s] is not null,UpgradeToNewVersion fail, taskID=[%s]",m_currentTask.pack_version.GetData(), m_currentTask.upgradeTaskId.GetData());
- 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());
- return Error_Unexpect;//这种情况有问题,需要清除此任务
- }
- }else{
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpgradeToNewVersion fail , get RootVer path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,"UpgradeToNewVersion: get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.NewVersion.GetData());
- if(!ExistsDirA(strNewVerPath.GetData())){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, strNewVerPath =%s is not exist,fail",strNewVerPath.GetData()).GetData());
- return Error_Unexpect;//这种情况有问题,需要清除此任务
- }
- //修改运行时文件
- //修改active配置
- CSimpleStringA strActiveFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "active.txt", rootVerPath.GetData());
- if(!ExistsFileA(strActiveFile.GetData())){
- //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail,active file is not exist");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,"UpgradeToNewVersion fail, active file is not exist");
- return Error_Unexpect;
- }
- //先做active文件备份,后面写入失败再copy回去
- #ifdef RVC_OS_WIN
- bool backupSucc = true;
- CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\back_active.txt", rootVerPath.GetData());
- if(!CopyFileA(strActiveFile.GetData(),strBackupActiveFile.GetData(),FALSE)){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, back up active.txt fail, err=%d",(int)GetLastError()).GetData());
- backupSucc = false;
- }
- FILE* fp = fopen(strActiveFile.GetData(),"wb+");
- if(fp==NULL){
- //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open write active.txt fail, err=%d",(int)GetLastError()).GetData());
- return Error_Unexpect;
- }
- int ret = fwrite(m_currentTask.NewVersion.GetData(),m_currentTask.NewVersion.GetLength(),1,fp);
- if(ret!=1){
- //LogError(Severity_Low, Error_Unexpect, 0, "write active.txt fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, write active.txt fail, err=%d",(int)GetLastError()).GetData());
- fclose(fp);
- if(backupSucc){
- if(CopyFileA(strBackupActiveFile.GetData(),strActiveFile.GetData(),FALSE)){
- RemoveFileA(strBackupActiveFile.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("back_active.txt copy to active.txt is succ");
- }else{
- 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());
- }
- }
- return Error_Unexpect;
- }else{
- fflush(fp);
- fclose(fp);
- if (ExistsFileA(strBackupActiveFile.GetData())) {
- RemoveFileA(strBackupActiveFile.GetData());
- }
- }
- //重新读active文件,看文件内容是什么
- fp = fopen(strActiveFile.GetData(),"rb");
- if(fp==NULL){
- //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open read active.txt fail, err=%d",(int)GetLastError()).GetData());
- return Error_Unexpect;
- }
- char cVer[16] = {0};
- int re = fread(cVer,m_currentTask.NewVersion.GetLength(),1,fp);
- if(re!=1){
- //LogError(Severity_Low, Error_Unexpect, 0, "Read active.txt fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, read active.txt fail, err=%d",(int)GetLastError()).GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read active.txt, version[%s]", cVer);
- }
- fclose(fp);
- return Error_Succeed;
- #else
- bool backupSucc = true;
- CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\back_active.txt", rootVerPath.GetData());
- if (fileutil_copy_file( strBackupActiveFile.GetData(),strActiveFile.GetData())!=0) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, back up active.txt fail, err=%d", errno).GetData());
- backupSucc = false;
- }
- FILE* fp = fopen(strActiveFile.GetData(),"wb+");
- if(fp==NULL){
- //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, open write active.txt fail, err=%d", errno).GetData());
- return Error_Unexpect;
- }
- int ret = fwrite(m_currentTask.NewVersion.GetData(),m_currentTask.NewVersion.GetLength(),1,fp);
- if(ret!=1){
- //LogError(Severity_Low, Error_Unexpect, 0, "write active.txt fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion fail, write active.txt fail, err=%d", errno).GetData());
- fclose(fp);
- if (backupSucc) {
- if (fileutil_copy_file(strActiveFile.GetData(), strBackupActiveFile.GetData())==0) {
- RemoveFileA(strBackupActiveFile.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("back_active.txt copy to active.txt is succ");
- }else{
- 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());
- }
- }
- return Error_Unexpect;
- }else{
- fflush(fp);
- fclose(fp);
- if (ExistsFileA(strBackupActiveFile.GetData())) {
- RemoveFileA(strBackupActiveFile.GetData());
- }
- }
- //重新读active文件,看文件内容是什么
- fp = fopen(strActiveFile.GetData(),"rb");
- if(fp==NULL){
- //LogError(Severity_Low, Error_Unexpect, 0, "open active.txt fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, open read active.txt fail, err=%d", errno).GetData());
- return Error_Unexpect;
- }
- char cVer[16] = {0};
- int re = fread(cVer,m_currentTask.NewVersion.GetLength(),1,fp);
- if(re!=1){
- //LogError(Severity_Low, Error_Unexpect, 0, "Read active.txt fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL,CSimpleStringA::Format("UpgradeToNewVersion fail, read active.txt fail, err=%d", errno).GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read active.txt, version[%s]", cVer);
- }
- fclose(fp);
- return Error_Succeed;
- #endif
- }
-
- }
- ErrorCodeEnum CUpgradeTaskFSM::RollBackToHistoryVersion(CVersion historyVersion)
- {
- // 判断目标版本是否小于当前版本
- CVersion v=m_currentVersion;//当前版本
- CVersion curVersion(v.GetMajor(), v.GetMinor(), v.GetRevision(), v.GetBuild());
- if (curVersion <= historyVersion)
- {
- 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());
- return Error_Param;
- }
- // 检查对应文件夹是否存在
- CSimpleStringA strHisVersion = historyVersion.ToString();
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer",rootVerPath);//获取version根路径
- if(rc!=Error_Succeed){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryVersion fail , get RootVer path is fail");
- return Error_Bug;
- }
- CSimpleStringA strHisVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), strHisVersion.GetData());
- if (!ExistsDirA(strHisVerPath.GetData()))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryVersion fail, history version dir [%s] not exists", strHisVerPath.GetData()).GetData());
- return Error_NotExist;
- }
- //删除当时的运行缓存值
- // 修改active.txt文件,可能存在失败
- CSimpleStringA strActiveFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "active.txt", rootVerPath.GetData());
- if(!ExistsFileA(strActiveFile.GetData())){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryVersion fail, active file is not exist");
- return Error_Unexpect;
- }
- //先做active文件备份,后面写入失败再copy回去
- #ifdef RVC_OS_WIN
- bool backupSucc = true;
- CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\Rollback_active.txt", rootVerPath.GetData());
- if(!CopyFileA(strActiveFile.GetData(),strBackupActiveFile.GetData(),FALSE)){
- 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());
- backupSucc = false;
- }
- FILE* fp = fopen(strActiveFile.GetData(),"wb+");
- if(fp==NULL){
- 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());
- return Error_Unexpect;
- }
- int ret = fwrite(strHisVersion.GetData(),strHisVersion.GetLength(),1,fp);
- if(ret!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, write active.txt fail,err=%d", (int)GetLastError()).GetData());
- fclose(fp);
- if(backupSucc){
- if(CopyFileA(strBackupActiveFile.GetData(),strActiveFile.GetData(),FALSE)){
- RemoveFileA(strBackupActiveFile.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Rollback_active.txt copy to active.txt is succ");
- }else{
- 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());
- }
- }
- return Error_Unexpect;
- }else{
- fflush(fp);
- fclose(fp);
- if (ExistsFileA(strBackupActiveFile.GetData())) {
- RemoveFileA(strBackupActiveFile.GetData());
- }
- }
- //重新读active文件,看文件内容是什么
- fp = fopen(strActiveFile.GetData(),"rb");
- if(fp==NULL){
- 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());
- return Error_Unexpect;
- }
- char cVer[16] = {0};
- int re = fread(cVer,strHisVersion.GetLength(),1,fp);
- if(re!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Read active.txt fail,err=%d", (int)GetLastError()).GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read active.txt, version[%s]", cVer);
- }
- fclose(fp);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set rollback to history version [%s] succeed", (const char*)strHisVersion);
- return Error_Succeed;
- #else
- bool backupSucc = true;
- CSimpleStringA strBackupActiveFile = CSimpleStringA::Format("%s\\Rollback_active.txt", rootVerPath.GetData());
- if (fileutil_copy_file(strBackupActiveFile.GetData(), strActiveFile.GetData())!=0) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, back up active.txt fail, err=%d", errno).GetData());
- backupSucc = false;
- }
- FILE* fp = fopen(strActiveFile.GetData(),"wb+");
- if(fp==NULL){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open write active.txt fail,err=%d", errno).GetData());
- return Error_Unexpect;
- }
- int ret = fwrite(strHisVersion.GetData(),strHisVersion.GetLength(),1,fp);
- if(ret!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, write active.txt fail,err=%d", errno).GetData());
- fclose(fp);
- if (backupSucc) {
- if (fileutil_copy_file(strActiveFile.GetData(), strBackupActiveFile.GetData())==0) {
- RemoveFileA(strBackupActiveFile.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Rollback_active.txt copy to active.txt is succ");
- }else{
- 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());
- }
- }
- return Error_Unexpect;
- }else{
- fflush(fp);
- fclose(fp);
- if (ExistsFileA(strBackupActiveFile.GetData())) {
- RemoveFileA(strBackupActiveFile.GetData());
- }
- }
- //重新读active文件,看文件内容是什么
- fp = fopen(strActiveFile.GetData(),"rb");
- if(fp==NULL){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, open read active.txt fail,err=%d", errno).GetData());
- return Error_Unexpect;
- }
- char cVer[16] = {0};
- int re = fread(cVer,strHisVersion.GetLength(),1,fp);
- if(re!=1){
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RRollBackToHistoryVersion fail, Read active.txt fail,err=%d", errno).GetData());
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("read active.txt, version[%s]", cVer);
- }
- fclose(fp);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("set rollback to history version [%s] succeed", (const char*)strHisVersion);
- return Error_Succeed;
- #endif
- }
- void CUpgradeTaskFSM::RecursiveGetSubFiles(const char *pszDir, const char *pszTrimStart, list<CSimpleStringA>& retList)
- {
- if (!ExistsDirA(pszDir))
- return;
- auto arr = fileutil_get_sub_files(pszDir);
- if (arr != NULL)
- {
- for (int i = 0; i < arr->nelts; ++i)
- {
- char *file = ARRAY_IDX(arr, i, char*);
- #ifdef RVC_OS_WIN
- //不区分大小写
- if (pszTrimStart != NULL && strnicmp(file, pszTrimStart, strlen(pszTrimStart))==0) {
- #else
- //区分大小写
- if (pszTrimStart != NULL && strncmp(file, pszTrimStart, strlen(pszTrimStart)) == 0) {
- #endif
- file += strlen(pszTrimStart);
- if (*file == SPLIT_SLASH)
- file++;
- }
- retList.push_back(file);
- }
- toolkit_array_free2(arr);
- }
- arr = fileutil_get_sub_dirs(pszDir);
- if (arr != NULL)
- {
- for (int i = 0; i < arr->nelts; ++i)
- {
- char *dir = ARRAY_IDX(arr, i, char*);
- RecursiveGetSubFiles(dir, pszTrimStart, retList);
- }
- toolkit_array_free2(arr);
- }
- }
- bool CUpgradeTaskFSM::IsFileMatch(const char *pszFilter, const char *pszFileName)
- {
- const char *p1 = pszFilter;
- const char *p2 = pszFileName;
- if (p1 == NULL)
- return true;
- if (p2 == NULL)
- return false;
- if (*p1 ==NULL && *p2 ==NULL)
- return true;
- else if (*p1 == NULL)
- return false;
- else if (*p2 == NULL)
- {
- // 查找*p1是否全是*
- while(*p1 == '*')
- p1++;
- if (*p1 == NULL)
- return true;
- else
- return false;
- }
- if (*p1 != '*')
- {
- if (tolower(*p1) != tolower(*p2))
- return false;
- else
- return IsFileMatch(p1+1, p2+1);
- }
- else
- {
- while(*++p1 == '*');
- if (*p1 == NULL)
- return true;
- while (*p2)
- {
- while(tolower(*p1) != tolower(*p2) && *++p2);
- if (*p2 == NULL)
- return false;
- if(IsFileMatch(p1+1, p2+1))
- return true;
- p2++;
- }
- return false;
- }
- }
- bool CUpgradeTaskFSM::RecursiveCopyDir(const char *pszSourceDir, const char *pszDestDir,CSimpleStringA &strErrInfo)
- {
- array_header_t *arr;
- #ifdef RVC_OS_WIN
- if (!ExistsDirA(pszSourceDir))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("source dir [%s] not exists: %d", pszSourceDir,GetLastError());
- strErrInfo = CSimpleStringA::Format("source dir [%s] not exists: %d", pszSourceDir, GetLastError());
- return false;
- }
- if (!ExistsDirA(pszDestDir))
- {
- if (!CreateDirRecursiveA(pszDestDir))
- {
- strErrInfo = CSimpleStringA::Format("create dir [%s] fail: %d", pszDestDir, GetLastError());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("create dir fail: %s",strErrInfo.GetData());
- return false;
- }
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("create dir [%s] succ", pszDestDir);
- }
- #else
- if (!ExistsDirA(pszSourceDir))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("source dir [%s] not exists: %d", pszSourceDir, errno);
- strErrInfo = CSimpleStringA::Format("source dir [%s] not exists: %d", pszSourceDir, errno);
- return false;
- }
- if (!ExistsDirA(pszDestDir))
- {
- if (!CreateDirRecursiveA(pszDestDir))
- {
- strErrInfo = CSimpleStringA::Format("create dir [%s] fail: %d", pszDestDir, errno);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("create dir fail: %s",strErrInfo.GetData());
- return false;
- }
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("create dir [%s] succ", pszDestDir);
- }
- #endif
- arr = fileutil_get_sub_files_a(pszSourceDir);
- if (arr)
- {
- int i;
- for (i = 0; i < arr->nelts; ++i)
- {
- char szDestFile[256] = { 0 };
- char *file = ARRAY_IDX(arr, i, char*);
- strcpy(szDestFile, pszDestDir);
- if (szDestFile[strlen(szDestFile) - 1] != SPLIT_SLASH)
- strcat(szDestFile, SPLIT_SLASH_STR);
- strcat(szDestFile, strrchr(file, SPLIT_SLASH) + 1);
- #ifdef RVC_OS_WIN
- if (!CopyFileA(file, szDestFile, FALSE))
- {
- strErrInfo = CSimpleStringA::Format("copy file [%s] fail: %d", file, GetLastError());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy file fail:%s",strErrInfo.GetData());
- toolkit_array_free2(arr);
- return false;
- }
- #else
- if (fileutil_copy_file(szDestFile, file)!=0)
- {
- strErrInfo = CSimpleStringA::Format("copy file [%s] fail: %d", file, errno);
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy file fail:%s",strErrInfo.GetData());
- toolkit_array_free2(arr);
- return false;
- }
- #endif
- }
- toolkit_array_free2(arr);
- }
- arr = fileutil_get_sub_dirs_a(pszSourceDir);
- if (arr)
- {
- int i;
- for (i = 0; i < arr->nelts; ++i)
- {
- char szDestSubDir[256] = { 0 };
- char *dir = ARRAY_IDX(arr, i, char*);
- strcpy(szDestSubDir, pszDestDir);
- if (szDestSubDir[strlen(szDestSubDir) - 1] != SPLIT_SLASH)
- strcat(szDestSubDir, SPLIT_SLASH_STR);
- strcat(szDestSubDir, strrchr(dir, SPLIT_SLASH) + 1);
- if (!RecursiveCopyDir(dir, szDestSubDir,strErrInfo))
- {
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy dir [%s] fail: %d", dir, GetLastError());
- if(strErrInfo.IsNullOrEmpty()){
- strErrInfo = CSimpleStringA::Format("copy dir [%s] fail: %d", dir, GetLastError());
- }
- toolkit_array_free2(arr);
- return false;
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy dir [%s] fail: %d", dir, errno);
- if (strErrInfo.IsNullOrEmpty()) {
- strErrInfo = CSimpleStringA::Format("copy dir [%s] fail: %d", dir, errno);
- }
- toolkit_array_free2(arr);
- return false;
- #endif
- }
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("copy dir [%s] succ", dir);
- }
- toolkit_array_free2(arr);
- }
- return true;
- }
- CSimpleStringA CUpgradeTaskFSM::GetFileDirectory(const char *pszFullPath)
- {
- int i=strlen(pszFullPath)-1;
- for( ; i>0 && pszFullPath[i]!= SPLIT_SLASH; i--)NULL;
- return CSimpleStringA(pszFullPath, i);
- }
- bool CUpgradeTaskFSM::IsWow64Process()
- {
- #ifdef RVC_OS_WIN
- typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
- LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
- BOOL bIsWow64 = FALSE;
- if (NULL != fnIsWow64Process)
- {
- if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("call IsWow64Process error: %d", GetLastError());
- return false;
- }
- return bIsWow64 == TRUE;
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get IsWow64Process error: %d", GetLastError());
- return false;
- }
- #endif
- return true;
- }
- int CUpgradeTaskFSM::system_on(string cmdFilePath, bool isWait,CSimpleStringA &errMsg)
- {
- #ifdef RVC_OS_WIN
- string cmdLine = "cmd /c ";
- cmdLine.append(cmdFilePath.c_str());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("exec bat %s",cmdLine.c_str());
- return waitSystem("cmd.exe", cmdLine.c_str(), true, errMsg);
- #else
- //linux直接用system函数即可
- return system(cmdFilePath.c_str());
- #endif
- }
- //返回值是0则正常执行,其他都是非正常未知状态
- int CUpgradeTaskFSM::waitSystem(string cmd, const char * par, bool nShow,CSimpleStringA &errMsg)
- {
- #ifdef RVC_OS_WIN
- SHELLEXECUTEINFOA ShExecInfo = { 0 };
- ShExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
- ShExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
- ShExecInfo.hwnd = NULL;
- ShExecInfo.lpVerb = NULL;
- ShExecInfo.lpFile = cmd.c_str(); //调用的程序名
- ShExecInfo.lpParameters = par; //调用程序的命令行参数
- ShExecInfo.lpDirectory = NULL;
- ShExecInfo.nShow = nShow ? SW_MINIMIZE: SW_HIDE; //窗口状态为隐藏
- ShExecInfo.hInstApp = NULL;
- if (!ShellExecuteEx(&ShExecInfo))
- {
- errMsg = CSimpleStringA::Format("shellExecute is fail :%d",GetLastError());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is fail :%s",errMsg.GetData());
- return -1;
- }
- //等到该进程结束,如果5分钟没结束,强行杀死进程
- if (WaitForSingleObject(ShExecInfo.hProcess, 5*60*1000) == WAIT_TIMEOUT)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is time out");
- errMsg = CSimpleStringA::Format("shellExecute is time out");
- if (TerminateProcess(ShExecInfo.hProcess, 0))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminateProcess is succ");
- }else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("TerminateProcess is fail :%d",GetLastError());
- }
- if (CloseHandle(ShExecInfo.hProcess))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is succ");
- }else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is fail");
- }
- return -1;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute is succ");
- DWORD exitCode = 0;
- if (!GetExitCodeProcess(ShExecInfo.hProcess, &exitCode))
- {
- errMsg = CSimpleStringA::Format("GetExitCodeProcess is fail:%d",GetLastError());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetExitCodeProcess is fail:%s",errMsg.GetData());
- return -1;
- }
- if (CloseHandle(ShExecInfo.hProcess))
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is succ");
- }else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("shellExecute CloseHandle is fail");
- }
- if(exitCode!=0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetExitCodeProcess ret exitCode=%d",(int)exitCode);
- errMsg = CSimpleStringA::Format("GetExitCodeProcess ret exitCode=%d",(int)exitCode);
- }
- return exitCode;
- #else
- return 0;
- #endif
- }
- char* CUpgradeTaskFSM::ConvertUtf8ToGBK(const char* strUtf8)
- {
- int len = MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, NULL, 0);
- WCHAR* wszGBK = new WCHAR[len + 1];
- memset(wszGBK, 0, len * 2 + 2);
- MultiByteToWideChar(CP_UTF8, 0, strUtf8, -1, wszGBK, len);
- len = WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, NULL, 0, NULL, NULL);
- char* szGBK = new char[len + 1];
- memset(szGBK, 0, len + 1);
- WideCharToMultiByte(CP_ACP, 0, wszGBK, -1, szGBK, len, NULL, NULL);
- delete[] wszGBK;
- return szGBK;
- }
- void CUpgradeTaskFSM::ConvertUtf8ToGBK(std::string &str)
- {
- char *dst = ConvertUtf8ToGBK(str.c_str());
- str = dst;
- delete[] dst;
- }
- char* CUpgradeTaskFSM::ConvertGBKToUtf8(const char* gbk, int *n)
- {
- int len = MultiByteToWideChar(CP_ACP, 0, gbk, -1, NULL, 0);
- WCHAR* wszGBK = new WCHAR[len + 1];
- memset(wszGBK, 0, len * 2 + 2);
- MultiByteToWideChar(CP_ACP, 0, gbk, -1, wszGBK, len);
- len = WideCharToMultiByte(CP_UTF8, 0, wszGBK, -1, NULL, 0, NULL, NULL);
- char* szUtf8 = new char[len + 1];
- memset(szUtf8, 0, len + 1);
- WideCharToMultiByte(CP_UTF8, 0, wszGBK, -1, szUtf8, len, NULL, NULL);
- delete[] wszGBK;
- *n = len - 1;
- return szUtf8;
- }
- void CUpgradeTaskFSM::ConvertGBKToUtf8(std::string &str)
- {
- int len = 0;
- char *dst = ConvertGBKToUtf8(str.c_str(), &len);
- str = dst;
- delete[] dst;
- }
- bool CUpgradeTaskFSM::is_str_utf8(const char* str)
- {
- unsigned int nBytes = 0;//UFT8可用1-6个字节编码,ASCII用一个字节
- unsigned char chr = *str;
- bool bAllAscii = true;
- for (unsigned int i = 0; str[i] != '\0'; ++i) {
- chr = *(str + i);
- //判断是否ASCII编码,如果不是,说明有可能是UTF8,ASCII用7位编码,最高位标记为0,0xxxxxxx
- if (nBytes == 0 && (chr & 0x80) != 0) {
- bAllAscii = false;
- }
- if (nBytes == 0) {
- //如果不是ASCII码,应该是多字节符,计算字节数
- if (chr >= 0x80) {
- if (chr >= 0xFC && chr <= 0xFD) {
- nBytes = 6;
- }
- else if (chr >= 0xF8) {
- nBytes = 5;
- }
- else if (chr >= 0xF0) {
- nBytes = 4;
- }
- else if (chr >= 0xE0) {
- nBytes = 3;
- }
- else if (chr >= 0xC0) {
- nBytes = 2;
- }
- else {
- return false;
- }
- nBytes--;
- }
- }
- else {
- //多字节符的非首字节,应为 10xxxxxx
- if ((chr & 0xC0) != 0x80) {
- return false;
- }
- //减到为零为止
- nBytes--;
- }
- }
- //违返UTF8编码规则
- if (nBytes != 0) {
- return false;
- }
- if (bAllAscii) { //如果全部都是ASCII, 也是UTF8
- return true;
- }
- return true;
- }
- ErrorCodeEnum CUpgradeTaskFSM::UnzipPack(const char* unZipPackName)
- {
- #ifdef RVC_OS_WIN
- // 设定解压临时目录
- char szOldPath[MAX_PATH] = {};
- GetCurrentDirectoryA(MAX_PATH, szOldPath);
- CSimpleStringA strDownloadsPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,get Downloads Path is fail");
- return Error_Unexpect;
- }
-
- CSimpleStringA strZipFile = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), unZipPackName);
- //升级包是否存在
- if(!ExistsFileA(strZipFile)){
- LogWarn(Severity_Low, Error_NotExist, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
- return Error_NotExist;
- }
- CSimpleStringA strUnzipDir;
- strUnzipDir = CSimpleStringA::Format("%s\\%s", strDownloadsPath.GetData(), unZipPackName);
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")){
- strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
- }
- // 解压目录是否存在,则先删除
- if (ExistsDirA(strUnzipDir.GetData()))
- {
- if(!RemoveDirRecursiveA(strUnzipDir.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,delete exist temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
- return Error_Unexpect;
- }
- }
- // 创建临时解压目录
- if(!CreateDirectoryA(strUnzipDir.GetData(), NULL)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,create temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
- return Error_Unexpect;
- }
- //设置当前目录为主目录
- if(!SetCurrentDirectoryA(strUnzipDir.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzipPack is fail,SetCurrentDirectoryA dir [%s] fail,err=%d",strUnzipDir.GetData(),GetLastError());
- return Error_Unexpect;
- }
- // 解压
- HZIP hz = OpenZip((void*)(const char*)strZipFile,0,ZIP_FILENAME);
- if (hz == 0)
- {
- SetCurrentDirectoryA(szOldPath);
- LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("open zip file [%s] fail", unZipPackName).GetData());
- return Error_Unexpect;
- }
- ZIPENTRY ze;
- ZRESULT zrc = GetZipItemA(hz,-1,&ze);
- if(zrc == ZR_OK){
- int numitems=ze.index;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("zip entry count is %d",ze.index);
- for (int i=0; i<numitems; i++)
- {
- zrc = GetZipItemA(hz,i,&ze);
- if(zrc==ZR_OK){
- //兼容压缩包里面中文名称是utf8编码
- if(is_str_utf8(ze.name)){
- char *pGBK = ConvertUtf8ToGBK((const char*)ze.name);
- zrc = UnzipItem(hz,i,pGBK,0,ZIP_FILENAME);
- if(zrc ==ZR_OK){
- //Dbg("unzip [%s] UTF8 item succeed", pGBK);
- delete[] pGBK;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip [%s] UTF8 item fail,result=0x%X", pGBK,(int)zrc);
- delete[] pGBK;
- break;
- }
- }else{
- zrc = UnzipItem(hz,i,ze.name,0,ZIP_FILENAME);
- if(zrc ==ZR_OK){
- //Dbg("unzip [%s] GBK item succeed", ze.name);
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip [%s] GBK item fail,result=0x%X", ze.name,(int)zrc);
- break;
- }
- }
- }else{
- //出错,退出
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("unzip GetZipItemA [%d] item fail,fail=0x%X",i,(int)zrc);
- break;
- }
- }
- CloseZip(hz);
- }else{
- CloseZip(hz);
- }
- // 恢复当前目录
- SetCurrentDirectoryA(szOldPath);
- if(zrc!=ZR_OK){
- return Error_Exception;
- }
- return Error_Succeed;
- #else
- CSimpleStringA strDownloadsPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
- if (rc != Error_Succeed) {
- Dbg("unzipPack is fail,get Downloads Path is fail");
- return Error_Unexpect;
- }
- CSimpleStringA strZipFile = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
- //升级包是否存在
- if (!ExistsFileA(strZipFile)) {
- LogWarn(Severity_Low, Error_NotExist, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("pack [%s] not exists", unZipPackName).GetData());
- return Error_NotExist;
- }
- CSimpleStringA strUnzipDir;
- strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), unZipPackName);
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")) {
- strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
- }
- // 解压目录是否存在,存在先删除
- if (ExistsDirA(strUnzipDir.GetData()))
- {
- if (!RemoveDirRecursiveA(strUnzipDir.GetData())) {
- Dbg("unzipPack is fail,delete exist temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), errno);
- return Error_Unexpect;
- }
- }
- // 创建临时解压目录
- if (!CreateDirA(strUnzipDir.GetData(), false)) {
- // 创建临时解压目录失败
- Dbg("unzipPack is fail,create temp unzip dir [%s] fail,err=%d", strUnzipDir.GetData(), errno);
- return Error_Unexpect;
- }
- if (changeFileAtt(strZipFile.GetData())!=0) {
- //改变文件属性
- Dbg("unzipPack is fail,changeFileAtt zip [%s] fail,err=%d", strZipFile.GetData(), errno);
- return Error_Unexpect;
- }
- // 解压
- string zipFileStr = strZipFile.GetData();
- string zipTempDir = strUnzipDir.GetData();
- if (UnZipToDir(zipFileStr, zipTempDir) != 0)
- {
- LogWarn(Severity_Low, Error_Unexpect, ERR_TASK_UNZIP_PACK_FAIL, CSimpleStringA::Format("unzip pack [%s] fail", unZipPackName));
- return Error_NotExist;
- }
- return Error_Succeed;
- #endif
- }
- ErrorCodeEnum CUpgradeTaskFSM::DeleteUnzipDir()
- {
- CSimpleStringA strDownloadsPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strDownloadsPath);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("DeleteUnzipDir is fail,get Downloads Path is fail");
- return Error_Unexpect;
- }
- //判断解压缩文件夹名是否存在,不存在告警
- if (m_currentTask.pack_name.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("DeleteUnzipDir is fail ,temp unzip dir name is null");
- return Error_Unexpect;
- }
- CSimpleStringA strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", strDownloadsPath.GetData(), m_currentTask.pack_name.GetData());
-
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")){
- strUnzipDir = strUnzipDir.SubString(0, strUnzipDir.GetLength()-4);
- }
- // 解压目录是否存在,存在则删除
- if (ExistsDirA(strUnzipDir.GetData()))
- {
- if(!RemoveDirRecursiveA(strUnzipDir.GetData())){
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(),(int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("DeleteUnzipDir fail , temp unzip dir [%s] fail,err=%d",strUnzipDir.GetData(), errno);
- #endif
- return Error_Unexpect;
- }else{
- return Error_Succeed;
- }
- }
- return Error_Succeed;
- }
- void CUpgradeTaskFSM::SendUpgradeTaskProgress(CTaskProcess &process, CSimpleStringA logCodeStr, CSimpleStringA rtaStr)
- {
- Json::Value root;
- Json::FastWriter fw;//写入对象
- if(!process.strPackName.IsNullOrEmpty()){
- root["strPackName"]=process.strPackName.GetData();
- }else{
- root["strPackName"]="";
- }
-
- if(process.installVersion.IsNullOrEmpty()){
- root["installVersion"]="0.0.0.0";
- }else{
- root["installVersion"]=process.installVersion.GetData();
- }
- //string currentBuildStr = CSimpleStringA::Format("%d.%d.%d",process.CurrentVersion.GetMajor(),process.CurrentVersion.GetMinor(),process.CurrentVersion.GetRevision()).GetData();
- root["CurrentVersion"]=process.CurrentVersion.GetData();
- root["CurrentBuild"]= process.CurrentVersion.GetData();
- root["upgradeTimeStr"]=CSmallDateTime::GetNow().ToTimeString().GetData();
- if(!process.cInstallState.IsNullOrEmpty()){
- root["cInstallState"]=process.cInstallState.GetData();
- }else{
- root["cInstallState"]="";
- }
- if(!process.strInstallComment.IsNullOrEmpty()){
- CSimpleStringA comment = "task:";
- comment.Append(process.strInstallComment.GetData());
- root["strInstallComment"]=comment.GetData();
- }else{
- root["strInstallComment"]="";
- }
- string upgradeStr = fw.write(root);
- if (!upgradeStr.empty()) {
- LogWarn(Severity_Low, Error_Succeed, LOG_WRAN_UPGRADE_PROGRESS, upgradeStr.c_str());
- if (rtaStr.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(logCodeStr).setAPI("SendUpgradeTaskProgress")(upgradeStr.c_str());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(logCodeStr).setResultCode(rtaStr).setAPI("SendUpgradeTaskProgress")(upgradeStr.c_str());
- }
- }else{
- LogWarn(Severity_Middle,Error_Unexpect,ERR_WRAN_UPGRADE_PROGRESS,"获取升级过程信息错误");
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::GetRunConfigStrValue(const char *pszSection, const char *pszKey, CSimpleStringA &strValue)
- {
- CSmartPointer<IConfigInfo> pConfig;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_Run, pConfig);
- if (rc != Error_Succeed){
- return rc;
- }
- return pConfig->ReadConfigValue(pszSection, pszKey, strValue);
- }
- ErrorCodeEnum CUpgradeTaskFSM::SetRunConfigStrValue(const char *pszSection, const char *pszKey, const char *pszValue)
- {
- CSmartPointer<IConfigInfo> pConfig;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_Run, pConfig);
- if (rc != Error_Succeed){
- return rc;
- }
- return pConfig->WriteConfigValue(pszSection, pszKey, pszValue);
- }
- bool CUpgradeTaskFSM::ClearCurrTaskInfo()
- {
- if(SetRunConfigStrValue("upgradeTask","UpgradeTaskId","")!=Error_Succeed){
- return false;
- }
- if(SetRunConfigStrValue("upgradeTask","CreateTaskVersion","")!=Error_Succeed){
- return false;
- }
- if(SetRunConfigStrValue("upgradeTask","PackName","")!=Error_Succeed){
- return false;
- }
- if(SetRunConfigStrValue("upgradeTask","PendingState","")!=Error_Succeed){
- return false;
- }
- if(SetRunConfigStrValue("upgradeTask","NewVersion","")!=Error_Succeed){
- return false;
- }
- if (SetRunConfigStrValue("upgradeTask", "TaskType", "") != Error_Succeed) {
- return false;
- }
- if (SetRunConfigStrValue("upgradeTask", "depNewVersion", "") != Error_Succeed) {
- return false;
- }
- //试着删除可能临时下载的升级包文件
- CSimpleStringA strPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Downloads", strPath);
- if(Error_Succeed != rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearCurrTaskInfo get Downloads path fail,upgradeTaskId=%s",m_currentTask.upgradeTaskId.GetData());
- return false;
- }
- CSimpleStringA tempPackPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s%s", strPath.GetData(), m_currentTask.pack_name.GetData(),".tmp");
- if(ExistsFileA(tempPackPath.GetData())){
- if(!RemoveFileA(tempPackPath.GetData())){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearCurrTaskInfo delete tempPack fail,packPath=%s",tempPackPath.GetData());
- return false;
- }
- }
- //清空内存变量
- m_currentTask.upgradeTaskId = "";
- m_currentTask.createTaskVersion = "";
- m_currentTask.pack_name = "";
- m_currentTask.cPendingState = "";
- m_currentTask.NewVersion="";
- m_currentTask.task_type = "";
- m_currentTask.depNewVersion = "";
- m_currentTask.pack_version = "";
- m_currentTask.stop_media_play =false;
- m_currentTask.reboot_type = 0;
- m_currentTask.file_path="";
- m_currentTask.download_url = "";
- m_currentTask.pack_hash = "";
- m_currentTask.pack_length = 0;
- ClearInstallStep();
- return true;
- }
- bool CUpgradeTaskFSM::ClearInstallStep()
- {
- //清理安装步骤
- int iCount = m_currentTask.install_step.size();
- for (int j = 0; j < iCount; j++){
- CInstallStep* tmp = m_currentTask.install_step.front();
- m_currentTask.install_step.pop();
- delete tmp;//删除对象
- }
- return true;
- }
- ErrorCodeEnum CUpgradeTaskFSM::LoadPersistTaskInfo()
- {
- // 从运行配置中读出上次未处理完的任务
- // 上次未安装结束
- CTaskInfo taskInfo = {};
- CSimpleStringA strValue;
- ErrorCodeEnum rc = GetRunConfigStrValue("upgradeTask", "UpgradeTaskId", strValue);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][UpgradeTaskId] fail ,err=%d",(int)rc);
- return rc;
- }
- taskInfo.upgradeTaskId = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "CreateTaskVersion", strValue);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][CreateTaskVersion] fail ,err=%d",(int)rc);
- return rc;
- }
- taskInfo.createTaskVersion = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "PackName", strValue);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][PackName] fail ,err=%d",(int)rc);
- return rc;
- }
- taskInfo.pack_name = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "PendingState", strValue);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][PendingState] fail ,err=%d",(int)rc);
- return rc;
- }
- taskInfo.cPendingState = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "NewVersion", strValue);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][NewVersion] fail ,err=%d",(int)rc);
- return rc;
- }
- taskInfo.NewVersion = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "TaskType", strValue);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][TaskType] fail ,err=%d", (int)rc);
- return rc;
- }
- taskInfo.task_type = strValue;
- rc = GetRunConfigStrValue("upgradeTask", "depNewVersion", strValue);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("recover upgrade state from run config, read [upgradeTask][depNewVersion] fail ,err=%d", (int)rc);
- return rc;
- }
- taskInfo.depNewVersion = strValue;
- //初始化其他变量
- //CSimpleStringA pack_version; //升级包指定的版本号
- //CSimpleStringA to_copy; //拷贝文件列表
- //CSimpleStringA to_run; //体系外运行脚本文件名称
- //bool reboot_type; //重启类型
- //CSimpleStringA download_url; //升级包下载地址
- //CSimpleStringA pack_hash; //升级包hash值
- //long pack_length; //升级包长度
- taskInfo.pack_version = "";
- taskInfo.reboot_type = 0;
- taskInfo.file_path = "";
- taskInfo.download_url = "";
- taskInfo.pack_hash = "";
- taskInfo.pack_length = 0;
- taskInfo.stop_media_play = true;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, UpgradeTaskId=%s", taskInfo.upgradeTaskId.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, CreateTaskVersion=%s",taskInfo.createTaskVersion.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, PackName=%s",taskInfo.pack_name.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, PendingState=%s",taskInfo.cPendingState.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, NewVersion=%s",taskInfo.NewVersion.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, TaskType=%s", taskInfo.task_type.GetData());
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("recover upgrade state from run config, depNewVersion=%s", taskInfo.depNewVersion.GetData());
- m_currentTask = taskInfo;
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::loadCenterCfgInfo()
- {
- //访问http地址的读取
- CSmartPointer<IConfigInfo> spConfig;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
- if (rc == Error_Succeed){
- CSimpleStringA str="";
- //加载后端服务访问地址
- rc = spConfig->ReadConfigValue("UpgradeManager", "QueryPreTaskUrl", str);
- if(rc==Error_Succeed){
- m_centerUrl.queryPreTaskUrl = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryPreTaskUrl=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryPreTaskUrl error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "QueryContinueTaskUrl", str);
- if(rc==Error_Succeed){
- m_centerUrl.queryContinueTaskUrl = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryContinueTaskUrl=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryContinueTaskUrl error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "UpdateTaskUrl", str);
- if(rc==Error_Succeed){
- m_centerUrl.updateTaskUrl = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini UpdateTaskUrl=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini UpdateTaskUrl error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "QueryCurrTaskUrl", str);
- if(rc==Error_Succeed){
- m_centerUrl.queryCurrTaskUrl = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryCurrTaskUrl=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryCurrTaskUrl error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "QueryNewTaskUrl", str);
- if(rc==Error_Succeed){
- m_centerUrl.queryNewTaskUrl = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryNewTaskUrl=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryNewTaskUrl error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "QueryTaskStatus", str);
- if(rc==Error_Succeed){
- m_centerUrl.queryTaskStatus = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini QueryTaskStatus=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini QueryTaskStatus error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "SendSM3TaskUrl", str);
- if(rc==Error_Succeed){
- m_centerUrl.sendSM3TaskUrl = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini SendSM3TaskUrl=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini SendSM3TaskUrl error");
- return rc;
- }
- //新的下载分段切片长度值(单位K)
- rc = spConfig->ReadConfigValue("UpgradeManager", "NewEachDownloadLen", str);
- if(rc==Error_Succeed){
- if(str.IsNullOrEmpty()){
- m_newEachDownloadLen = DOWNLOAD_CONTENT_EACH_LEN;
- }else{
- if(atoi(str.GetData())>16){
- m_newEachDownloadLen = atoi(str.GetData())*1024;
- }else{
- m_newEachDownloadLen = 16*1024;//设置默认最小值
- }
-
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini NewEachDownloadLen=%d K", m_newEachDownloadLen);
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini NewEachDownloadLen error");
- return rc;
- }
- //加载是否打印http通讯日志
- int printlogInt =0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "PrintLog", printlogInt);
- if(rc==Error_Succeed){
- if(printlogInt==0){
- m_PrintHttpLog = false;
- }else{
- m_PrintHttpLog = true;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini PrintLog=%d",printlogInt);
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini PrintLog error");
- return rc;
- }
- int startFlagInt =0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "StartFlag", startFlagInt);
- if(rc==Error_Succeed){
- if(startFlagInt==0){
- m_startFlag = false;
- }else{
- m_startFlag = true;
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini StartFlag=%d",startFlagInt);
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini StartFlag error");
- return rc;
- }
- int queryNewTaskInterval = 0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "queryNewTaskInterval", queryNewTaskInterval);
- if (rc == Error_Succeed) {
- if (queryNewTaskInterval != 0) {
- if (queryNewTaskInterval < 10) {
- m_queryNewTaskInterval = 10;
- }
- else {
- m_queryNewTaskInterval = queryNewTaskInterval;
- }
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init read CenterSetting.ini queryNewTaskInterval=%d", m_queryNewTaskInterval);
- }
- else {
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini queryNewTaskInterval error");
- return rc;
- }
- int installStopCopyDep = 0;
- rc = spConfig->ReadConfigValueInt("UpgradeManager", "installStopCopyDep", installStopCopyDep);
- if (rc == Error_Succeed) {
- if (installStopCopyDep == 1) {
- m_installStopCopyDep = true;//配置1时停止拷贝
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("init read CenterSetting.ini installStopCopyDep=%d", m_installStopCopyDep);
- }
- else {
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini installStopCopyDep error");
- return rc;
- }
- //加载扫描hash配置文件列表
- rc = spConfig->ReadConfigValue("UpgradeManager", "relativeDir", str);
- if(rc==Error_Succeed){
- m_hashScanSet.relativeDir = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini relativeDir=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini relativeDir error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "absoluteDir", str);
- if(rc==Error_Succeed){
- m_hashScanSet.absoluteDir = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini absoluteDir=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini absoluteDir error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "currVerDir", str);
- if(rc==Error_Succeed){
- m_hashScanSet.currVerDir = str;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini currVerDir=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini currVerDir error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "blackFile", str);
- if(rc==Error_Succeed){
- m_hashScanSet.blackFile = str;
- CAutoArray<CSimpleStringA> arr = str.Split('|');
- for(int i=0; i< arr.GetCount(); i++)
- {
- m_FileBlacklist.push_back(arr[i]);
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini blackFile=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini blackFile error");
- return rc;
- }
- rc = spConfig->ReadConfigValue("UpgradeManager", "blackDir", str);
- if(rc==Error_Succeed){
- m_hashScanSet.blackDir = str;
- CAutoArray<CSimpleStringA> arr = str.Split('|');
- for(int i=0; i< arr.GetCount(); i++)
- {
- m_DirBlacklist.push_back(arr[i]);
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("init read CenterSetting.ini blackDir=%s",str.GetData());
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini blackDir error");
- return rc;
- }
- }else{
- LogWarn(Severity_Middle, rc, ERR_TASK_READ_INI_FAIL, "get CenterSetting.ini error");
- return rc;
- }
- return Error_Succeed;
- }
- bool CUpgradeTaskFSM::GetFileLength(const char* filePath,long &fileLen)
- {
- FILE* file = fopen(filePath, "rb");
- if (file!=NULL)
- {
- #ifdef RVC_OS_WIN
- fileLen = filelength(fileno(file));
- fclose(file);
- return true;
- #else
- if (fseek(file, 0, SEEK_END)!=0) {
- Dbg("GetFileLength fseek is error,%s",strerror(errno));
- fclose(file);
- fileLen = 0;
- return false;
- }
- fileLen = ftell(file); ///求出当前文件指针距离文件开始的字节数
- if (fileLen == -1) {
- Dbg("GetFileLength ftell is error,%s", strerror(errno));
- fclose(file);
- fileLen = 0;
- return false;
- }
- else {
- fclose(file);
- return true;
- }
- #endif
- } else{
- fileLen = 0;
- return false;
- }
-
- return true;
- }
- ErrorCodeEnum CUpgradeTaskFSM::GetSM3List(CSimpleStringA &strSM3List)
- {
- if (!m_fileSM3List.IsNullOrEmpty())
- {
- strSM3List = m_fileSM3List;
- return Error_Succeed;
- }
- m_fileSM3Map.clear();//生成文件hash列表前先清空
-
- //根据配置项开始扫描文件和计算hash
- ErrorCodeEnum rc = Error_Succeed ;
- if(!m_hashScanSet.absoluteDir.IsNullOrEmpty()){
- //绝对路径扫描
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetSM3List scan absoluteDir=%s",m_hashScanSet.absoluteDir.GetData());
- rc = ScanSM3ByType(1,m_hashScanSet.absoluteDir);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan absoluteDir is fail");
- return rc;
- }
- }
- if(!m_hashScanSet.relativeDir.IsNullOrEmpty()){
- //相对路径扫描
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetSM3List scan relativeDir=%s",m_hashScanSet.relativeDir.GetData());
- ScanSM3ByType(2,m_hashScanSet.relativeDir);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan relativeDir is fail");
- return rc;
- }
- }
- if(!m_hashScanSet.currVerDir.IsNullOrEmpty()){
- //当前版本扫描
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetSM3List scan currVerDir=%s",m_hashScanSet.currVerDir.GetData());
- ScanSM3ByType(3,m_hashScanSet.currVerDir);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("GetMD5List fail ,scan currVerDir is fail");
- return rc;
- }
- }
- if(m_iBlackFileCount>50){
- LogWarn(Severity_Low, rc, WARN_BLACK_FILE_SUM, CSimpleStringA::Format("get MD5List black file count=%d",m_iBlackFileCount));
- }
- m_iBlackFileCount=0;
- for(auto it=m_fileSM3Map.begin(); it!=m_fileSM3Map.end(); it++)
- {
- strSM3List += it->first;
- strSM3List += ",";
- strSM3List += it->second;
- strSM3List += ";";
- }
- m_fileSM3List = strSM3List;
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::ScanSM3ByType(int type,CSimpleStringA pathFilter)
- {
- if(!pathFilter.IsNullOrEmpty()){
- CSimpleStringA rootPath;//根路径
- CSimpleStringA replacePath;//替换路径
- CSimpleStringA currPath;//当前版本路径
- CSimpleStringA tempPath ="";
- ErrorCodeEnum Error =m_pEntity->GetFunction()->GetPath("Root",tempPath);//例如:C:\Run /opt/Run
- if(Error_Succeed == Error){
- if(!tempPath.IsNullOrEmpty()){
- string runPathStr = tempPath.GetData();
- int pos = runPathStr.find_last_of(SPLIT_SLASH);
- rootPath = runPathStr.substr(0,pos).c_str();
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get Root path is null");
- return Error_Null;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get Root path is error");
- return Error;
- }
- CSimpleStringA tempCurrPath = "";
- Error =m_pEntity->GetFunction()->GetPath("Base",tempCurrPath);//例如:C:\Run\version\4.8.1.1 /opt/Run/version/4.8.1.1
- if(Error_Succeed == Error){
- if(!tempCurrPath.IsNullOrEmpty()){
- currPath = tempCurrPath;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get currVer path is null");
- return Error_Null;
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("ScanSM3ByType get currVer path is error");
- return Error;
- }
- //路径扫描
- CAutoArray<CSimpleStringA> copyList = pathFilter.Split('|');
- for(int i=0; i<copyList.GetCount(); i++)
- {
- CSimpleStringA file = copyList[i];
- #ifdef RVC_OS_WIN
- #else
- //UOS把路径改为反斜杠
- string replaceStr = file.GetData();
- std::replace(replaceStr.begin(), replaceStr.end(), '\\', '/');
- file = replaceStr.c_str();
- #endif
- if(file.IsNullOrEmpty()){
- continue;
- }else{
- //构造扫描的绝对路径
- CSimpleStringA scanFilter = "";
- CSimpleStringA replaceDir = "";
- if(type==1){
- //绝对路径
- scanFilter = file;
- replaceDir = GetFileDirectory(file.GetData());
- }else if(type==2){
- //相对路径
- scanFilter = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",rootPath.GetData(),file.GetData());
- replaceDir = GetFileDirectory(file.GetData());
- }else if(type==3){
- //当前版本路径:特殊处理下替换路径为Run\version\4.8.1.1
- scanFilter = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",currPath.GetData(),file.GetData());
- CSimpleStringA temp = scanFilter.SubString(rootPath.GetLength()+1,scanFilter.GetLength()-(rootPath.GetLength()+1));
- replaceDir = GetFileDirectory(temp.GetData());
- }
- //替换路径前缀
- ErrorCodeEnum ret = NewSM3Folder(scanFilter,replaceDir);
- if(ret!=Error_Succeed){
- return ret;
- }
- }
- }
- }
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::NewSM3Folder(CSimpleStringA scanFilter,CSimpleStringA replaceDir)
- {
- if(scanFilter.IsNullOrEmpty()){
- return Error_Succeed;
- }
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("scan file scanFilter is %s",scanFilter.GetData());
- //通配符
- if(scanFilter.IndexOf("*")>0){
- //找到要扫描的文件夹
- CSimpleStringA strFileDir = GetFileDirectory(scanFilter.GetData());
- //过滤通配条件
- CSimpleStringA strFileFilter = _GetFileName(scanFilter.GetData());
- list<CSimpleStringA> fileList;
- //获取所有根文件夹下的文件相对路径:如mod\test.dll
- RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
- for(auto it = fileList.begin(); it != fileList.end(); it++)
- {
-
- CSimpleStringA tempFile = *it;
- if (IsFileMatch(strFileFilter, _GetFileName(tempFile.GetData())))
- {
- CSimpleStringA tempFullName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",strFileDir.GetData(),tempFile.GetData());
- CSimpleStringA tempFileName = _GetFileName(tempFile.GetData());
- CSimpleStringA tempFileDir = GetFileDirectory(tempFile.GetData());
- //整个黑名单文件过滤
- bool isBlackFile = false;
- list<CSimpleStringA>::iterator itorFile = m_FileBlacklist.begin();
- while(itorFile!=m_FileBlacklist.end())
- {
- CSimpleStringA fileBlack = *itorFile;
- //if(tempFileName.IsEndWith(fileBlack.GetData(),true)){
- // isBlackFile=true;
- // break;
- //}
- if(IsFileMatch(fileBlack.GetData(),tempFileName.GetData())){
- isBlackFile=true;
- break;
- }
- itorFile++;
- }
- if(isBlackFile){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackFile Filter don't add to md5 list, file = [%s]", tempFullName.GetData());
- m_iBlackFileCount++;
- continue;
- }
- //整个黑名单文件夹过滤
- bool isBlackDir = false;
- list<CSimpleStringA>::iterator itorDir = m_DirBlacklist.begin();
- while(itorDir!=m_DirBlacklist.end())
- {
- CSimpleStringA dirBlack = *itorDir;
- if(tempFileDir.IndexOf(dirBlack.GetData())>0){
- isBlackDir=true;
- break;
- }
- itorDir++;
- }
- if(isBlackDir){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackDir Filter don't add to md5 list, dir = [%s]", tempFullName.GetData());
- continue;
- }
- //计算hash值,加入到hash列表
- CSimpleStringA strMD5Val;
- ErrorCodeEnum rErrcode = SM3FileToStr(tempFullName, strMD5Val,false);
- if (Error_Succeed != rErrcode)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("%s get sm3 fail ,error:%d", tempFullName.GetData(), (int)rErrcode);
- return rErrcode;
- }
- CSimpleStringA relativePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",replaceDir.GetData(),tempFile.GetData());
- //Dbg("scan file succ [%s]",relativePath.GetData());
- m_fileSM3Map[relativePath] = strMD5Val;
- Sleep(100);//时间片
- }
- }
- }else{
- if(ExistsFileA(scanFilter.GetData())){
- //整个黑名单文件过滤
- bool isBlackFile = false;
- CSimpleStringA tempFileName = _GetFileName(scanFilter.GetData());//文件名称
- CSimpleStringA tempFileDir = GetFileDirectory(scanFilter.GetData());//文件夹名称
- list<CSimpleStringA>::iterator itorFile = m_FileBlacklist.begin();
- while(itorFile!=m_FileBlacklist.end())
- {
- CSimpleStringA fileBlack = *itorFile;
- //if(scanFilter.IsEndWith(fileBlack.GetData(),true)){
- // isBlackFile=true;
- // break;
- //}
- if(IsFileMatch(fileBlack.GetData(),tempFileName.GetData())){
- isBlackFile=true;
- break;
- }
- itorFile++;
- }
- if(isBlackFile){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackFile Filter don't add to md5 list, file = [%s]", scanFilter.GetData());
- m_iBlackFileCount++;
- }
- //整个黑名单文件夹过滤
- bool isBlackDir = false;
- list<CSimpleStringA>::iterator itorDir = m_DirBlacklist.begin();
- while(itorDir!=m_DirBlacklist.end())
- {
- CSimpleStringA dirBlack = *itorDir;
- if(tempFileDir.IndexOf(dirBlack.GetData())>0){
- isBlackDir=true;
- break;
- }
- itorDir++;
- }
- if(isBlackDir){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("BlackDir Filter don't add to md5 list, dir = [%s]", scanFilter.GetData());
- }
- if(!isBlackDir&&!isBlackFile){
- //加入hash列表
- CSimpleStringA strMD5Val;
- ErrorCodeEnum rErrcode = SM3FileToStr(scanFilter, strMD5Val,false);
- if (Error_Succeed != rErrcode)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("%s get sm3 fail ,error:%d", scanFilter.GetData(), (int)rErrcode);
- return rErrcode;
- }
- CSimpleStringA tempFileName = _GetFileName(scanFilter.GetData());
- CSimpleStringA relativePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s",replaceDir.GetData(),tempFileName.GetData());
- //Dbg("scan file succ [%s]",relativePath.GetData());
- #ifdef RVC_OS_WIN
- #else
- Sleep(100);//加入时间碎片
- #endif
- m_fileSM3Map[relativePath] = strMD5Val;
- }
- }
- }
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::RollBackVersionCheck(string& failReason, CSimpleStringA& strErrMsg)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin RollBackVersionCheck");
- //获取新版本号
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("RootVer", rootVerPath);//获取version根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RollBackVersionCheck fail , get RootVer path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "RollBackVersionCheck: get RootVer path is fail");
- failReason = "C";
- strErrMsg = "RollBackVersionCheck fail , get RootVer path is fail";
- return Error_Bug;
- }
- CSimpleStringA strRollbackVersion = m_currentTask.pack_version;
- CVersion curVer = m_currentVersion;//当前版本号
- // 指定版本
- DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
- int n = sscanf(strRollbackVersion.GetData(), "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
- if (n != 4)
- {
- strErrMsg = CSimpleStringA::Format("指定回退版本号无效(%s)", strRollbackVersion.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("specified Rollback version is invalid: [%s]", strRollbackVersion.GetData()).GetData());
- failReason = "C";
- strErrMsg = CSimpleStringA::Format("specified Rollback version is invalid: [%s]", strRollbackVersion.GetData());
- return Error_Bug;
- }
- else {
- m_currentTask.NewVersion = strRollbackVersion;//赋值回退版本号给内存变量
- }
-
- if (curVer.ToString() == strRollbackVersion) {
- //版本号相同,
- strErrMsg = CSimpleStringA::Format("指定回退版本号与当前版本相同,无效(配置:%s, 当前:%s)", strRollbackVersion.GetData(), curVer.ToString().GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- else if (dwMajor > curVer.GetMajor()
- || (dwMajor == curVer.GetMajor() && dwMinor > curVer.GetMinor())
- || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision > curVer.GetRevision())
- || (dwMajor == curVer.GetMajor() && dwMinor == curVer.GetMinor() && dwRevision == curVer.GetRevision() && dwBuild > curVer.GetBuild())) {
- //升级版本大于当前版本
- strErrMsg = CSimpleStringA::Format("指定回退版本号大于当前版本号(配置:%s,当前:%s)", strRollbackVersion.GetData(), curVer.ToString().GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- //回退版本是否存在
- CSimpleStringA strRollbackVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.NewVersion.GetData());
- if (!ExistsDirA(strRollbackVerPath.GetData())) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("RollBackVersionCheck fail, strRollbackVerPath =%s is not exist,fail", strRollbackVerPath.GetData()).GetData());
- strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", strRollbackVersion.GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- return Error_Succeed;
- }
- void CUpgradeTaskFSM::judgeTaskClass()
- {
- m_TempDepUpgradeFlag = false;//每次安装前初始化。
- //临时方案判定是适配器升级还是应用升级
- if (isTerminalInstall()) {
- //安装时判断
- if (m_currentTask.pack_name.IndexOf("adapter") != -1) {
- m_TempDepUpgradeFlag = true;
- }
- }
- else {
- //非安装时判断:判断只有一条拷贝dep路径的策略
- if (!m_currentTask.install_step.empty()) {
- int iCount = m_currentTask.install_step.size();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install cmd size = %d", iCount);
- if (iCount == 1) {
- CInstallStep* tmp = m_currentTask.install_step.front();
- if (tmp->cmdType == "Copy") {
- if (tmp->srcPathType == "3") {
- CSimpleStringA depStr = "";
- depStr.Append(SPLIT_SLASH_STR).Append("dep").Append(SPLIT_SLASH_STR); //win :\dep\ uos: /dep/
- if (tmp->srcPath.IndexOf(depStr.GetData()) != -1) {
- m_TempDepUpgradeFlag = true;
- }
- }
- }
- }
- }
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::judgeRollbackTaskClass(CSimpleStringA verDirName, string& failReason, CSimpleStringA& strErrMsg)
- {
- //搜索终端应用目录,适配器应用目录,
- CSimpleStringA depPathStr(true);
- CSimpleStringA verPathStr(true);
- ErrorCodeEnum Err = GetEntityBase()->GetFunction()->GetPath("DepBase", depPathStr);
- if (Err != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("judgeRollbackTaskClass fail , get DepBase path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "judgeRollbackTaskClass: get DepBase path is fail");
- failReason = "C";
- strErrMsg = "judgeRollbackTaskClass fail , get DepBase path is fail";
- return Error_Bug;
- }
- Err = m_pEntity->GetFunction()->GetPath("RootVer", verPathStr);
- if (Err != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("judgeRollbackTaskClass fail , get RootVer path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "judgeRollbackTaskClass: get RootVer path is fail");
- failReason = "C";
- strErrMsg = "judgeRollbackTaskClass fail , get RootVer path is fail";
- return Error_Bug;
- }
- CSimpleStringA strDestDir = "";
- if (DirIsExist(verPathStr.GetData(), verDirName.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("app version dir find is ok,dir=%s", verDirName.GetData());
- m_TempDepUpgradeFlag = false;//应用版本
- return Error_Succeed;
- }
- else if (DirIsExist(depPathStr.GetData(), verDirName.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("dep version dir find is ok, dir=%s", verDirName.GetData());
- m_TempDepUpgradeFlag = true;//适配器版本
- return Error_Succeed;
- }
- else {
- CSimpleStringA errStr = CSimpleStringA::Format("judgeRollbackTaskClass fail, RollbackVerRootPath =[%s|%s] not find version dir [%s],fail", verPathStr.GetData(), depPathStr.GetData(), verDirName.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, errStr.GetData());
- strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", verDirName.GetData());
- failReason = "X";
- return Error_Unexpect;//不存在
- }
- }
- bool CUpgradeTaskFSM::DirIsExist(const char* scanPath, const char* dirName)
- {
- CSimpleStringA strDestDir = "";
- if (dirName == NULL||scanPath==NULL) {
- return false;
- }
- auto subdirs = fileutil_get_sub_dirs(scanPath);
- if (subdirs != NULL)
- {
- bool isMatch = false;
- for (int i = 0; i < subdirs->nelts; ++i)
- {
- const char* dir = ARRAY_IDX(subdirs, i, char*);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("dir=%s,dirName=%s", dir, dirName);
- CSimpleStringA dirNameStr = dirName;
- if (dirNameStr.Compare(_GetFileName(dir))==0) {
- isMatch = true;
- break;
- }
- }
- toolkit_array_free2(subdirs);
- return isMatch;
- }
- else {
- return false;
- }
- }
- int CUpgradeTaskFSM::ExecDepInstall(CSimpleStringA& strErrMsg)
- {
- if (!isTerminalInstall()) {
- //升级
- if (!m_currentTask.pack_version.IsNullOrEmpty()) {
- CSimpleStringA strUpgradeDepVersion = m_currentTask.pack_version;
- CSimpleStringA latterDepVersion;//要更新到的版本号
- CSimpleStringA curVer = m_currentDepVersion;//当前版本号
- // 指定版本
- latterDepVersion = strUpgradeDepVersion.GetData();
- if (curVer == strUpgradeDepVersion) {
- //版本号相同
- strErrMsg = CSimpleStringA::Format("指定升级适配器版本号与当前版本相同,无效(配置:%s, 当前:%s)", strUpgradeDepVersion.GetData(), curVer.GetData());
- return 0;
- }
- CSimpleStringA strErrInfo = "";
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateNewDepVersion,version[%s],pack[%s]", strUpgradeDepVersion.GetData(), m_currentTask.pack_name.GetData());
- ErrorCodeEnum rc = CreateNewDepVersion(latterDepVersion, strErrInfo);
- if (rc != Error_Succeed)
- {
- strErrMsg = CSimpleStringA::Format("CreateNewDepVersion fail:%s", strErrInfo.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewDepVersion,version[%s] fail:%s", strUpgradeDepVersion.GetData(), strErrInfo.GetData());
- //清理临时版本文件夹
- ClearUpgradeFailDepVersion(latterDepVersion);
- return 0;
- }
- else {
- m_currentTask.depNewVersion = strUpgradeDepVersion;//赋值升级适配器版本号给内存变量
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateNewDepVersion,version[%s] succ", strUpgradeDepVersion.GetData());
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDepInstall fail ,pack_version is null");
- strErrMsg = CSimpleStringA::Format("ExecDepInstall fail ,pack_version is null");
- return 0;
- }
- }
- else {
- //新安装,无值则填写默认初始版本号
- if (m_currentTask.pack_version.IsNullOrEmpty()) {
- m_currentTask.pack_version = "0.0.0.1";//新安装,默认初始适配器版本
- m_currentTask.depNewVersion = "0.0.0.1";
- }
- else {
- m_currentTask.depNewVersion = m_currentTask.pack_version.GetData();
- }
- if (m_installStopCopyDep) {
- //不需要拷贝dep公共库
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("installStopCopyDep is %d , No need to copy common Dep dir", m_installStopCopyDep);
- }
- else {
- //兼容拷贝dep公共库
- CSimpleStringA strErrInfo = "";
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin CreateInstallDepVersion,version[%s],pack[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.pack_name.GetData());
- ErrorCodeEnum rc = CreateInstallDepVersion(m_currentTask.depNewVersion, strErrInfo);
- if (rc != Error_Succeed)
- {
- strErrMsg = CSimpleStringA::Format("CreateInstallDepVersion fail:%s", strErrInfo.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateInstallDepVersion,version[%s] fail:%s", m_currentTask.depNewVersion.GetData(), strErrInfo.GetData());
- //清理临时版本文件夹
- ClearUpgradeFailDepVersion(m_currentTask.depNewVersion);
- return 0;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CreateInstallDepVersion,version[%s] succ", m_currentTask.depNewVersion.GetData());
- }
- }
- }
- //循环执行安装命令
- int iRet = 1;//默认是成功
- if (!m_currentTask.install_step.empty()) {
- int iCount = m_currentTask.install_step.size();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("install Dep cmd size = %d", iCount);
- for (int j = 0; j < iCount; j++) {
- CInstallStep* tmp = m_currentTask.install_step.front();
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====begin Dep cmd=[%s]=====", tmp->cmdType.GetData());
- //开始处理具体命令
- if (tmp->cmdType == "Delete") {
- bool ret = ExecDepDeleteCmd(strErrMsg, tmp);
- if (!ret) {
- //报错才判断
- if (tmp->cmdFail == 0) {
- iRet = 0;
- break;//出错直接退出
- }
- else if (tmp->cmdFail == 1) {
- //继续
- }
- else {
- iRet = 0;
- break;//其他值也退出
- }
- }
- }
- else if (tmp->cmdType == "Copy") {
- bool ret = ExecDepCpoyCmd(strErrMsg, tmp);
- if (!ret) {
- //报错才判断
- if (tmp->cmdFail == 0) {
- iRet = 0;
- break;//出错直接退出
- }
- else if (tmp->cmdFail == 1) {
- //继续
- }
- else {
- iRet = 0;
- break;//其他值也退出
- }
- }
- }
- else if (tmp->cmdType == "Run") {
- int retInt = ExecDepRunCmd(strErrMsg, tmp);
- if (retInt == 0 || retInt == -1) {
- //报错才判断
- if (tmp->cmdFail == 0) {
- iRet = retInt;//会有0,-1值
- break;//出错直接退出,并返回体系外结果
- }
- else if (tmp->cmdFail == 1) {
- //继续
- }
- else {
- iRet = 0;
- break;//其他值也退出
- }
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("cmd=[%s] is invalid", tmp->cmdType.GetData());
- iRet = 0;
- break;//命令无效直接退出
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("=====end Dep cmd=[%s]=====", tmp->cmdType.GetData());
- m_currentTask.install_step.pop();//去除元素
- delete tmp;//删除内存
- }
- }
- return iRet;//返回处理结果
- }
- ErrorCodeEnum CUpgradeTaskFSM::CreateNewDepVersion(CSimpleStringA NewSoftwareVersion, CSimpleStringA& strErrInfo)
- {
- // 创建新适配器版本
- CSimpleStringA rootDepPath;
- ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("DepBase", rootDepPath);//适配器根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail , get DepBase path is fail");
- strErrInfo = CSimpleStringA::Format("Create new dep version fail , get DepBase path is fail");
- return Error_Bug;
- }
- CSimpleStringA strCurDepPath;
- rc = m_pEntity->GetFunction()->GetPath("Dep", strCurDepPath);//获取当前适配器根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail , get Dep path is fail");
- strErrInfo = CSimpleStringA::Format("Create new dep version fail , get Dep path is fail");
- return Error_Bug;
- }
- //新路径
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootDepPath.GetData(), NewSoftwareVersion.GetData());
- if (m_currentDepVersion == NewSoftwareVersion)
- {
- 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());
- strErrInfo = CSimpleStringA::Format("new ver [%s] equals current ver [%s]", NewSoftwareVersion.GetData(), m_currentDepVersion.GetData());
- return Error_Bug;
- }
- if (ExistsDirA(strNewVerPath.GetData()))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new version dir [%s] already exist, delete it", strNewVerPath.GetData());
- if (!RemoveDirRecursiveA(strNewVerPath.GetData())) {
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail, delete already exist new dep version is fail:%d", GetLastError());
- strErrInfo = CSimpleStringA::Format("Create new dep version fail, delete already exist new dep version is fail:%d", (int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version fail, delete already exist new dep version is fail:%d", errno);
- strErrInfo = CSimpleStringA::Format("Create new dep version fail, delete already exist new dep version is fail:%d", errno);
- #endif
- return Error_Bug;
- }
- }
- if (!CreateDirA(strNewVerPath.GetData(), TRUE))
- {
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version dir fail: %d", GetLastError());
- strErrInfo = CSimpleStringA::Format("create new dep version dir fail: %d", (int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new dep version dir fail: %d", errno);
- strErrInfo = CSimpleStringA::Format("create new dep version dir fail: %d", errno);
- #endif
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("create new dep version dir succ, dir = %s", strNewVerPath.GetData());
- //增加错误信息字段,回传给上层应用
- CSimpleStringA strErrMsg = "";
- CSimpleStringA strSource = CSimpleStringA::Format("%s", strCurDepPath.GetData());
- CSimpleStringA strDest = CSimpleStringA::Format("%s", strNewVerPath.GetData());
- if (!RecursiveCopyDir(strSource, strDest, strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
- strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::CreateInstallDepVersion(CSimpleStringA NewSoftwareVersion, CSimpleStringA& strErrInfo)
- {
- LOG_FUNCTION();
- CSimpleStringA strCurVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("Base", strCurVerPath);//获取当前应用version路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new Install dep version fail , get Base path is fail");
- strErrInfo = CSimpleStringA::Format("Create new Install dep version fail , get Base path is fail");
- return Error_Bug;
- }
-
- CSimpleStringA strCurrDepPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "dep", strCurVerPath.GetData());
- if (ExistsDirA(strCurrDepPath.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new install common dep dir is exist, begin copy dir = %s", strCurrDepPath.GetData());
- //存在则拷贝公共库dep文件
- CSimpleStringA tempPath;
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\ /opt/Run/dep/
- if (Error_Succeed == Error) {
- CSimpleStringA strNewDepPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), NewSoftwareVersion.GetData());
- CSimpleStringA strErrMsg = "";
- if (!RecursiveCopyDir(strCurrDepPath.GetData(), strNewDepPath.GetData(), strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir fail");
- strErrInfo = CSimpleStringA::Format("copy dep dir fail: %s", strErrMsg.GetData());
- return Error_Unexpect;
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy dep dir succ");
- return Error_Succeed;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Create new Install dep version fail ,get DepBase path is fail");
- strErrInfo = CSimpleStringA::Format("Create new Install dep version fail , get DepBase path is fail");
- return Error_Bug;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("new install common dep dir is not exist, default return true,dir=%s", strCurrDepPath.GetData());
- return Error_Succeed;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::ClearUpgradeFailDepVersion(CSimpleStringA NewSoftwareVersion)
- {
- CSimpleStringA rootDepPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootDepPath);//适配器根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion fail , get DepBase path is fail");
- return Error_Bug;
- }
- //新路径
- CSimpleStringA strNewVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootDepPath.GetData(), NewSoftwareVersion.GetData());
- if (ExistsDirA(strNewVerPath.GetData()))
- {
- if (!RemoveDirRecursiveA(strNewVerPath.GetData())) {
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), (int)GetLastError());
- #else
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion fail, delete temp Version [%s] is fail:%d", strNewVerPath.GetData(), errno);
- #endif
- return Error_Bug;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion succ, delete temp Version [%s] ", strNewVerPath.GetData());
- return Error_Succeed;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ClearUpgradeFailDepVersion succ, delete temp Version [%s] is not exist ", strNewVerPath.GetData());
- return Error_Succeed;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::UpgradeDepToNewVersion()
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin UpgradeToDepNewVersion");
- //获取新版本号
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("NewDepVersion is null, pack_version=[%s] is not null,UpgradeToNewDepVersion fail, taskID=[%s]", m_currentTask.pack_version.GetData(), m_currentTask.upgradeTaskId.GetData());
- 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());
- return Error_Unexpect;//这种情况有问题,需要清除此任务
- }
- else {
- ErrorCodeEnum ec = Error_Exception;
- if (isTerminalInstall()) {
- //安装需要刷新适配器路径到框架。
- ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(m_currentTask.depNewVersion, true);
- }
- else {
- ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(m_currentTask.depNewVersion, false);
- }
- if (ec != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("UpgradeDepToNewVersion fail, RewriteDepVersion version %s return %s", m_currentTask.depNewVersion.GetData(),SpStrError(ec));
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_UPDATE_ACTIVE_FAIL, CSimpleStringA::Format("UpgradeToNewVersion: get RootVer path is fail", m_currentTask.depNewVersion.GetData(), SpStrError(ec)));
- }
- return ec;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SwitchUpgradeDepNow()
- {
- //根据重启策略类型去重启
- //重启策略类型(0:不启动 1:重启框架 2:重启系统)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin SwitchUpgradeDepNow");
- if (m_currentTask.reboot_type == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("upgrade to new dep version [%s] succeed, taskID=[%s] ", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData());
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- else if (m_currentTask.reboot_type == 1) {
- if (m_currentTask.task_type.Compare("U") == 0) {
- //适配器版本升级
- LogEvent(Severity_Middle, Event_DeviceAdapterUpgrade_Framework_Restart,
- CSimpleStringA::Format("upgrade to new dep version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else if (m_currentTask.task_type.Compare("R") == 0) {
- //适配器版本回退
- LogEvent(Severity_Middle, Event_DeviceAdapterRollBack_Framework_Restart,
- CSimpleStringA::Format("rollback to old dep version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- }
- else if (m_currentTask.reboot_type == 2) {
- if (m_currentTask.task_type.Compare("U") == 0) {
- LogEvent(Severity_Middle, Event_DeviceAdapterUpgrade_OS_Restart,
- CSimpleStringA::Format("upgrade to new dep version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else {
- LogEvent(Severity_Middle, Event_DeviceAdapterRollBack_OS_Restart,
- CSimpleStringA::Format("rollback to old dep version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("reSetType=[%d] is invalid ,upgrade to new dep version [%s] fail, taskID=[%s]", m_currentTask.reboot_type, m_currentTask.depNewVersion.GetData(), m_currentTask.upgradeTaskId.GetData());
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- // 强制刷新日志
- m_pEntity->GetFunction()->FlushLogFile();
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::RollBackDepVersionCheck(string& failReason, CSimpleStringA& strErrMsg)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin RollBackDepVersionCheck");
- //获取新版本号
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootVerPath);//获取version根路径
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("RollBackDepVersionCheck fail , get DepBase path is fail");
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, "RollBackDepVersionCheck: get DepBase path is fail");
- failReason = "C";
- strErrMsg = "RollBackDepVersionCheck fail , get DepBase path is fail";
- return Error_Bug;
- }
- CSimpleStringA strRollbackVersion = m_currentTask.pack_version;
- CSimpleStringA curDepVer = m_currentDepVersion;//当前版本号
- // 指定版本
- m_currentTask.depNewVersion = strRollbackVersion;//赋值适配器回退版本号给内存变量
- if (curDepVer == strRollbackVersion) {
- //版本号相同,
- strErrMsg = CSimpleStringA::Format("指定回退版本号与当前版本相同,无效(配置:%s, 当前:%s)", strRollbackVersion.GetData(), curDepVer.GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- //回退版本是否存在
- CSimpleStringA strRollbackVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), m_currentTask.depNewVersion.GetData());
- if (!ExistsDirA(strRollbackVerPath.GetData())) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLLBACK_VERSION_CHECK_FAIL, CSimpleStringA::Format("RollBackVersionCheck fail, strRollbackVerPath =%s is not exist,fail", strRollbackVerPath.GetData()).GetData());
- strErrMsg = CSimpleStringA::Format("指定回退版本文件夹不存在(配置:%s)", strRollbackVersion.GetData());
- failReason = "X";
- return Error_Unexpect;
- }
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::RollBackToHistoryDepVersion(CSimpleStringA historyDepVersion)
- {
- //判断是否为空
- if (historyDepVersion.IsNullOrEmpty())
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryDepVersion fail , historyDepVersion is null");
- return Error_Param;
- }
- // 判断目标版本是否等于当前版本
- if (historyDepVersion == m_currentDepVersion) {
- 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());
- return Error_Param;
- }
- // 检查对应文件夹是否存在
- CSimpleStringA rootVerPath;
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetPath("DepBase", rootVerPath);//获取version根路径
- if (rc != Error_Succeed) {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, "RollBackToHistoryDepVersion fail , get DepBase path is fail");
- return Error_Bug;
- }
- CSimpleStringA strHisVerPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootVerPath.GetData(), historyDepVersion.GetData());
- if (!ExistsDirA(strHisVerPath.GetData()))
- {
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryDepVersion fail, history version dir [%s] not exists", strHisVerPath.GetData()).GetData());
- return Error_NotExist;
- }
- ErrorCodeEnum ec = GetEntityBase()->GetFunction()->GetPrivilegeFunction()->RewriteDepVersion(historyDepVersion, false);
- if (ec != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackToHistoryDepVersion fail, RewriteDepVersion version %s return %s", strHisVerPath.GetData(), SpStrError(ec));
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_ROLL_BACK_ACTIVE_FAIL, CSimpleStringA::Format("RollBackToHistoryDepVersion fail, RewriteDepVersion version %s return %s", strHisVerPath.GetData(), SpStrError(ec)));
- }
- return ec;
- }
- int CUpgradeTaskFSM::ExecDepRunCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
- {
- CSimpleStringA destPath;//目的路径
- if (ins->dstPathType == "0") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(1, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "1") {
- destPath = ins->dstPath;//绝对路径
- }
- else if (ins->dstPathType == "2") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(2, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "3") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(3, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "4") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(4, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级包相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPath GetRootTypePath 4 is fail");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPathType is invalid %s", ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd destPathType is invalid %s", ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd destPath is %s", destPath.GetData());
- // ToRun=install.bat
- if (ExistsFileA(destPath.GetData()))
- {
- #ifdef RVC_OS_WIN
- // window模式下 如果是Wow64模式,需屏蔽System32重定向
- PVOID pRedirectOldValue(NULL);
- bool bIsWow64 = IsWow64Process();
- if (bIsWow64)
- {
- if (!Wow64DisableWow64FsRedirection(&pRedirectOldValue)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64DisableWow64FsRedirection fail: %d", GetLastError());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64DisableWow64FsRedirection succ");
- }
- }
- #endif
- //system(strSourcePath);
- string sysPathStr = destPath.GetData();
- CSimpleStringA err = "";
- int ret = system_on(sysPathStr, true, err);
- #ifdef RVC_OS_WIN
- // 如果是Wow64模式,恢复System32重定向
- if (bIsWow64)
- {
- if (!Wow64RevertWow64FsRedirection(pRedirectOldValue)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64RevertWow64FsRedirection fail: %d", GetLastError());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Wow64RevertWow64FsRedirection succ");
- }
- }
- #endif
- if (ret != 0) {
- //程序执行异常,结果未知
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown ,err=%s", err.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ,err=%s", err.GetData());
- #else
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, system_on exec unknown , ret=%d, err=%s", ret, strerror(errno));
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, system_on exec unknown ret=%d, err=%s", ret, strerror(errno));
- #endif
- return -1;//未知结果返回
- }
- else {
- //进一步看返回结果文件判断是否成功
- CSimpleStringA strUnzipPath = GetFileDirectory(destPath.GetData());
- #ifdef RVC_OS_WIN
- CSimpleStringA strResultLog = strUnzipPath + "\\result.log";//结果文件
- #else
- CSimpleStringA strResultLog = strUnzipPath + "/result.log";//结果文件
- #endif
- CSimpleStringA eErrorCode = "";
- //获取结果文件
- if (!GetSysUpgradeResult(strResultLog, eErrorCode, strErrMsg))
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, get result from result.log fail, %s", strErrMsg.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail ,get result from result.log fail, %s", strErrMsg.GetData());
- return 0;//失败
- }
- if (eErrorCode == "0")
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is succ,[%s] ", destPath.GetData());
- return 1;//成功
- }
- else {
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s", eErrorCode.GetData());
- #else
- DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail,errorCode = %s,%s", eErrorCode.GetData(), strErrMsg.GetData());
- #endif
- return 0;//失败
- }
- }
- }
- else
- {
- strErrMsg = CSimpleStringA::Format("ExecRunCmd is fail, run file [%s] is not Exist", destPath.GetData());
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecRunCmd is fail, run file [%s] is not Exist", destPath.GetData());
- return 0;//失败
- }
- }
- bool CUpgradeTaskFSM::ExecDepDeleteCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
- {
- //只删除同一层目录下的文件和文件夹
- CSimpleStringA destPath;//目的路径+通配符
- if (ins->dstPathType == "0") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(1, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "1") {
- destPath = ins->dstPath;//绝对路径
- }
- else if (ins->dstPathType == "2") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(2, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "3") {
- CSimpleStringA rootPath;
- if (GetDepRootTypePath(3, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPathType is invalid %s", ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecDeleteCmd destPathType is invalid %s", ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecDeleteCmd destPath is %s", destPath.GetData());
- if (destPath.IndexOf("*") > 0) {
- CSimpleStringA strFileFilter = _GetFileName(destPath);
- CSimpleStringA strDestDir = destPath.SubString(0, destPath.GetLength() - strFileFilter.GetLength() - 1);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match filter name [%s] in dir [%s]", strFileFilter.GetData(), strDestDir.GetData());
- // 删除所有匹配文件
- bool bRet = true;
- auto arr = fileutil_get_sub_files(strDestDir.GetData());
- if (arr != NULL)
- {
- for (int i = 0; i < arr->nelts; ++i)
- {
- char* file = ARRAY_IDX(arr, i, char*);
- if (IsFileMatch(strFileFilter, _GetFileName(file)))
- {
- if (RemoveFileA(file)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", file);
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", file);
- strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", file);
- bRet = false;
- break;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match file: [%s]", file);
- }
- }
- toolkit_array_free2(arr);
- if (!bRet) {
- return bRet;
- }
- }
- // 删除所有匹配子目录
- auto subdirs = fileutil_get_sub_dirs(strDestDir.GetData());
- if (subdirs != NULL)
- {
- for (int i = 0; i < subdirs->nelts; ++i)
- {
- const char* dir = ARRAY_IDX(subdirs, i, char*);
- if (IsFileMatch(strFileFilter, _GetFileName(dir)))
- {
- if (RemoveDirRecursive(dir)) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", dir);
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", dir);
- strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", dir);
- bRet = false;
- break;
- }
- }
- else
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ignore not match dir: [%s]", dir);
- }
- }
- toolkit_array_free2(subdirs);
- if (!bRet) {
- return bRet;
- }
- }
- return bRet;
- }
- else {
- //直接删除文件
- bool bRet = true;
- if (ExistsFileA(destPath.GetData()))
- {
- if (RemoveFileA(destPath.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file succ: [%s]", destPath.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match file fail: [%s]", destPath.GetData());
- strErrMsg = CSimpleStringA::Format("delete match file fail: [%s]", destPath.GetData());
- bRet = false;
- }
- return bRet;
- }
- else if (ExistsDirA(destPath.GetData()))
- {
- if (RemoveDirRecursiveA(destPath.GetData())) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir succ: [%s]", destPath.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete match dir fail: [%s]", destPath.GetData());
- strErrMsg = CSimpleStringA::Format("delete match dir fail: [%s]", destPath.GetData());
- bRet = false;
- }
- return bRet;
- }
- else
- {
- //指定文件不再则忽略删除此文件
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete file [%s] not exists,ignore delete file", destPath.GetData());
- return bRet;
- }
- }
- }
- bool CUpgradeTaskFSM::ExecDepCpoyCmd(CSimpleStringA& strErrMsg, CInstallStep* ins)
- {
- CSimpleStringA sourcePath;//路径+通配符
- if (ins->srcPathType == "0") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(1, rootPath)) {
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 1 is fail");
- return false;
- }
- }
- else if (ins->srcPathType == "1") {
- sourcePath = ins->srcPath;//绝对路径
- }
- else if (ins->srcPathType == "2") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(2, rootPath)) {
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//当前版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 2 is fail");
- return false;
- }
- }
- else if (ins->srcPathType == "3") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(4, rootPath)) {
- sourcePath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->srcPath.GetData());//升级包相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd sourcePath GetRootTypePath 4 is fail");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd srcPathType is invalid %s", ins->srcPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd srcPathType is invalid %s", ins->srcPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd sourcePath is %s", sourcePath.GetData());
- CSimpleStringA destPath;//目的路径文件夹
- if (ins->dstPathType == "0") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(1, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 1 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "1") {
- destPath = ins->dstPath;//绝对路径
- }
- else if (ins->dstPathType == "2") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(2, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//当前版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 2 is fail");
- return false;
- }
- }
- else if (ins->dstPathType == "3") {
- CSimpleStringA rootPath = "";
- if (GetDepRootTypePath(3, rootPath)) {
- destPath = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", rootPath.GetData(), ins->dstPath.GetData());//升级版本相对路径
- }
- else {
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd destPath GetRootTypePath 3 is fail");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd dstPathType is invalid %s", ins->dstPathType.GetData());
- strErrMsg = CSimpleStringA::Format("ExecCpoyCmd dstPathType is invalid %s", ins->dstPathType.GetData());
- return false;//不支持的路径类型
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("ExecCpoyCmd destPath is %s", destPath.GetData());
- if (sourcePath.IndexOf("*") > 0) {
- //循环匹配拷贝
- //找到要扫描的文件夹
- CSimpleStringA strFileDir = GetFileDirectory(sourcePath.GetData());
- //过滤通配条件
- CSimpleStringA strFileFilter = _GetFileName(sourcePath.GetData());
- list<CSimpleStringA> fileList;
- //获取所有根文件夹下的文件相对路径:如mod\test.dll
- RecursiveGetSubFiles(strFileDir.GetData(), strFileDir.GetData(), fileList);
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("find fileList =%d", fileList.size());
-
- for (auto it = fileList.begin(); it != fileList.end(); it++)
- {
- if (IsFileMatch(strFileFilter, _GetFileName((const char*)(*it))))
- {
- CSimpleStringA strSrcName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", GetFileDirectory(sourcePath.GetData()).GetData(), (const char*)(*it));//源文件路径
- CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), (const char*)(*it));//目标文件路径
- //匹配成功,开始拷贝文件
- CSimpleStringA errMsg = "";
- ErrorCodeEnum rc = CopyFileOperate(strSrcName.GetData(), strDestName.GetData(), 3, errMsg);
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] to [%s] %s", strSrcName.GetData(),strDestName.GetData(), rc == Error_Succeed ? "succeed" : "fail");
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail: %s", strSrcName.GetData(), errMsg.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail: %s", strSrcName.GetData(), errMsg.GetData());
- return false;//报错
- }
- }
- }
- }
- else {
- //直接拷贝文件:考虑有些文件因智能对比不一定下发,故如果文件不存在,则默认忽略此策略
- CSimpleStringA errMsg = "";
- CSimpleStringA strDestName = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", destPath.GetData(), _GetFileName(sourcePath.GetData()));
- if (ExistsFileA(sourcePath.GetData())) {
- ErrorCodeEnum rc = CopyFileOperate(sourcePath.GetData(), strDestName.GetData(), 3, errMsg);
- if (rc != Error_Succeed)
- {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:%s", sourcePath.GetData(), errMsg.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail:%s", sourcePath.GetData(), errMsg.GetData());
- return false;//报错
- }
- }
- else {
- if (ins->srcPathType == "3") {
- //升级包因智能升级不一定有指定的文件存在
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("拷贝指定的文件[%s]不存在,因智能升级对比过滤,故忽略此文件拷贝", sourcePath.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("copy file [%s] fail:file to copy not exist", sourcePath.GetData());
- strErrMsg = CSimpleStringA::Format("copy file [%s] fail:file to copy not exist", sourcePath.GetData());
- return false;//报错
- }
- }
- }
- return true;
- }
- bool CUpgradeTaskFSM::GetDepRootTypePath(int rootType, CSimpleStringA& Path)
- {
- //适配器
- CSimpleStringA tempPath;
- if (isTerminalInstall() && (rootType == 2 || rootType == 3)) {
- //当是安装状态时,此路径取pack_version值,如果为空,默认用0.0.0.1 版本号
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\4.9.1.1 /opt/Run/dep/4.9.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- if (!m_currentTask.pack_version.IsNullOrEmpty()) {
- Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
- }
- else {
- Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), "0.0.0.1");
- }
- return true;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is error");
- return false;
- }
- }
- if (rootType == 1) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Root", tempPath);//例如:C:\Run /opt/Run
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- string runPathStr = tempPath.GetData();
- int pos = runPathStr.find_last_of(SPLIT_SLASH);
- Path = runPathStr.substr(0, pos).c_str();
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get Root path is error");
- return false;
- }
- }
- else if (rootType == 2) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Dep", tempPath);//例如:C:\Run\dep\4.8.1.1 /opt/Run/dep/4.8.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- Path = tempPath;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get currDepVer path is error");
- return false;
- }
- }
- else if (rootType == 3) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("DepBase", tempPath);//例如:C:\Run\dep\4.9.1.1 /opt/Run/dep/4.9.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- Path = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_version.GetData());
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradeVer path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradeVer path is error");
- return false;
- }
- }
- else if (rootType == 4) {
- ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Downloads", tempPath);//例如:C:\rvc\Downloads\4.8.1.1 /opt/rvc/Downloads/4.8.1.1
- if (Error_Succeed == Error) {
- if (!tempPath.IsNullOrEmpty()) {
- CSimpleStringA strUnzipDir;
- strUnzipDir = CSimpleStringA::Format("%s" SPLIT_SLASH_STR "%s", tempPath.GetData(), m_currentTask.pack_name.GetData());
- //解压去除了.zip后缀
- if (strUnzipDir.IsEndWith(".zip")) {
- Path = strUnzipDir.SubString(0, strUnzipDir.GetLength() - 4);
- }
- else {
- Path = strUnzipDir;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is null");
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("get upgradePack path is error");
- return false;
- }
- }
- return true;
- }
- CSimpleStringA CUpgradeTaskFSM::getAlarmCurrVersion()
- {
- //一期因无法从策略获取适配器升级还是应用升级,默认返回当前应用版本数据,待二期再做区分
- return m_currentVersion.ToString();
- }
- ErrorCodeEnum CUpgradeTaskFSM::SM3FileToStr(CSimpleStringA strFilePath, CSimpleStringA &strSM3,bool isSub)
- {
- if(strFilePath.IsNullOrEmpty()){
- return Error_Null;
- }
- int nlen = strlen(strFilePath.GetData());
- char* pchar = new char[nlen+1];
- strcpy(pchar,strFilePath.GetData());
- BYTE md5[32]={0};
- try
- {
- if(SM3File(pchar,md5)){
- delete[] pchar;
- //获取16进制的字符串
- if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 to hex str fail,file=%s",strFilePath.GetData());
- return Error_Unexpect;
- }
- return Error_Succeed;
- }else{
- delete[] pchar;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt fail ,file=%s",strFilePath.GetData());
- return Error_Unexpect;
- }
- }
- catch (...)
- {
- delete[] pchar;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt exception ,file=%s",strFilePath.GetData());
- return Error_Exception;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SM3DataToStr(CSimpleStringA strData, CSimpleStringA &strSM3,bool isSub)
- {
- if(strData.IsNullOrEmpty()){
- return Error_Null;
- }
- BYTE md5[32]={0};
- try
- {
- if(SM3Hash((BYTE*)strData.GetData(),strlen(strData.GetData()),md5)){
- //获取16进制的字符串
- if(Error_Succeed!=SM3_Str(strSM3,md5,isSub)){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 to hex str fail");
- return Error_Unexpect;
- }
- return Error_Succeed;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt fail");
- return Error_Unexpect;
- }
- }
- catch (...)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("sm3 encrypt exception");
- return Error_Exception;
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SM3_Str(CSimpleStringA &strSM3,BYTE * SM3Byte,bool isSub)
- {
- if(SM3Byte == NULL){
- return Error_Exception;
- }
- int SM3_len=64;
- if(isSub){
- SM3_len=32;
- }
- int i;
- char* file_SM3 = (char*)malloc((SM3_len + 1) * sizeof(char));
- if(file_SM3 == NULL)
- {
- fprintf(stderr, "SM3 malloc failed.\n");
- return Error_Exception;
- }
- memset(file_SM3, 0, (SM3_len + 1));
- if(SM3_len == 32)
- {
- for(i=0; i<16; i++)
- { //SM3截取中间16位字节,8-24位字节数,小写
- sprintf(&file_SM3[i*2], "%02x", SM3Byte[i+8]);
- }
- }
- else if(SM3_len == 64)
- {
- for(i=0; i<32; i++)
- {
- sprintf(&file_SM3[i*2], "%02x", SM3Byte[i]);
- }
- }
- strSM3=file_SM3;
- free(file_SM3);
- return Error_Succeed;
- }
- bool CUpgradeTaskFSM::IsPackDownloaded(const char *packPath,const char* packHash,long packLen)
- {
- if(!ExistsFileA(packPath)){
- return false;//文件不存在,下载
- }
- //计算hash值
- CSimpleStringA strMD5Val;
- ErrorCodeEnum rc = SM3FileToStr(packPath, strMD5Val,false);
- if (Error_Succeed != rc)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s get download pack sm3 fail ,error:%d", packPath, (int)rc);
- return false;//获取hash码失败,下载
- }
- //不区分大小写比较文件hash
- #ifdef RVC_OS_WIN
- if(stricmp(strMD5Val.GetData(),packHash)==0){
- #else
- if(strcmp(strMD5Val.GetData(),packHash)==0){
- #endif
- return true;//相同,不下载
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("%s sm3[%s] is no equal upgrade sm3[%s], retry download.", packPath, strMD5Val.GetData(), packHash);
- return false;//不相同,下载
- }
- }
- bool CUpgradeTaskFSM::DownloadFileWrite(byte* content,long contentLen,const char* filePath)
- {
- if(contentLen==0){
- return true;
- }
- FILE* tempFp = fopen(filePath,"ab");
- if(tempFp==NULL){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite open file fail");
- return false;
- }
- int ret = fwrite(content,(size_t)contentLen,1,tempFp);
- fclose(tempFp);
- if(ret!=1){
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite write file fail,ret = %d,errno = %d",ret,(int)GetLastError());
- return false;
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("DownloadFileWrite write file fail,ret = %d,errno = %d",ret, errno);
- return false;
- #endif
- }
- return true;
- }
- bool CUpgradeTaskFSM::CheckIfCanSwitchNow()
- {
- //对于终端初始化安装时,直接通过。
- if (isTerminalInstall()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow terminal new install,return true");
- return true;
- }
- //非重启操作,则直接可以进行切换,不用等待时机
- if(m_currentTask.reboot_type == 0){
- return true;
- }
- CSimpleStringA strCustomerHandle;
- CSimpleStringA strCallState;
- // 无交互N、客户关注A、客户在控制终端C、柜员协助T、柜员代操作G
- ErrorCodeEnum rc = m_pEntity->GetFunction()->GetSysVar("CustomerHandle", strCustomerHandle);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get CustomerHandle value is fail ,err=%d",(int)rc);
- return false;
- }
- // 离线O、尝试连线柜员C、免提通话H、连线失败F、断线B
- rc = m_pEntity->GetFunction()->GetSysVar("CallState", strCallState);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get CallState value is fail ,err=%d",(int)rc);
- return false;
- }
- #ifdef RVC_OS_WIN
- SYSTEMTIME st = {};
- GetLocalTime(&st);
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("hour is %d",(int)st.wHour);
- bool bOffworkTime = st.wHour < 8 || st.wHour >= 21;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("hour is %d, strCustomerHandle=%s, strCallState=%s, bOffworkTime=%d",(int)st.wHour,strCustomerHandle.GetData(),strCallState.GetData(),(int)bOffworkTime);
- #else
- time_t nowTime = time(NULL);
- tm nowTimeTm = { 0 };
- localtime_r(&nowTime, &nowTimeTm);
- //Dbg("hour is %d", (int)nowTimeTm.tm_hour);
- bool bOffworkTime = nowTimeTm.tm_hour < 8 || nowTimeTm.tm_hour >= 21;
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("hour is %d, strCustomerHandle=%s, strCallState=%s, bOffworkTime=%d",(int)nowTimeTm.tm_hour,strCustomerHandle.GetData(),strCallState.GetData(),(int)bOffworkTime);
- #endif
- // 或者下班时间且非连线状态 @20151202
- // 客户关注状态A,不允许切换 by zl 20191113
- if (strCustomerHandle[0] == 'N' || (bOffworkTime && strCallState[0] == 'O')) {
- return true;
- }
- else {
- // 防止感知一直误报有人状态,加入以下特例:如果是一天当中首次从切换状态直接跳转过来的升级切换,并且当前是首页则进行切换
- if (!bOffworkTime) {
- CSimpleStringA strUIState;
- // M 首页
- rc = m_pEntity->GetFunction()->GetSysVar("UIState", strUIState);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow get strUIState value is fail ,err=%d", (int)rc);
- return false;
- }
- #ifdef RVC_OS_WIN
- CSimpleStringA nowStr = CSimpleStringA::Format("%d-%d-%d", st.wYear, st.wMonth, st.wDay).GetData();
- #else
- CSimpleStringA nowStr = CSimpleStringA::Format("%d-%d-%d", nowTimeTm.tm_year+1900, nowTimeTm.tm_mon+1, nowTimeTm.tm_mday).GetData();
- #endif
- //读取强制切换的日期
- CSimpleStringA ForceSwitchDateStr = "";
- ErrorCodeEnum rc = GetRunConfigStrValue("upgradeTask", "ForceSwitchDate", ForceSwitchDateStr);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow read from run config, read [upgradeTask][ForceSwitchDate] fail ,err=%d", (int)rc);
- return false;
- }
- //首页并且切换状态直接进入
- if (strUIState.Compare("M") == 0 && m_bSwitchFlag) {
- //当天是否切换过
- if (ForceSwitchDateStr.Compare(nowStr.GetData()) == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow is not ForceSwitch, ForceSwitchDate[%s]", ForceSwitchDateStr.GetData());
- return false;
- }
- else {
- //直接切换,并写入强制切换日期
- if (SetRunConfigStrValue("upgradeTask", "ForceSwitchDate", nowStr.GetData()) != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow write run config, write [upgradeTask][ForceSwitchDate] fail[%s],err=%d", nowStr.GetData(), (int)rc);
- }
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow ForceSwitch, ForceSwitchDate[%s]", nowStr.GetData());
- return true;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("CheckIfCanSwitchNow is not ForceSwitch, UIState=%s,m_bSwitchFlag=%d", strUIState.GetData(),(int)m_bSwitchFlag);
- return false;
- }
- }
- else {
- return false;
- }
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::SwitchUpgradeNow()
- {
- //默认轻量包不重启系统和框架,体系外系统不重启系统,系统升级重启框架
- //根据重启策略类型去重启
- //重启策略类型(0:不启动 1:重启框架 2:重启系统)
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("begin SwitchUpgradeNow");
- if (m_currentTask.reboot_type == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("upgrade to new version [%s] succeed, taskID=[%s] ", m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData());
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- else if (m_currentTask.reboot_type == 1) {
- if (m_currentTask.NewVersion.IsNullOrEmpty()) {
- //非版本升级
- LogEvent(Severity_Middle, Event_Req_Framework_No_Upgrade_Restart,
- CSimpleStringA::Format("upgrade to new version [%s] succeed, request to no upgrade restart framework , taskID=[%s]", m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else {
- if (m_currentTask.task_type.Compare("U") == 0) {
- //版本升级,健康有后续回退处理
- LogEvent(Severity_Middle, Event_Req_Framework_Restart,
- CSimpleStringA::Format("upgrade to new version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else if (m_currentTask.task_type.Compare("R") == 0) {
- //版本回退,健康无后续回滚处理
- LogEvent(Severity_Middle, Event_Req_Framework_Rollback_Restart,
- CSimpleStringA::Format("rollback to old version [%s] succeed, request to restart framework , taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- }
- }
- else if (m_currentTask.reboot_type == 2) {
- if (m_currentTask.NewVersion.IsNullOrEmpty()) {
- //非版本升级
- LogEvent(Severity_Middle, Event_Req_OS_Restart,
- CSimpleStringA::Format("SysPackInstall upgrade to new version [%s] succeed, request to restart OS, taskID=[%s]", m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else {
- if (m_currentTask.task_type.Compare("U") == 0) {
- LogEvent(Severity_Middle, Event_Req_OS_Upgrade_Restart,
- CSimpleStringA::Format("upgrade to new version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- else {
- LogEvent(Severity_Middle, Event_Req_OS_Restart,
- CSimpleStringA::Format("rollback to old version [%s] succeed, request to restart OS, taskID=[%s]", m_currentTask.NewVersion.GetData(), m_currentTask.upgradeTaskId.GetData()));
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_PreRestart));//进入S7
- }
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("reSetType=[%d] is invalid ,upgrade to new version [%s] fail, taskID=[%s]", m_currentTask.reboot_type, m_currentVersion.ToString().GetData(), m_currentTask.upgradeTaskId.GetData());
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- // 强制刷新日志
- m_pEntity->GetFunction()->FlushLogFile();
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::DownloadProgress(long tempFileLen,long fileSumLen)
- {
- UpgradeDownloadProgress dProgress;
- dProgress.currentFile = m_currentTask.pack_name;
- dProgress.fileNum = 1;
- dProgress.progress=0;
- if(fileSumLen!=0){
- //DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("tempFileLen =%d , fileSumLen =%d",tempFileLen,fileSumLen);
- dProgress.progress = (int)(tempFileLen/(fileSumLen/100));
- if(dProgress.progress ==10||dProgress.progress ==20||dProgress.progress ==30||dProgress.progress ==40||dProgress.progress ==50
- ||dProgress.progress ==60||dProgress.progress ==70||dProgress.progress ==80||dProgress.progress ==90)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("download progress is %d ,tempFileLen =%d , fileSumLen =%d",dProgress.progress,tempFileLen,fileSumLen);
- }
- //Dbg("download file [%s] progress is %d",dProgress.currentFile.GetData(),dProgress.progress);
- ErrorCodeEnum retError = SpSendBroadcast(GetEntityBase()->GetFunction(), SP_MSG_OF(UpgradeDownloadProgress), SP_MSG_SIG_OF(UpgradeDownloadProgress), dProgress);
- return retError;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI("DownloadProgress")("download file [%s] progress is fail,sumlen=0");
- return Error_Exception;
- }
-
- }
- char CUpgradeTaskFSM::GetInstallState(int nState)
- {
- if (nState == s4)
- return 'U';
- else if (nState == s5)
- return 'I';
- else if (nState == s6)
- return 'S';
- else
- return 'N';
- }
- ErrorCodeEnum CUpgradeTaskFSM::GetUpgradeState(bool &bInstalling, CSimpleStringA &strPackFile, CSimpleStringA &strExecID, char &cInstallState, bool &bSysInstall, bool &bLightPack, CSimpleStringA &strNewVersion)
- {
- bInstalling = !m_currentTask.upgradeTaskId.IsNullOrEmpty();
- if (bInstalling)
- {
- strPackFile = m_currentTask.pack_name;
- strExecID = m_currentTask.upgradeTaskId;
- cInstallState = GetInstallState(m_iState);
- bSysInstall = false;
- bLightPack = false;
- //if(!m_currentTask.to_run.IsNullOrEmpty()){
- // bSysInstall = true;
- //}else{
- // bSysInstall = false;
- //}
- //if(m_currentTask.pack_version.IsNullOrEmpty()){
- // bLightPack = true;
- //}else{
- // bLightPack = false;
- //}
- strNewVersion = m_currentTask.NewVersion;
- }
- return Error_Succeed;
- }
- void CUpgradeTaskFSM::HttpsLogCallBack(const char* logtxt)
- {
- DbgWithLink(LOG_LEVEL_DEBUG,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("http dbg: %s",logtxt);
- }
- bool CUpgradeTaskFSM::isWork()
- {
- //兜底方案是判断集中配置一个参数,去除其他变量的判断,但是容易出现任务状态更新不准的情况。
- if(m_startFlag){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade startFlag is true");
- return true;
- }
- //判断是否在设备安装状态,不受一般升级影响
- if (isTerminalInstall()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("isTerminalInstall get TerminalStage is N");
- return true;
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("isTerminalInstall get TerminalStage is not N");
- }
-
- //判断升级实体是否工作
- //1.当有版本升级任务时,判断是否处于Guardian升级回退过程,如果已经升级成功或者回退成功,则开始工作,否则等待中
- //2.当无任务或者非版本升级任务时,判断TerminalStage这个变量,非X状态,当A状态并且进入首页,则开始工作
-
- //升级任务
- if((!m_currentTask.NewVersion.IsNullOrEmpty())&&(m_currentTask.cPendingState=="T"||m_currentTask.cPendingState=="C"||m_currentTask.cPendingState=="X")){
- CSimpleStringA strRunInfo,strStartTime;
- if (m_pEntity->GetFunction()->GetPath("RunInfo",strRunInfo) == Error_Succeed){
- #ifdef RVC_OS_WIN
- strStartTime = strRunInfo + "\\runcfg\\starttime.dat";
- #else
- strStartTime = strRunInfo + "/runcfg/starttime.dat";
- #endif
- if(!ExistsFileA(strStartTime.GetData())){
- return true;//完成升级过程,通过
- }else{
- #ifdef RVC_OS_WIN
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade process is not end ,file \\runcfg\\starttime is exist");
- #else
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade process is not end ,file /runcfg/starttime is exist");
- #endif
- return false;//继续等待
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgrade process is not end ,get runinfo path is error");
- return false;//失败,继续等待
- }
- }
- //适配器任务
- if ((!m_currentTask.depNewVersion.IsNullOrEmpty()) && (m_currentTask.cPendingState == "T" || m_currentTask.cPendingState == "C" || m_currentTask.cPendingState == "X")) {
- return true;//适配器无升级监护
- }
- //非升级任务和无任务
- CSimpleStringA strValue;
- if(m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed){
- if(strValue.Compare("X")==0){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("TerminalStage = X ,continue wait");
- return false;//状态是x继续等待
- }
- if(strValue.Compare("A")==0){
- if(((CUpgradeMgrEntity*)m_pEntity)->m_bStartUp){
- return true;//通过
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("TerminalStage = A ,but UIState is not M , continue wait");
- return false;//准入过,但进入首页,继续等待
- }
- }
- return true;//剩余其他状态都可以通过
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("get TerminalStage is error , continue wait");
- return false;//失败,继续等待
- }
- }
- bool CUpgradeTaskFSM::isAuthSucc() {
- CSimpleStringA strValue;
- if (m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed) {
- if (strValue.Compare("A") == 0) {
- return true;
- }
- else {
- return false;
- }
- }
- else {
- return false;
- }
- }
- bool CUpgradeTaskFSM::isTerminalInstall() {
- CSimpleStringA strValue;
- if (m_pEntity->GetFunction()->GetSysVar("TerminalStage", strValue) == Error_Succeed) {
- if (strValue.Compare("N") == 0) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("isTerminalInstall get TerminalStage=N");
- return true; //表示安装模式
- }else{
- return false;
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("isTerminalInstall get TerminalStage is error , default return fasle");
- return false;//默认认为在升级状态
- }
- }
- void CUpgradeTaskFSM::upgradeSuccStateBroadCast() {
- UpgradeStateEvent stateEvent;
- stateEvent.strPackName = m_currentTask.pack_name.GetData();
- stateEvent.strExecID = m_currentTask.upgradeTaskId.GetData();
- stateEvent.cInstallState = 'A';//表示成功状态
- stateEvent.bSysInstall = false;
- stateEvent.bLightPack = false;
- stateEvent.strNewVersion = m_currentTask.NewVersion;
- SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
- }
- #ifdef RVC_OS_WIN
- #else
- int CUpgradeTaskFSM::changeFileAtt(const char* path)
- {
- struct stat attr_of_del;
- if (lstat(path, &attr_of_del) == 0)
- {
- //修改为775属性
- mode_t f_attrib = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | S_IXOTH;
- if (chmod(path, f_attrib) != 0)
- {
- Dbg("set file attribute is fail,errno=%d, file=%s", errno, path);
- return -1;
- }
- return 0;
- }
- else {
- Dbg("get file attribute is fail,errno=%d, file=%s", errno, path);
- return -1;
- }
- }
- #endif
- void CUpgradeTaskFSM::OnStateTrans(int iSrcState, int iDstState)
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("trans from %s to %s", GetStateName(iSrcState), GetStateName(iDstState));
- if (iSrcState >= s4 && iDstState <= s3)
- {
- // 发送状态广播(通知业务界面清除状态)
- UpgradeStateEvent stateEvent;
- stateEvent.strPackName = "";
- stateEvent.strExecID = "";
- stateEvent.cInstallState = 'N';
- stateEvent.bSysInstall = false;
- stateEvent.bLightPack = false;
- stateEvent.strNewVersion = "";
- SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
- }
- else if (iDstState >= s4)
- {
- //assert(HasRunningUpdate());
- //SetRunConfigStrValue("Install", "Pack", m_strIntallingPack);
- //if (iDstState == s3)
- // SetRunConfigStrValue("Install", "PendingState", "U");
- //else if (iDstState == s4)
- // SetRunConfigStrValue("Install", "PendingState", "I");
- //else if (iDstState == s5)
- // SetRunConfigStrValue("Install", "PendingState", "C");
- //else if (iDstState == s6)
- // SetRunConfigStrValue("Install", "PendingState", "S");
- // 发送状态广播
- UpgradeStateEvent stateEvent;
- stateEvent.strPackName = m_currentTask.pack_name.GetData();
- stateEvent.strExecID = m_currentTask.upgradeTaskId.GetData();
- stateEvent.cInstallState = GetInstallState(iDstState);
- stateEvent.bSysInstall = false;
- stateEvent.bLightPack = false;
- stateEvent.strNewVersion = m_currentTask.NewVersion;
- SpSendBroadcast(m_pEntity->GetFunction(), eMsg_UpgradeStateEvent, eMsgSig_UpgradeStateEvent, stateEvent);
- }
- }
- void CUpgradeTaskFSM::OnSysVarEvent(const char *pszKey, const char *pszValue,const char *pszOldValue,const char *pszEntityName)
- {
- //监听系统变量状态
- if(strcmp("CallState",pszKey)==0){
- if (pszValue[0] == 'O') {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("m_bDownloadIdle is false ");
- m_bDownloadIdle = false;//可以下载
- } else {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("m_bDownloadIdle is true");
- m_bDownloadIdle = true;//不能下载
- }
- }
- }
- ErrorCodeEnum CUpgradeTaskFSM::OnInit()
- {
- //初始化
- ErrorCodeEnum rc = LoadPersistTaskInfo();//加载运行时文件
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("LoadPersistTaskInfo fail");
- return rc;
- }
- rc = loadCenterCfgInfo();//加载集中配置文件
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("loadCenterCfgInfo fail");
- return rc;
- }
- //加载终端启动的版本号
- CSystemStaticInfo info;
- rc = m_pEntity->GetFunction()->GetSystemStaticInfo(info);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("load GetSystemStaticInfo fail ");
- return rc;
- }else{
- m_currentVersion = info.InstallVersion;//当前版本号赋值
- m_currentDepVersion = info.CurrDepVersion.GetData();//当前适配器版本号,有可能为空
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("App version:%s , Dep version:%s", m_currentVersion.ToString().GetData(),m_currentDepVersion.GetData());
- }
- //注册callstate变量监控
- rc = m_pEntity->GetFunction()->RegistSysVarEvent("CallState", this);
- if(rc!=Error_Succeed){
- LogWarn(Severity_Middle, rc, ERR_WRAN_REGIST_SYS_VAR_FAIL, CSimpleStringA::Format("RegistSysVarEvent CallState is fail,%d",(int)rc).GetData());
- return rc;//自检失败
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("RegistSysVarEvent UIState succ");
- }
- AddStateHooker(this);
- ((CUpgradeMgrEntity*)m_pEntity)->testActive();//添加测试active文件是否被占用的方法
- return Error_Succeed;
- }
- ErrorCodeEnum CUpgradeTaskFSM::OnExit()
- {
- m_pEntity->GetFunction()->UnregistSysVarEvent("CallState");
- RemoveStateHooker(this);
- return Error_Succeed;
- }
- void CUpgradeTaskFSM::s1_on_entry()
- {
- //判断是否进入了首页
- CSimpleStringA strValue;
- if(isWork()&&((CUpgradeMgrEntity*)m_pEntity)->m_initSucc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("====upgrade is start up ====");
- ScheduleTimer(2,10*1000);//首次进入等待hash时间
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("last upgrade progress is not end or is not initSucc,wait 10s ");
- ScheduleTimer(1, 10*1000);//等待一段时间再判断是否进入首页
- }
- }
- void CUpgradeTaskFSM::s1_on_exit()
- {
- CancelTimer(1);//等待进入首页计时器
- CancelTimer(2);//等待hash计算计时器
- }
- unsigned int CUpgradeTaskFSM::s1_on_event(FSMEvent* event)
- {
- if (event->iEvt == EVT_TIMER)
- {
- if(event->param1 == 1){
- CSimpleStringA strValue;
- if(isWork()&&((CUpgradeMgrEntity*)m_pEntity)->m_initSucc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("====upgrade is start up ====");
- ScheduleTimer(2,10*1000);//首次进入等待hash时间
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("last upgrade progress is not end or is not initSucc,wait 10s ");
- ScheduleTimer(1, 10*1000);//等待一段时间再判断是否进入首页
- }
- }else if(event->param1 ==2){
-
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入s2
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s2_on_entry()
- {
- //判断是否存在残留任务
- if(m_currentTask.upgradeTaskId.IsNullOrEmpty()&&m_currentTask.cPendingState.IsNullOrEmpty()){
- //直接进入查询新任务
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- //处理上个任务
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));
- }
- }
- void CUpgradeTaskFSM::s2_on_exit()
- {
- CancelTimer(1);//更新任务状态计时器
- CancelTimer(2);//查询当前任务计时器
- }
- unsigned int CUpgradeTaskFSM::s2_on_event(FSMEvent* event)
- {
- if (event->iEvt == EVT_TIMER){
- if(event->param1 == 1){
- Task::UpdateTaskStatus* uTask = new Task::UpdateTaskStatus(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(uTask);
- if(Error_Succeed!=rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create UpdateTaskStatus is fail,%d",(int)rc);
- ScheduleTimer(1,60*1000);//继续更新任务状态
- }
- }else if(event->param1 == 2){
- Task::QueryCurrTask* qTask = new Task::QueryCurrTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
- if(Error_Succeed!=rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create QueryCurrTask is fail,%d",(int)rc);
- ScheduleTimer(2,4*60*1000);//继续查询当前任务
- }
- }
- }else if (event->iEvt == Event_DealCurrTask)
- {
- //处理运行时文件异常记录的情况
- if (m_currentTask.task_type.IsNullOrEmpty()) {
- m_currentTask.task_type = "U";//兼容旧版本字段无值的情况,默认是升级模式
- }
- if (m_currentTask.task_type.Compare("U") == 0) {
- if (m_currentTask.upgradeTaskId.IsNullOrEmpty() || m_currentTask.createTaskVersion.IsNullOrEmpty()
- || m_currentTask.cPendingState.IsNullOrEmpty() || m_currentTask.pack_name.IsNullOrEmpty()) {
- //有任务时,则4个字段不能为空,否则任务有问题
- CSimpleStringA errStr = CSimpleStringA::Format("current Task param is null, clear this task, upgradeTaskId=[%s],createTaskVersion=[%s],cPendingState=[%s],PackName=[%s]",
- m_currentTask.upgradeTaskId.GetData(), m_currentTask.createTaskVersion.GetData(), m_currentTask.cPendingState.GetData(), m_currentTask.pack_name.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK, errStr.GetData());
- if (ClearCurrTaskInfo()) {
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
- }
- }
- }
- else if (m_currentTask.task_type.Compare("R") == 0) {
- if (m_currentTask.upgradeTaskId.IsNullOrEmpty() || m_currentTask.createTaskVersion.IsNullOrEmpty()
- || m_currentTask.cPendingState.IsNullOrEmpty()) {
- //有任务时,则3个字段不能为空,否则任务有问题
- CSimpleStringA errStr = CSimpleStringA::Format("current Task param is null, clear this task, upgradeTaskId=[%s],createTaskVersion=[%s],cPendingState=[%s]",
- m_currentTask.upgradeTaskId.GetData(), m_currentTask.createTaskVersion.GetData(), m_currentTask.cPendingState.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK, errStr.GetData());
- if (ClearCurrTaskInfo()) {
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
- }
- }
- }
- else {
- CSimpleStringA errStr = CSimpleStringA::Format("current Task param task_type=[%s], param is Not Supported, clear this task",m_currentTask.task_type.GetData());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK, errStr.GetData());
- if (ClearCurrTaskInfo()) {
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("clear current task is fail 1,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
- }
- }
- //任务已到最终状态
- if(m_currentTask.cPendingState=="T"||m_currentTask.cPendingState=="C"||m_currentTask.cPendingState=="X"){
- //取消任务C和切换任务T时,更新任务状态
- Task::UpdateTaskStatus* uTask = new Task::UpdateTaskStatus(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(uTask);
- if(Error_Succeed!=rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create UpdateTaskStatus is fail,%d",(int)rc);
- ScheduleTimer(1,60*1000);//继续更新任务状态
- }
- }else{
- //当前任务
- if(m_currentTask.createTaskVersion!=m_currentVersion.ToString()){
- //比较遗留任务的创建版本号是否和现在版本一致,不一致,则可能出现拷贝别的终端文件或者已经手工改了别的版本引发,这种情况下自动清理此次任务。
- 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());
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_RUNINFO_TASK,errStr.GetData());
- if(ClearCurrTaskInfo()){
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 2,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_DealCurrTask));//继续处理上个任务
- }
- }else{
- Task::QueryCurrTask* qTask = new Task::QueryCurrTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
- if(Error_Succeed!=rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s2 create QueryCurrTask is fail,%d",(int)rc);
- ScheduleTimer(2,4*60*1000);//继续查询当前任务
- }
- }
- }
- }else if(event->iEvt == Event_EndUpdateTask){
- //更新任务状态返回结果
- UpdateTaskStatusEvent* pEvent = (UpdateTaskStatusEvent*)event;
- if(pEvent->isSucc){
- //告警回滚和升级成功
- if(m_currentTask.cPendingState=="T"){
- if (isTerminalInstall()) {
- //安装情况
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentVersion.ToString();//当前的版本
- up.CurrentVersion = m_currentVersion.ToString();//当前的版本
- }
- else {
- up.installVersion = m_currentDepVersion.GetData();//安装适配器版本
- up.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
- }
- up.cInstallState = "A";
- up.strInstallComment = "启动成功";
- SendUpgradeTaskProgress(up, UpgradeMgr_START_ID);
- upgradeSuccStateBroadCast();//广播告知升级成功
- }
- else {
- //非安装情况
- if (m_currentTask.NewVersion == m_currentVersion.ToString() ||
- m_currentTask.depNewVersion == m_currentDepVersion ||
- (m_currentTask.NewVersion == "" && m_currentTask.depNewVersion == "")) {
- //安装成功
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentVersion.ToString();//当前的版本
- up.CurrentVersion = m_currentVersion.ToString();//当前的版本
- }
- else {
- up.installVersion = m_currentDepVersion.GetData();//安装适配器版本
- up.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
- }
- up.cInstallState = "A";
- up.strInstallComment = "启动成功";
- if (m_currentTask.task_type.Compare("U") == 0) {
- SendUpgradeTaskProgress(up, UpgradeMgr_START_ID);
- }
- else {
- SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_START_ID);
- }
- upgradeSuccStateBroadCast();//广播告知升级成功
- }
- else {
- //回滚
- struct CTaskProcess upRoll;
- upRoll.strPackName = m_currentTask.pack_name;//安装包名
- if (m_currentTask.depNewVersion.IsNullOrEmpty()) {
- upRoll.installVersion = m_currentTask.NewVersion.GetData();//任务升级后的版本号
- upRoll.CurrentVersion = m_currentVersion.ToString();//当前的版本
- }
- else {
- upRoll.installVersion = m_currentTask.depNewVersion.GetData();//安装适配器版本
- upRoll.CurrentVersion = m_currentDepVersion.GetData();//适配器当前版本
- }
- upRoll.cInstallState = "R";
- upRoll.strInstallComment = "自动倒回";
- if (m_currentTask.task_type.Compare("U") == 0) {
- SendUpgradeTaskProgress(upRoll, UpgradeMgr_START_ID, " RTA5667");
- }
- else {
- SendUpgradeTaskProgress(upRoll, UpgradeMgr_ROLLBACK_START_ID, " RTA5672");
- }
- }
- }
- ErrorCodeEnum rc = SetRunSucceed(m_currentTask.pack_name.GetData());
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("SetRunSucceed is fail: %d", (int)rc);
- }
-
- }
- //清除运行时文件和内存任务,跳转到S3
- if(ClearCurrTaskInfo()){
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndUpdateTask clear current task is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new UpdateTaskStatusEvent(true));//继续更新任务状态
- }
- }else{
- ScheduleTimer(1,60*1000);//继续更新任务状态
- }
- }else if(event->iEvt == Event_EndQueryCurrTask){
- //查询当前任务返回结果
- QueryCurrTaskEvent* pEvent = (QueryCurrTaskEvent*)event;
- if(pEvent->isSucc){
- if(pEvent->isTask_valid){
- //根据不同任务状态值,进入不同阶段。U:下载阶段,I:安装阶段,回退检查,S切换阶段
- if(m_currentTask.cPendingState=="U"){
- return 4;//下载
- }else if(m_currentTask.cPendingState=="I"){
- if (m_currentTask.task_type.Compare("R") == 0) {
- //因回退不进入S阶段,故加入切换标志。
- m_bSwitchFlag = true;
- }
- return 5;//安装,回退检查
- }else if(m_currentTask.cPendingState=="S"){
- //加入切换标志,用于切换时判断是否是切换进入的流程。
- m_bSwitchFlag = true;
- return 6;//切换
- }else{
- //无效状态
- LogWarn(Severity_Middle, Error_Exception, ERR_TASK_INVALID_STATUS_FAIL,CSimpleStringA::Format("invalid pending state : %s",m_currentTask.cPendingState.GetData()).GetData());
- //任务无效,清理任务
- if(ClearCurrTaskInfo()){
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndQueryCurrTask clear current task is fail 2,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new QueryCurrTaskEvent(true,true));//继续清理当前任务
- }
- }
- }else{
- 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());
- //任务无效,清理任务
- if(ClearCurrTaskInfo()){
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndQueryCurrTask clear current task is fail 1,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new QueryCurrTaskEvent(true,false));//继续清理当前任务
- }
- }
- }else{
- ScheduleTimer(2,4*60*1000);//继续查询当前任务
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s3_on_entry()
- {
- //查询新任务:先预查询任务,传送hash,接着查询任务
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("entery S3");
- m_queryNewTaskCount = 0;
- m_strPreTaskId = "";
- m_bNeedHash=0;
- m_fileSM3List="";
- m_fileSM3ListHash="";
- isSendHash=false;
- //预查询任务
- Task::QueryNewPreTask* qTask = new Task::QueryNewPreTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(qTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewPreTask fail,wait 4 min retry ,err=%d",(int)rc);
- ScheduleTimer(1, m_queryNewTaskInterval*1000);//等待4分钟后再次查询是否有新任务
- }
- }
- void CUpgradeTaskFSM::s3_on_exit()
- {
- CancelTimer(1);//预查询任务计时器
- CancelTimer(2);//上传hash计时器
- CancelTimer(3);//继续任务计时器
- m_queryNewTaskCount =0;
- m_strPreTaskId = "";
- m_bNeedHash=0;
- m_fileSM3List="";
- m_fileSM3ListHash="";
- isSendHash=false;
- }
- unsigned int CUpgradeTaskFSM::s3_on_event(FSMEvent* event)
- {
- if(event->iEvt == EVT_TIMER){
-
- if(event->param1 == 1){
- //发起预查询任务
- Task::QueryNewPreTask* nTask = new Task::QueryNewPreTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewPreTask fail,wait [%d]s retry ,err=%d", m_queryNewTaskInterval, (int)rc);
- ScheduleTimer(1, m_queryNewTaskInterval *1000);//等待4分钟后再次查询是否有新任务
- }
- }else if(event->param1 == 2){
- //上传hash
- Task::SendSM3Task* SM3Task = new Task::SendSM3Task(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(SM3Task);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create SendSM3Task fail,err=%d",(int)rc);
- ScheduleTimer(2, 60*1000);//等待1分钟过后再次发送
- }
- }else if(event->param1 == 3){
- //继续任务
- Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
- ScheduleTimer(3, m_queryNewTaskInterval *1000);//等待4分钟过后再次发送
- }
- }
- }
- else if(event->iEvt == Event_EndPrePoll){
- QueryNewPreTaskEvent* pEvent = (QueryNewPreTaskEvent*)event;
- if(pEvent->isSucc){
- if(m_strPreTaskId.IsNullOrEmpty()){
- m_queryNewTaskCount++;
- if(m_queryNewTaskCount>=QUERY_NO_TASK_WARN_LIMIT){
- LogWarn(Severity_Low, Error_Exception, ERR_TASK_QUERY_NO_TASK,"QueryNewPreTask 15 times succ,no new task");
- m_queryNewTaskCount=0;
- }
- if (isAuthSucc()) {
- ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次查询是否有新任务
- }
- else {
- ScheduleTimer(1, 30 * 1000);//等待30s后再次查询是否有新任务
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewPreTask succ, task_id=%s",m_strPreTaskId.GetData());
- if(m_bNeedHash){
- //预查询成功
- if(isSendHash){
- //之前发送hash成功,直接开始继续任务查询线程
- Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
- ScheduleTimer(3, 60*1000);//再次查询是否有新任务
- }
- }else{
- //之前未发送hash成功,开始计算hash线程
- Task::SendSM3Task* SM3Task = new Task::SendSM3Task(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(SM3Task);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create SendSM3Task fail,err=%d",(int)rc);
- ScheduleTimer(2, 60*1000);//等待一分钟过后再次发送
- }
- }
- }else{
- //不需要hash,直接继续查询新任务
- Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
- ScheduleTimer(3, 60*1000);//等待4分钟后再次查询是否有新任务
- }
- }
- }
- }else{
- //预查询失败
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewPreTask fail,wait 4 min retry");
- if (isAuthSucc()) {
- ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次预查询是否有新任务
- }
- else {
- ScheduleTimer(1, 30 * 1000);//等待30s后再次查询是否有新任务
- }
-
- }
- }
- else if(event->iEvt == Event_EndSendSM3Task){
- Task::QueryNewContinueTask* nTask = new Task::QueryNewContinueTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s3 create QueryNewContinueTask fail,err=%d",(int)rc);
- ScheduleTimer(3, 60*1000);//等待4分钟后再次查询是否有新任务
- }
- }
- else if(event->iEvt == Event_EndContinuePoll){
- QueryNewContinueTaskEvent* pEvent = (QueryNewContinueTaskEvent*)event;
- if(pEvent->retParam == 0){
- //查询失败,继续查询
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask fail,wait [%d]s retry",m_queryNewTaskInterval);
- if (isAuthSucc()) {
- ScheduleTimer(3, m_queryNewTaskInterval * 1000);//等待4分钟后再次查询继续新任务
- }
- else {
- ScheduleTimer(3, 30 * 1000);//等待30s后再次查询继续新任务
- }
- }else if(pEvent->retParam == 1){
- //查询成功,跳到下一个状态,写入运行时文件
- bool isWriteOk=false;
- while(true){
- if(SetRunConfigStrValue("upgradeTask","NewVersion","")!=Error_Succeed){
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "depNewVersion", "") != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "CreateTaskVersion", m_currentTask.createTaskVersion.GetData()) != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "UpgradeTaskId", m_currentTask.upgradeTaskId.GetData()) != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "taskType", m_currentTask.task_type.GetData()) != Error_Succeed) {
- break;
- }
- if (m_currentTask.task_type.Compare("U") == 0) {
- if (SetRunConfigStrValue("upgradeTask", "PendingState", "U") != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "PackName", m_currentTask.pack_name.GetData()) != Error_Succeed) {
- break;
- }
- }else if(m_currentTask.task_type.Compare("R") == 0){
- if (SetRunConfigStrValue("upgradeTask", "PendingState", "I") != Error_Succeed) {
- break;
- }
- if (SetRunConfigStrValue("upgradeTask", "PackName", "") != Error_Succeed) {
- break;
- }
- }
- isWriteOk=true;
- break;
- }
- if(isWriteOk){
- if (m_currentTask.task_type.Compare("U") == 0) {
- //升级下载
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "D";
- up.strInstallComment = "正在下载";
- SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID);
- m_currentTask.cPendingState = "U";//改变内存变量为U
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDownload));//进入S4
- }
- else {
- //回退
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "B";
- up.strInstallComment = "正在回退";
- SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID);
- m_currentTask.cPendingState = "I";//改变内存变量为I
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartInstall));//进入S5
- }
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndPoll write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒,继续创建
- PostEventFIFO(new QueryNewContinueTaskEvent(1));//继续创建任务
- }
- }else{
- //跳出,重新预检查任务
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("QueryNewContinueTask fail,jump to PreTask");
- if (isAuthSucc()) {
- ScheduleTimer(1, m_queryNewTaskInterval * 1000);//等待4分钟后再次预查询是否有新任务
- }
- else {
- ScheduleTimer(1, 30 * 1000);//等待30s后再次预查询是否有新任务
- }
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s4_on_entry()
- {
- //下载升级包
- m_bTaskCancel = false;//默认任务非取消
- m_downloadBreakOffCount = 0;
- if(m_bDownloadIdle){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CallState is not O , download is break off , wait a moment");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_Download_Idle));//进入不可下载状态
- }else{
- Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
- ScheduleTimer(1, 15*1000);//等待15秒再试
- }
- }
- ScheduleTimer(2, 30*1000);//启动查询任务是否有效
- }
- void CUpgradeTaskFSM::s4_on_exit()
- {
- CancelTimer(1);//正常下载计时器
- CancelTimer(2);//查询任务是否取消计时器
- CancelTimer(3);//外部状态中止下载计时器
- }
- unsigned int CUpgradeTaskFSM::s4_on_event(FSMEvent* event)
- {
-
- if (event->iEvt == EVT_TIMER)
- {
- if(event->param1 == 1){
- Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
- ScheduleTimer(1, 15*1000);//再次下载升级包
- }
- }else if(event->param1 == 2){
- Task::QueryTaskStatus* dTask = new Task::QueryTaskStatus(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create QueryTaskStatus fail,err=%d",(int)rc);
- ScheduleTimer(2, 30*1000);//再次查询任务是否有效
- }
- }else if(event->param1 == 3){
- //无效状态
- if(m_bDownloadIdle){
- if (m_downloadBreakOffCount > 60) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CallState is not O , download is break off , wait a moment");
- m_downloadBreakOffCount = 0;
- }
- else {
- m_downloadBreakOffCount++;
- }
- ScheduleTimer(3,10*1000);//等待下次是否空闲
- }else{
- Task::DownloadPackTask* dTask = new Task::DownloadPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s4 create DownloadPackTask fail,err=%d",(int)rc);
- ScheduleTimer(3, 10*1000);//等待下次是否空闲
- }
- }
- }
- }else if (event->iEvt == Event_EndQueryTaskStatus){
- QueryTaskStatusEvent* pEvent = (QueryTaskStatusEvent*)event;
- if(pEvent->isSucc){
- if(pEvent->isTask_valid){
- ScheduleTimer(2, 30*1000);//有效,再次查询任务是否有效
- m_bTaskCancel = false;
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("query upgradeTask is cancel,set m_bTaskCancel=true");
- m_bTaskCancel = true;//取消下载,结束查询任务是否有效计时器
- }
- }else{
- ScheduleTimer(2, 30*1000);//通讯失败,再次查询任务是否有效
- }
- }else if (event->iEvt == Event_EndDownload){
- DownloadPackTaskEvent* pEvent = (DownloadPackTaskEvent*)event;
- if(pEvent->isSucc){
- if(SetRunConfigStrValue("upgradeTask","PendingState","I")==Error_Succeed){
- //下载成功
- m_currentTask.cPendingState = "I";//改变内存变量为I
- if(m_currentTask.pack_version.IsNullOrEmpty()){
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID)("体系外下载成功");
- }else{
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID)("终端版本下载成功");
- }
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartInstall));//进入S5
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndDownload write runinfo is fail,retry in 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new DownloadPackTaskEvent(true));//继续写运行时文件
- }
-
- }else{
- if (m_currentTask.pack_version.IsNullOrEmpty()) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_OUTSIDE_SYSTEM_DOWNLOAD_ID).setResultCode("RTA5634")("体系外下载失败,通讯报错");
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER).setLogCode(UpgradeMgr_VERSION_DOWNLOAD_ID).setResultCode("RTA5633")("终端版本下载失败,通讯报错");
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("download pack is fail , wait for 2 min retry download");
- ScheduleTimer(1, 120*1000);//下载失败,等2分钟,再次下载任务
- }
-
- }else if (event->iEvt == Event_Download_Fail){
- DownloadPackTaskFailEvent* pEvent = (DownloadPackTaskFailEvent*)event;
- //写入运行时文件,状态为C
- if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
-
- //告警下载失败
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = pEvent->errMsg.c_str();
- SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID,"RTA5660");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask download is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_Download_Fail write runinfo is fail,retry in 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new DownloadPackTaskFailEvent(pEvent->errMsg));//继续写运行时文件
- }
- }else if (event->iEvt == Event_Download_Idle){
- ScheduleTimer(3,10*1000);//等待下次是否空闲
- }else if (event->iEvt == Event_CancelTask){
- //取消任务,清理任务
- if(ClearCurrTaskInfo()){
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = "任务策略已取消";
- SendUpgradeTaskProgress(up,UpgradeMgr_DOWNLOAD_ID,"RTA5661");
-
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask is cancel,prepare to s3");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry in 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_CancelTask));//继续取消任务
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s5_on_entry()
- {
- //停止播放广告和音频
- Task::StopMediaPlayTask* nTask = new Task::StopMediaPlayTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create StopMediaPlayTask fail,err=%d",(int)rc);
- ScheduleTimer(1, 30*1000);//等待30秒再试
- }
- }
- void CUpgradeTaskFSM::s5_on_exit()
- {
- CancelTimer(1);//停止广播和声音计时器
- CancelTimer(2);//解压计时器
- CancelTimer(3);//安装计时器
- CancelTimer(4);//等待跳转切换计时器
- CancelTimer(5);//回退检查计时器
- }
- unsigned int CUpgradeTaskFSM::s5_on_event(FSMEvent* event)
- {
- if(event->iEvt == EVT_TIMER){
- if(event->param1 == 1){
- //再次发起任务查询
- Task::StopMediaPlayTask* nTask = new Task::StopMediaPlayTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(nTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create StopMediaPlayTask fail,err=%d",(int)rc);
- ScheduleTimer(1, 30*1000);//等待30秒再停止播放广告和音频
- }
- }else if(event->param1 == 2){
- Task::UnzipPackTask* iTask = new Task::UnzipPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s5 create UnzipPackTask fail,err=%d",(int)rc);
- ScheduleTimer(2, 30*1000);//等待30秒再解压包
- }
- }else if(event->param1 == 3){
- BOOL doInstall = true;
- if(!m_startFlag) //非强制安装
- {
- if (m_currentTask.pack_version.GetLength() == 0) //体系外升级
- {
- CSimpleStringA strState;
- ErrorCodeEnum err = m_pEntity->GetFunction()->GetSysVar("UIState", strState);
- if (err == Error_Succeed && strState != CSimpleStringA("M")) //非主界面不安装
- {
- doInstall = false;
- }
- }
- }
- //对于终端初始化安装时,直接通过。
- if (isTerminalInstall()) {
- doInstall = true;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask terminal new install");
- }
- if (doInstall)
- {
- //解压后判断是什么类型升级
- judgeTaskClass();
- Task::InstallPackTask* iTask = new Task::InstallPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask fail,err=%d", (int)rc);
- ScheduleTimer(3, 30 * 1000);//等待30秒再安装
- }
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 UIState is not M , create InstallPackTask wait for the next time");
- ScheduleTimer(3, 30 * 1000);//等待30秒再安装
- }
- }
- else if (event->param1 == 4) {
- //已安装成功,直接进入切换状态
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask succ, enter into S6");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
- }
- else if (event->param1 == 5) {
- Task::RollBackCheckTask* iTask = new Task::RollBackCheckTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create RollBackCheckTask fail,err=%d", (int)rc);
- ScheduleTimer(5, 30 * 1000);//等待30秒再次检查
- }
- }
- }
- else if(event->iEvt == Event_EndStopMediaPlayTask){
- StopMediaPlayTaskEvent* pEvent = (StopMediaPlayTaskEvent*)event;
- if(pEvent->isSucc){
- if (m_currentTask.task_type.Compare("U") == 0) {
- //开始解压
- Task::UnzipPackTask* iTask = new Task::UnzipPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create UnzipPackTask fail,err=%d", (int)rc);
- ScheduleTimer(2, 30 * 1000);//等待30秒再解压包
- }
- }
- else if (m_currentTask.task_type.Compare("R") == 0) {
- //回退检查
- Task::RollBackCheckTask* iTask = new Task::RollBackCheckTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create RollBackCheckTask fail,err=%d", (int)rc);
- ScheduleTimer(5, 30 * 1000);//等待30秒再检查
- }
- }
- }else{
- ScheduleTimer(1, 30*1000);//等待30秒再停止播放广告和音频
- }
- }
- else if (event->iEvt == Event_EndUnzipPackTask){
- UnzipPackTaskEvent* pEvent = (UnzipPackTaskEvent*)event;
- if(pEvent->isSucc){
- //开始安装
- BOOL doInstall = true;
- if (!m_startFlag) //非强制安装
- {
- if (m_currentTask.pack_version.GetLength() == 0) //体系外升级
- {
- CSimpleStringA strState;
- ErrorCodeEnum err = m_pEntity->GetFunction()->GetSysVar("UIState", strState);
- if (err == Error_Succeed && strState != CSimpleStringA("M")) //非主界面不安装
- {
- doInstall = false;
- }
- }
- }
- //对于终端初始化安装时,直接通过。
- if (isTerminalInstall()) {
- doInstall = true;
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask terminal new install");
- }
- if (doInstall)
- {
- //解压后判断是什么类型升级
- judgeTaskClass();
- Task::InstallPackTask* iTask = new Task::InstallPackTask(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(iTask);
- if (rc != Error_Succeed) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 create InstallPackTask fail,err=%d", (int)rc);
- ScheduleTimer(3, 30 * 1000);//等待30秒再安装
- }
- }
- else{
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("s5 UIState is not M , create InstallPackTask wait for the next time");
- ScheduleTimer(3, 30 * 1000);//等待30秒再安装
- }
- }else{
- if(m_currentTask.stop_media_play){
- //恢复广告和音频播放
- ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
- if(Error_Succeed != rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("unzip fail set UpdateState to 0 fail, err=%d",(int)rc);
- }
- }
- //解压失败,写入运行时文件,状态为C
- if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
-
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = "解压失败";
- SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5662");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("unzip pack is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndUnzipPackTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new UnzipPackTaskEvent(false));//继续写运行时文件
- }
-
- }
- }
- else if (event->iEvt == Event_EndInstallPackTask){
- if(m_currentTask.stop_media_play){
- //恢复广告和音频播放
- ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
- if(Error_Succeed != rc){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("EndInstallPackTask set UpdateState to 0 fail, err=%d",(int)rc);
- }
- }
- InstallPackTaskEvent* pEvent = (InstallPackTaskEvent*)event;
- if(pEvent->isSucc){
- //安装成功进入切换,设置状态为S和新版本号
- //写入运行时文件
- bool isWriteOk=false;
- while(true){
- if (!m_TempDepUpgradeFlag) {
- if (SetRunConfigStrValue("upgradeTask", "NewVersion", m_currentTask.NewVersion.GetData()) != Error_Succeed) {
- break;
- }
- }
- else {
- if (SetRunConfigStrValue("upgradeTask", "depNewVersion", m_currentTask.depNewVersion.GetData()) != Error_Succeed) {
- break;
- }
- }
- if(SetRunConfigStrValue("upgradeTask","PendingState","S")!=Error_Succeed){
- break;
- }
- isWriteOk=true;
- break;
- }
- if(isWriteOk){
- //告警安装
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if(!m_currentTask.NewVersion.IsNullOrEmpty()){
- up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
- }else if(!m_currentTask.depNewVersion.IsNullOrEmpty()){
- up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
- }else {
- up.installVersion = m_currentVersion.ToString();//当前版本号
- }
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "W";
- up.strInstallComment = "安装成功";
- SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID);
- m_currentTask.cPendingState = "S";//改变内存变量S
- //modify by lwt 修改为非兜底升级时等待一段时间再进入切换状态。
- if (m_startFlag) {
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
- }
- else {
- ScheduleTimer(4, 20 * 1000);//等待20秒再进入切换状态
- }
-
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new InstallPackTaskEvent(true,"",0));//继续写运行时文件
- }
- }else{
- if(pEvent->failStatus==0){
- //安装失败,设置状态为C
- if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
-
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = pEvent->errMsg;//错误信息
- SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5663");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("install pack is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new InstallPackTaskEvent(false,pEvent->errMsg,0));//继续写运行时文件
- }
- }else if(pEvent->failStatus==-1){
- //安装失败,设置状态为X 未知
- if(SetRunConfigStrValue("upgradeTask","PendingState","X")==Error_Succeed){
-
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "X";
- up.strInstallComment = pEvent->errMsg;//错误信息
- SendUpgradeTaskProgress(up,UpgradeMgr_INSTALL_ID,"RTA5664");
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("install pack is fail ,prepare to s2");
- m_currentTask.cPendingState = "X";//改变内存变量X
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("Event_EndInstallPackTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new InstallPackTaskEvent(false,pEvent->errMsg,-1));//继续写运行时文件
- }
- }
- }
- }
- else if (event->iEvt == Event_EndRollBackCheckTask) {
- if (m_currentTask.stop_media_play) {
- //恢复广告和音频播放
- ErrorCodeEnum rc = m_pEntity->GetFunction()->SetSysVar("UpdateState", "0", true);
- if (Error_Succeed != rc) {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("EndInstallPackTask set UpdateState to 0 fail, err=%d", (int)rc);
- }
- }
- RollBackCheckTaskEvent* pEvent = (RollBackCheckTaskEvent*)event;
- if (pEvent->isSucc) {
- bool isWriteOk = false;
- while (true) {
- if (!m_TempDepUpgradeFlag) {
- if (SetRunConfigStrValue("upgradeTask", "NewVersion", m_currentTask.NewVersion.GetData()) != Error_Succeed) {
- break;
- }
- }
- else {
- if (SetRunConfigStrValue("upgradeTask", "depNewVersion", m_currentTask.depNewVersion.GetData()) != Error_Succeed) {
- break;
- }
- }
- isWriteOk = true;
- break;
- }
- if (isWriteOk) {
- m_currentTask.cPendingState = "S";//改变内存变量S
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查成功");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartSwitch));//进入S6
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_EndRollBackCheckTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new RollBackCheckTaskEvent(true, "", ""));//继续写运行时文件
- }
- }
- else {
- //失败
- if (pEvent->failReason.compare("X") != 0) {
- //回退失败,设置状态为C
- if (SetRunConfigStrValue("upgradeTask", "PendingState", "C") == Error_Succeed) {
- //回滚失败取消
- struct CTaskProcess up;
- up.strPackName = "";//安装包名
- up.installVersion = m_currentTask.pack_version;//回退的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = pEvent->errMsg.GetData();//错误信息
- SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID,"RTA5668");
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackCheck is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查失败");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_EndRollBackCheckTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new RollBackCheckTaskEvent(false, pEvent->errMsg, "C"));//继续写运行时文件
- }
- }
- else if (pEvent->failReason.compare("X")==0) {
- //安装失败,设置状态为X 未知
- if (SetRunConfigStrValue("upgradeTask", "PendingState", "X") == Error_Succeed) {
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = "";//安装包名
- up.installVersion = m_currentTask.pack_version;//回退的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "X";
- up.strInstallComment = pEvent->errMsg.GetData();//错误信息
- SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_ID,"RTA5669");
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("RollBackCheck is fail ,prepare to s2");
- m_currentTask.cPendingState = "X";//改变内存变量X
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_USER)("终端回退版本检查失败");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }
- else {
- DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Event_EndRollBackCheckTask write runinfo is fail,retry int 5's");
- Sleep(5 * 1000);//等待五秒
- PostEventFIFO(new RollBackCheckTaskEvent(false, pEvent->errMsg, "X"));//继续写运行时文件
- }
- }
- }
- }
- return 0;
- }
- void CUpgradeTaskFSM::s6_on_entry()
- {
- //进入切换处理流程:不同类型包判断不同
- //时间长,需要判断后台是否取消任务
- if (CheckIfCanSwitchNow())
- {
- ScheduleTimer(2,1000);//进行版本切换操作
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("not applicable time to switch, retry in 20's");
- ScheduleTimer(1, 20*1000);//继续等待
- }
- ScheduleTimer(3, 30*1000);//启动查询任务是否有效
- }
- void CUpgradeTaskFSM::s6_on_exit()
- {
- CancelTimer(1);//判断是否切换时间计时器
- CancelTimer(2);//切换运行时文件写入计时器
- CancelTimer(3);//任务取消计时器
- CancelTimer(4);//切换重启写入active文件计时器
- CancelTimer(5);//active文件写入失败写运行时计时器
- m_bSwitchFlag = false;//切换标志重置。
- }
- unsigned int CUpgradeTaskFSM::s6_on_event(FSMEvent* event)
- {
- if (event->iEvt == EVT_TIMER)
- {
- if(event->param1==1)
- {
- //进入切换处理流程:不同类型包判断不同
- if (CheckIfCanSwitchNow())
- {
- ScheduleTimer(2,1000);//进行版本切换操作
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("not applicable time to switch, retry in 20's");
- ScheduleTimer(1, 20*1000);//继续等待切换时机
- }
- }else if(event->param1==2){
-
- //修改运行时文件状态T
- if(SetRunConfigStrValue("upgradeTask","PendingState","T")==Error_Succeed){
-
- //告警切换
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if (!m_currentTask.NewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
- }else if (!m_currentTask.depNewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
- }else {
- up.installVersion = m_currentVersion.ToString();//当前版本号
- }
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "S";
- up.strInstallComment = "已设为启动版本";
- if (m_currentTask.task_type.Compare("U")==0) {
- SendUpgradeTaskProgress(up,UpgradeMgr_SWTICH_ID);
- }
- else{
- SendUpgradeTaskProgress(up,UpgradeMgr_ROLLBACK_SWTICH_ID);
- }
- m_currentTask.cPendingState = "T";//改变内存变量
- ScheduleTimer(4,5*1000);//等待告警上报,准备修改active文件,进行切换
-
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("switch write runinfo is fail,retry in 10's");
- ScheduleTimer(1, 10*1000);//继续等待下次切换机会再重试
- }
-
- }else if(event->param1==3){
- Task::QueryTaskStatus* dTask = new Task::QueryTaskStatus(this);
- ErrorCodeEnum rc = m_pEntity->GetFunction()->PostThreadPoolTask(dTask);
- if(rc!=Error_Succeed){
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("s6 create QueryTaskStatus fail,err=%d",(int)rc);
- ScheduleTimer(3, 30*1000);//再次查询任务是否有效
- }
- }else if(event->param1==4){
- //修改active文件
- if (!m_TempDepUpgradeFlag) {
- if (UpgradeToNewVersion() == Error_Succeed) {
- SwitchUpgradeNow();//切换版本
- }
- else {
- ScheduleTimer(5, 3 * 1000);//UpgradeToNewVersion执行失败后写运行时计时器
- }
- }
- else {
- if (UpgradeDepToNewVersion() == Error_Succeed) {
- SwitchUpgradeDepNow();//适配器切换版本
- }
- else {
- ScheduleTimer(5, 3 * 1000);//UpgradeToDepNewVersion执行失败后写运行时计时器
- }
- }
- }else if(event->param1==5){
-
- if(SetRunConfigStrValue("upgradeTask","PendingState","C")==Error_Succeed){
- //告警切换失败
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- if (!m_currentTask.NewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentTask.NewVersion;//任务升级后的版本号
- }else if (!m_currentTask.depNewVersion.IsNullOrEmpty()) {
- up.installVersion = m_currentTask.depNewVersion;//升级后的适配器版本号
- }else {
- up.installVersion = m_currentVersion.ToString();//当前版本号
- }
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = "更新active文件失败";//错误信息
- if (m_currentTask.task_type.Compare("U")==0) {
- SendUpgradeTaskProgress(up,UpgradeMgr_SWTICH_ID,"RTA5665");
- }
- else {
- SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_SWTICH_ID, "RTA5670");
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("UpgradeToNewVersion is fail ,prepare to s2");
- m_currentTask.cPendingState = "C";//改变内存变量C
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartDealTask));//进入S2
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("UpgradeToNewVersion fail, write runinfo is fail,retry in 10's");
- ScheduleTimer(5,10*1000);//继续重试写入运行时
- }
- }
- }else if (event->iEvt == Event_EndQueryTaskStatus){
- QueryTaskStatusEvent* pEvent = (QueryTaskStatusEvent*)event;
- if(pEvent->isSucc){
- if(pEvent->isTask_valid){
- ScheduleTimer(3, 30*1000);//有效,再次查询任务是否有效
- }else{
- //无效,清理任务
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("query upgradeTask is cancel");
- if(ClearCurrTaskInfo()){
- //告警下载取消
- struct CTaskProcess up;
- up.strPackName = m_currentTask.pack_name;//安装包名
- up.installVersion = m_currentTask.pack_version;//安装的版本
- up.CurrentVersion = getAlarmCurrVersion();//当前的版本
- up.cInstallState = "C";
- up.strInstallComment = "任务策略已取消";
- if (m_currentTask.task_type.Compare("U")==0) {
- SendUpgradeTaskProgress(up, UpgradeMgr_SWTICH_ID,"RTA5666");
- }
- else {
- SendUpgradeTaskProgress(up, UpgradeMgr_ROLLBACK_SWTICH_ID, "RTA5671");
- }
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("upgradeTask is cancel,prepare to s3");
- PostEventFIFO(new FSMEvent(CUpgradeTaskFSM::Event_StartPoll));//进入S3
- }else{
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("clear current task is fail 1,retry in 5's");
- Sleep(5 * 1000);//等待五秒,继续清理
- PostEventFIFO(new QueryTaskStatusEvent(true,false));//继续取消任务
- }
- }
- }else{
- ScheduleTimer(3, 30*1000);//通讯失败,再次查询任务是否有效
- }
- }
-
- return 0;
- }
- void CUpgradeTaskFSM::s7_on_entry()
- {
- DbgWithLink(LOG_LEVEL_INFO,LOG_TYPE_SYSTEM)("enter disable state , wait framework restart or OS restart");
- }
- void CUpgradeTaskFSM::s7_on_exit()
- {
- }
- unsigned int CUpgradeTaskFSM::s7_on_event(FSMEvent* event)
- {
- return 0;
- }
|