UpgradeTaskFSM.cpp 243 KB

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