ResourceWatcherFSM.cpp 158 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354
  1. #include "stdafx.h"
  2. #include "ResourceWatcherFSM.h"
  3. #include "DeviceBaseClass.h"
  4. #include <string.h>
  5. #include <string>
  6. #include <assert.h>
  7. #include <algorithm>
  8. #include "fileutil.h"
  9. #include <ctime>
  10. #include "CommEntityUtil.hpp"
  11. #include "SpUtility.h"
  12. #include "RestfulFunc.h"
  13. #include <stdio.h>
  14. #include <stdlib.h>
  15. #include "ResourceWatcher_UserCode.h"
  16. #ifdef RVC_OS_LINUX
  17. #include <vector>
  18. #include <dirent.h>
  19. #include <sstream>
  20. #include <fstream>
  21. #include <iostream>
  22. #include "publicFunExport.h"
  23. #include "toolkit.h"
  24. #include "iniutil.h"
  25. #include "osutil.h"
  26. #else
  27. #include <intrin.h>
  28. #include <ShlObj.h>
  29. #include <ShellAPI.h>
  30. #include <Pdh.h>
  31. #include <io.h>
  32. #include <direct.h>
  33. #include "memutil.h"
  34. #include "array.h"
  35. #include <Windows.h>
  36. #include <wintrust.h>
  37. #include <direct.h>
  38. #include <Mscat.h>
  39. #include <Softpub.h>
  40. #include <wlanapi.h>
  41. #include <Netlistmgr.h> //网络检测添加
  42. #include <psapi.h>
  43. #include <tlhelp32.h>
  44. #include "Mmdeviceapi.h"
  45. #include "Propidl.h"
  46. #include "Functiondiscoverykeys_devpkey.h"
  47. #pragma comment(lib, "pdh.lib")
  48. #pragma comment(lib,"winmm.lib" )
  49. #pragma comment(lib, "shell32.lib")
  50. #pragma comment(lib, "Wintrust.lib")
  51. #pragma comment(lib, "crypt32.lib")
  52. #pragma comment(lib, "wlanapi.lib")
  53. #endif
  54. //硬件信息搜集参数
  55. #define DEFAULT_HARDWARE_CHECK_TIME 60 * 1000 //CPU、内存扫描默认间隔,1分钟
  56. #define TIMER_HARDWARE_CHECK 2
  57. //硬盘扫描
  58. #define DEFAULT_DISK_CHECK_TIME 4 * 60 * 60 * 1000 //硬盘默认4小时扫描一次
  59. #define TIMER_DISK_CHECK 3
  60. //保留版本数目
  61. #define DEFAULT_VERSION_SAVED_COUNT 5
  62. #define MAX_VERSION_PATH 256
  63. //一天的秒数,用于计算文件时间
  64. const int SECONDS_OF_DAY = 60 * 60 * 24;
  65. const int VIDEO_DEFAULT_BACKDAYS = 30;
  66. #ifdef RVC_OS_LINUX
  67. #define PROCESS_ITEM 14 //进程CPU信息读取位置参数
  68. const int MAX_MAINLINK_CHECK_TIME = 5000;
  69. const int TIMER_MAINLINK_CHECK = 4;
  70. #else
  71. const int TIMER_ID_CLEARVIDEO_ENHANCE = 1;
  72. const int THOUSAND = 1024;
  73. const int MILLION = 1048576;
  74. #endif // RVC_OS_LINUX
  75. static int hardwareCheckTime = 60 * 1000; //初始化硬件检测间隔
  76. static int hardwareCheckFlag = 1;
  77. static int cpuWarnTime = 0;
  78. static int cpuWarnThreshold = 10;
  79. static int memWarnTime = 0;
  80. static int memWarnThreshold = 10; //初始化CUP、内存告警阈值次数
  81. static int diskCheckTime = 4 * 60 * 60 * 1000; //初始化硬盘检测间隔
  82. static int diskCheckFlag = 1;
  83. #define DIV (1024 * 1024)
  84. #define DAY_DIV (24 * 60 * 60)
  85. #define HOURS_DIV (60 * 60)
  86. #define MINUS_DIV (60)
  87. #ifndef RVC_OS_LINUX
  88. #define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)
  89. #define SafeDeleteArraySize(pData) { if(pData){delete []pData;pData=NULL;} }
  90. #endif // !RVC_OS_LINUX
  91. template<class T>
  92. class TimerOutHelper : public ITimerListener
  93. {
  94. public:
  95. typedef void (T::* FuncTimer)(void* pUserdata);
  96. TimerOutHelper(T* p, FuncTimer pTimerFunc, void* pData, bool bDeleteSelf = false)
  97. : m_pObject(p), m_pUserData(pData), m_pTimer(pTimerFunc), m_bDeleteSelf(bDeleteSelf)
  98. {
  99. }
  100. virtual void OnTimeout(DWORD dwTimerID)
  101. {
  102. (m_pObject->*m_pTimer)(m_pUserData);
  103. if (m_bDeleteSelf)
  104. delete this;
  105. }
  106. private:
  107. void* m_pUserData;
  108. T* m_pObject;
  109. FuncTimer m_pTimer;
  110. bool m_bDeleteSelf;
  111. };
  112. ResourceWatcherFSM::ResourceWatcherFSM(void)
  113. :m_strTerminalNo(true),
  114. m_bFirstRunAfterBoot(FALSE),
  115. m_cpuTop(0)
  116. {
  117. #ifdef RVC_OS_WIN
  118. m_forceStartupWithExeFlag = 0;
  119. m_iNonSignedTotal = 0;
  120. m_bNeedForceDiskCheck = false;
  121. m_DoneDetectAutostart = true;
  122. #endif // RVC_OS_WIN
  123. }
  124. ResourceWatcherFSM::~ResourceWatcherFSM(void)
  125. {
  126. }
  127. void ResourceWatcherFSM::s0_on_entry()
  128. {
  129. LOG_FUNCTION();
  130. #if defined(RVC_OS_WIN)
  131. this->PostEventFIFO(new RunEvent());
  132. BOOL fInstallBySetup(FALSE);
  133. ErrorCodeEnum rc = DetectVTMInstalledBySetup(fInstallBySetup);
  134. if (Error_Succeed == rc && !fInstallBySetup) {
  135. GetEntityBase()->GetFunction()->PostThreadPoolTask(new CreateLinkTask(this));
  136. }
  137. else {
  138. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("detect install type return %s, setup type: %d", SpStrError(rc), fInstallBySetup);
  139. }
  140. #endif //RVC_OS_WIN
  141. }
  142. unsigned int ResourceWatcherFSM::s0_on_event(FSMEvent* e)
  143. {
  144. LOG_FUNCTION();
  145. unsigned int unRes = 0;
  146. switch (e->iEvt)
  147. {
  148. case USER_EVT_RUN:
  149. {
  150. e->SetHandled();
  151. }
  152. break;
  153. default:
  154. {
  155. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Unexpecetd Event(%d)", e->iEvt);
  156. }
  157. break;
  158. }
  159. return unRes;
  160. }
  161. void ResourceWatcherFSM::s0_on_exit()
  162. {
  163. }
  164. void ResourceWatcherFSM::s1_on_entry()
  165. {
  166. LOG_FUNCTION();
  167. }
  168. unsigned int ResourceWatcherFSM::s1_on_event(FSMEvent* e)
  169. {
  170. LOG_FUNCTION();
  171. unsigned int unRes = 0;
  172. e->SetHandled();
  173. return unRes;
  174. }
  175. void ResourceWatcherFSM::s1_on_exit()
  176. {
  177. }
  178. void ResourceWatcherFSM::s2_on_entry()
  179. {
  180. LOG_FUNCTION();
  181. }
  182. unsigned int ResourceWatcherFSM::s2_on_event(FSMEvent* e)
  183. {
  184. LOG_FUNCTION();
  185. unsigned int unRes = 0;
  186. switch (e->iEvt)
  187. {
  188. case USER_EVT_RUN:
  189. {
  190. e->SetHandled();
  191. }
  192. break;
  193. }
  194. return unRes;
  195. }
  196. void ResourceWatcherFSM::s2_on_exit()
  197. {
  198. }
  199. void ResourceWatcherFSM::s3_on_entry()
  200. {
  201. LOG_FUNCTION();
  202. }
  203. unsigned int ResourceWatcherFSM::s3_on_event(FSMEvent* e)
  204. {
  205. unsigned int unRes = 0;
  206. switch (e->iEvt)
  207. {
  208. case USER_EVT_RUN:
  209. {
  210. e->SetHandled();
  211. }
  212. break;
  213. }
  214. return unRes;
  215. }
  216. void ResourceWatcherFSM::s3_on_exit()
  217. {
  218. }
  219. #ifdef RVC_OS_LINUX
  220. bool ResourceWatcherFSM::GetMonitorInfo(CSimpleStringA& outInfo)
  221. {
  222. std::string sucContent, failedContent;
  223. CSimpleStringA strCmd("xrandr | grep \" connected\" | sed -e \"s/\([A-Z0-9]\+\) connected.*/\1/\"");
  224. bool ret = SP::Module::Util::ShellExecute(strCmd.GetData(), sucContent, failedContent);
  225. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{%s}:{%s}{%s}", strCmd.GetData(), sucContent.c_str(), failedContent.c_str());
  226. std::string msg = SP::Utility::ToTrim(sucContent);
  227. SP::Utility::replaceInPlace(msg, "\n", "|");
  228. outInfo = msg.c_str();
  229. return ret;
  230. }
  231. #endif // RVC_OS_LINUX
  232. //首页状态变化时触发的功能
  233. void ResourceWatcherFSM::TriggerAtStatusChanged(bool bMStatus)
  234. {
  235. if (firstMpage)//首次进入首页
  236. {
  237. firstMpage = false;
  238. CSmartPointer<IConfigInfo> spRunConfig;
  239. CSmartPointer<IConfigInfo> spCtSettingConfig;
  240. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  241. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  242. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardwareCheckTime", hardwareCheckTime);
  243. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardwareCheckFlag", hardwareCheckFlag);
  244. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "DiskCheckTime", diskCheckTime);
  245. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "DiskCheckFlag", diskCheckFlag);
  246. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "CpuTooHighPercent", m_cpuHighPercent);
  247. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "CpuWarnThreshold", cpuWarnThreshold);
  248. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "MemoryTooHighPercent", m_memHighPercent);
  249. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "MemWarnThreshold", memWarnThreshold);
  250. spCtSettingConfig->ReadConfigValueInt("ResourceWatcher", "HardDiskTooHighPercent", m_diskHighPercent);
  251. spCtSettingConfig->ReadConfigValueInt(m_pEntity->GetEntityName(), "VerifySignature", m_iVerify);
  252. #if defined(RVC_OS_WIN)
  253. if (m_iVerify == 1) {//文件签名校验
  254. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Verify digitsign...");
  255. VerifyDigitSignTask* task = new VerifyDigitSignTask(this);
  256. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  257. }
  258. #endif //RVC_OS_WIN
  259. if (hardwareCheckTime <= 0) { //非法数值情况下设置为默认一分钟
  260. hardwareCheckTime = DEFAULT_HARDWARE_CHECK_TIME;
  261. }
  262. void* pTmpData = NULL;
  263. ITimerListener* pListener = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::HardwareInfoTimer, pTmpData);
  264. GetEntityBase()->GetFunction()->SetTimer(TIMER_HARDWARE_CHECK, pListener, hardwareCheckTime);
  265. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Set Hardware Timer!");
  266. if (diskCheckFlag > 0) {
  267. GetSystemDiskStatus(); //仅启动时检测一次硬盘状态即可
  268. }
  269. if (diskCheckTime <= 0) {
  270. diskCheckTime = DEFAULT_DISK_CHECK_TIME;
  271. }
  272. void* pTmpData2 = NULL;
  273. ITimerListener* pListener2 = new TimerOutHelper<ResourceWatcherFSM>(this, &ResourceWatcherFSM::DiskCheckTimer, pTmpData2);
  274. GetEntityBase()->GetFunction()->SetTimer(TIMER_DISK_CHECK, pListener2, diskCheckTime);
  275. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Set DISK CHECK Timer!");
  276. //集中配置额外加的清理逻辑
  277. CenterSettingDeleteTask* centerSettingDeleteTask = new CenterSettingDeleteTask(this);
  278. GetEntityBase()->GetFunction()->PostThreadPoolTask(centerSettingDeleteTask);
  279. //终端默认的自动清理逻辑
  280. AutoDeleteFilesTask* autoDeleteTask = new AutoDeleteFilesTask(this);
  281. GetEntityBase()->GetFunction()->PostThreadPoolTask(autoDeleteTask);
  282. #if defined(RVC_OS_LINUX)
  283. if (m_bFirstRunAfterBoot) {
  284. UINT sysVer = 0;
  285. UploadSysVersionInfo(sysVer);
  286. ConfirmWindowEffectHasBeenOpen();
  287. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("fetch os version: %u", sysVer);
  288. if (1031 < sysVer) {
  289. ConfirmDDEClipboardDisable();
  290. ConfirmNotificationCenterDisable();
  291. }
  292. else {
  293. RecoverDDEClipboardEnable();
  294. }
  295. GetEntityBase()->GetFunction()->PostThreadPoolTask(new DetectSoftwareInstallStatusTask(this));
  296. GetEntityBase()->GetFunction()->PostThreadPoolTask(new UploadMonitorInfoTask(this));
  297. AlarmSystemBasicInfo();
  298. }
  299. #endif //RVC_OS_LINUX
  300. }
  301. }
  302. ErrorCodeEnum ResourceWatcherFSM::OnInit()
  303. {
  304. firstMpage = true; //是否首次进入首页
  305. ErrorCodeEnum erroCode = Error_Succeed;
  306. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Complied at: %s %s", __DATE__, __TIME__);
  307. CSmartPointer<IConfigInfo> spRunConfig;
  308. CSmartPointer<IConfigInfo> spCtSettingConfig;
  309. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  310. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  311. erroCode = GetEntityBase()->GetFunction()->GetSystemStaticInfo(m_RvcSysinfo);
  312. m_strTerminalNo = m_RvcSysinfo.strTerminalID;
  313. m_bFirstRunAfterBoot = DetectIsFirstRunAtBoot();
  314. if (m_bFirstRunAfterBoot) {
  315. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("First time to run after system boot.");
  316. }
  317. if (m_bFirstRunAfterBoot) {
  318. #if defined(RVC_OS_WIN)
  319. //GetSystemMetrics (SM_CMONITORS) 计数仅显示可见的显示器
  320. const int screenNums = GetSystemMetrics(SM_CMONITORS);
  321. const int aimScreenNums4Stand2S = 2;
  322. const int aimScreenNums4Other = 1;
  323. if (0 == m_RvcSysinfo.strMachineType.Compare("RVC.Stand2S", true) && screenNums != aimScreenNums4Stand2S) {
  324. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_LACK_OF_MONITOR
  325. , CSimpleStringA::Format("{\"subject\":\"screen_count\",\"machine_type\":\"%s\",\"expect\":%d,\"actual\":%d}"
  326. , m_RvcSysinfo.strMachineType.GetData(), aimScreenNums4Stand2S, screenNums));
  327. }
  328. else if (0 != m_RvcSysinfo.strMachineType.Compare("RVC.Stand2S", true) && screenNums != aimScreenNums4Other) {
  329. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_LACK_OF_MONITOR
  330. , CSimpleStringA::Format("{\"subject\":\"screen_count\",\"machine_type\":\"%s\",\"expect\":%d,\"actual\":%d}"
  331. , m_RvcSysinfo.strMachineType.GetData(), aimScreenNums4Other, screenNums));
  332. }
  333. #endif //RVC_OS_WIN
  334. }
  335. spCtSettingConfig->ReadConfigValueInt(m_pEntity->GetEntityName(), "DisplayCnt", m_iNonSignedDisplay);
  336. if (m_iNonSignedDisplay <= 0)
  337. m_iNonSignedDisplay = 10;
  338. spRunConfig->ReadConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  339. return Error_Succeed;
  340. }
  341. ErrorCodeEnum ResourceWatcherFSM::OnExit()
  342. {
  343. #ifdef RVC_OS_LINUX
  344. GetEntityBase()->GetFunction()->KillTimer(TIMER_HARDWARE_CHECK);
  345. #endif // RVC_OS_LINUX
  346. return Error_Succeed;
  347. }
  348. void ResourceWatcherFSM::AfterInit()
  349. {
  350. #if defined(RVC_OS_WIN)
  351. if (m_bFirstRunAfterBoot) {
  352. DetectAutoStartupCover();
  353. DetectWallpaperAndWarn();
  354. ClearDesktopFileTask* task = new ClearDesktopFileTask(this);
  355. GetEntityBase()->GetFunction()->PostThreadPoolTask(task);
  356. }
  357. DetectVersionHasChangedAndWarnCover();
  358. #endif //RVC_OS_WIN
  359. }
  360. void ResourceWatcherFSM::LinkDetect(int detectType, const char* url, bool& status, unsigned int& delay, int warnFlag)
  361. {
  362. string tUrl = url;
  363. string host = "http://";
  364. int flag = 0;
  365. unsigned int tInterval = 0;
  366. string msg;
  367. if (tUrl.find("http") == string::npos) {
  368. tUrl = host + tUrl;
  369. }
  370. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Check url:[%s].", tUrl.c_str());
  371. ULLINT begin, end;
  372. begin = SP::Module::Comm::RVCGetTickCount();
  373. int curFlag = HttpProbe(tUrl, msg, 5);
  374. end = SP::Module::Comm::RVCGetTickCount();
  375. tInterval = end - begin;
  376. if (curFlag > 0 && curFlag < 400) {
  377. flag = true;
  378. }
  379. else {
  380. flag = false;
  381. }
  382. if (flag == false) {
  383. status = false;
  384. }
  385. else {
  386. status = true;
  387. }
  388. delay = tInterval > 0 ? tInterval:1;
  389. }
  390. ErrorCodeEnum ResourceWatcherFSM::BizLinkDetect(
  391. SpReqAnsContext<ResourceWatcherService_BizLinkDetect_Req, ResourceWatcherService_BizLinkDetect_Ans>::Pointer ctx)
  392. {
  393. LOG_FUNCTION();
  394. ErrorCodeEnum ec = Error_Succeed;
  395. int detectType = ctx->Req.protocol;
  396. CSimpleStringA url = ctx->Req.bizLink;
  397. bool linkStatus = false;
  398. unsigned int delay = 0;
  399. LinkDetect(detectType, url.GetData(), linkStatus, delay);
  400. ctx->Ans.bizLinkStatus = linkStatus;
  401. ctx->Ans.bizLinkDelayMS = delay;
  402. ctx->Ans.intParam = 0;
  403. CSimpleStringA warn;
  404. if (!linkStatus) {
  405. warn = CSimpleStringA::Format("BizLink disconnected[%s].", url.GetData());
  406. }
  407. else
  408. {
  409. warn = CSimpleStringA::Format("BizLink connected[%s], Delay time [%d]ms.", url.GetData(), delay);
  410. }
  411. LogWarn(Severity_Low, Error_Param, LOG_WARN_BIZLINK_CONNECT_CHECK, warn.GetData());
  412. if (ctx != NULL) {
  413. ctx->Answer(ec);
  414. }
  415. return ec;
  416. }
  417. //通过集中配置额外执行的清理策略
  418. void ResourceWatcherFSM::CenterSettingDelete()
  419. {
  420. string p;
  421. CSmartPointer<IConfigInfo> spCtSettingConfig;
  422. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  423. CSimpleStringA upPath(""), tempPath(""), tPath(""), upgradePath("");
  424. spCtSettingConfig->ReadConfigValue("ResourceWatcher", "DocumentCleanPath", tempPath);
  425. if (tempPath.GetLength() == 0) {
  426. return;
  427. }
  428. ErrorCodeEnum erroCode = Error_Succeed;
  429. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  430. CSmartPointer<IConfigInfo> spConfigRun;
  431. //判断是否需要被清理
  432. erroCode = pFunc->OpenConfig(Config_Run, spConfigRun);
  433. if (erroCode != Error_Succeed) {
  434. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Open Run Config failed");
  435. return;
  436. }
  437. int nLastTaskTime = 0;
  438. int nLstFlag = 0;
  439. bool bFailFlag = false;
  440. CSimpleStringA optFileName("");
  441. UINT64 utVersion = 0;
  442. spConfigRun->ReadConfigValueHexInt("DeleteDocumentTask", "OptVer", utVersion);
  443. spConfigRun->ReadConfigValue("DeleteDocumentTask", "DocumentName", optFileName);
  444. spConfigRun->ReadConfigValueInt("DeleteDocumentTask", "LastCondi", nLstFlag);
  445. spConfigRun->ReadConfigValueInt("DeleteDocumentTask", "LastTime", nLastTaskTime);
  446. CVersion optVer(utVersion);
  447. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  448. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastCondi: %d",
  449. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  450. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
  451. (LPCTSTR)optVer.ToString(), nLstFlag);
  452. if (optVer.IsValid() && optVer == m_RvcSysinfo.InstallVersion && !nLstFlag && optFileName == tempPath)
  453. {
  454. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Certain document cleaning has been done before.");
  455. return;
  456. }
  457. //执行清理逻辑
  458. upPath = tempPath;
  459. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  460. nFileCount = ProcessFileDelete(upPath.GetData(), nDelSuc, nDelFail, false);
  461. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Process result(%s): count(%d), suc(%d), failed(%d).", upPath.GetData(), nFileCount, nDelSuc, nDelFail);
  462. if (nDelFail != 0) {
  463. bFailFlag = true;
  464. //break;
  465. }
  466. nLstFlag = bFailFlag ? 1 : 0;
  467. spConfigRun->WriteConfigValueHexInt("DeleteDocumentTask", "OptVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  468. spConfigRun->WriteConfigValue("DeleteDocumentTask", "DocumentName", tempPath);
  469. spConfigRun->WriteConfigValueInt("DeleteDocumentTask", "LastCondi", nLstFlag);
  470. spConfigRun->WriteConfigValue("DeleteDocumentTask", "LastTime",
  471. (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  472. if (!bFailFlag)
  473. {
  474. LogWarn(Severity_Low, Error_Debug, LOG_WARN_FILE_DELETE_SUC, CSimpleStringA::Format("Delete files in [%s] success", tempPath.GetData()));
  475. }
  476. }
  477. time_t ResourceWatcherFSM::GetPathTimeSeconds(const char* inPath)
  478. {
  479. if (!inPath)
  480. {
  481. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetPathFileDays PATH = NULL.", inPath);
  482. return 0;
  483. }
  484. time_t lCreateTime = 0;
  485. //int reTimes = 0;
  486. #ifdef RVC_OS_WIN
  487. struct _finddata_t fileinfo;//文件信息读取结构
  488. string p;
  489. long hFile = _findfirst(inPath, &fileinfo);
  490. if (hFile == -1L)
  491. {
  492. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get [%s] fileinfo failed. GLE = %u.", inPath, GetLastError());
  493. return 0;
  494. }
  495. lCreateTime = fileinfo.time_write; //文件最后修改时间
  496. _findclose(hFile);
  497. #else
  498. struct stat stFile;
  499. if (stat(inPath, &stFile) == -1)
  500. {
  501. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] Failed to get file stats. GLE=%d.", inPath, GetLastError());
  502. return 0;
  503. }
  504. lCreateTime = stFile.st_mtime; //文件状态最后修改时间
  505. #endif // RVC_OS_WIN
  506. //reTimes = lCreateTime; //文件时间
  507. return lCreateTime;
  508. }
  509. //所有文件删除功能都用这个函数来处理
  510. //bool delDir:控制是否将目录也一并删除,false 保留目录, true 删除目录
  511. //int saveBackDay:保存多少天内的文件, 默认参数,默认值为0,即不保存。(delDir = true时,该参数强制为0)
  512. int ResourceWatcherFSM::ProcessFileDelete(LPCTSTR lpszPath, int& nDelSucCnt, int& nDelFailedCnt, bool delDir, unsigned int saveBackDay)
  513. {
  514. if (delDir == true) //若要删除目录,则不保留任何文件
  515. {
  516. saveBackDay = 0;
  517. }
  518. int fileCnt = 0;
  519. char* searchFilePath = new char[MAX_PATH];
  520. char* tempFilePath = new char[MAX_PATH];
  521. if (searchFilePath == NULL || tempFilePath == NULL)
  522. {
  523. if (searchFilePath) delete[] searchFilePath;
  524. if (tempFilePath) delete[] tempFilePath;
  525. searchFilePath = NULL;
  526. tempFilePath = NULL;
  527. return fileCnt;
  528. }
  529. ZeroMemory(searchFilePath, MAX_PATH);
  530. ZeroMemory(tempFilePath, MAX_PATH);
  531. #ifdef RVC_OS_LINUX
  532. int fileLength = strlen(lpszPath);
  533. struct stat st;
  534. if (stat(lpszPath, &st) == -1)
  535. {
  536. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("[%s] Failed to get file stats.", lpszPath);
  537. nDelSucCnt++;
  538. return fileCnt;
  539. }
  540. if (!S_ISDIR(st.st_mode))
  541. {//单文件处理
  542. if (saveBackDay != 0)
  543. {
  544. time_t lSystemTime;
  545. time(&lSystemTime);
  546. time_t fileTime = GetPathTimeSeconds(lpszPath); //获取文件的最后改动时间
  547. int delDays = (lSystemTime - fileTime) / SECONDS_OF_DAY;
  548. if (delDays < saveBackDay) // 未达到需要清理的天数阈值,无需清理
  549. {
  550. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Files 存留天数[%d], 删除阈值[%u],无需清理.", (int)delDays, saveBackDay);
  551. return fileCnt;
  552. }
  553. }
  554. if (RemoveFileA(lpszPath) == true) {
  555. nDelSucCnt++;
  556. fileCnt++;
  557. }
  558. else {
  559. nDelFailedCnt++;
  560. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A08").setAPI("DeleteFiles")("RemoveFileA [%s] failed, GLE = %u.", tempFilePath, errno);
  561. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_FILE_DELETE_FAILED, CSimpleStringA::Format("RemoveFileA [%s] failed, GLE = %u.", tempFilePath, errno));
  562. }
  563. if (searchFilePath) delete[] searchFilePath;
  564. if (tempFilePath) delete[] tempFilePath;
  565. searchFilePath = NULL;
  566. tempFilePath = NULL;
  567. return fileCnt;
  568. }
  569. DIR* d = opendir(lpszPath);
  570. if (!d) {
  571. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("opendir failed: %d.", errno);
  572. if (searchFilePath) delete[] searchFilePath;
  573. if (tempFilePath) delete[] tempFilePath;
  574. searchFilePath = NULL;
  575. tempFilePath = NULL;
  576. nDelFailedCnt++;
  577. return fileCnt;
  578. }
  579. struct dirent* dp = NULL;
  580. while ((dp = readdir(d)) != NULL) {
  581. if ((!strcmp(dp->d_name, ".")) || (!strcmp(dp->d_name, ".."))) {
  582. continue;
  583. }
  584. strcpy(tempFilePath, lpszPath);
  585. if (strlen(tempFilePath) + strlen(dp->d_name) + 3 >= MAX_PATH) {
  586. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("filePath is too long for current.");
  587. continue;
  588. }
  589. strcat(tempFilePath, "/");
  590. strcat(tempFilePath, dp->d_name);
  591. stat(tempFilePath, &st);
  592. if (saveBackDay != 0)
  593. {
  594. time_t lSystemTime;
  595. time(&lSystemTime);
  596. time_t fileTime = GetPathTimeSeconds(tempFilePath); //获取文件的最后改动时间
  597. int delDays = (lSystemTime - fileTime) / SECONDS_OF_DAY;
  598. if (delDays < saveBackDay) // 未达到需要清理的天数阈值,无需清理
  599. {
  600. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Dir[%s], 存留天数[%d], 删除阈值[%u],无需清理.", tempFilePath, (int)delDays, saveBackDay);
  601. continue;
  602. }
  603. }
  604. int tDelSucCnt = 0, tDelFailedCnt = 0;
  605. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt, true); //子目录要清理
  606. if (tDelFailedCnt != 0) {
  607. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A08").setAPI("DeleteFiles")("rm(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, errno);
  608. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_FILE_DELETE_FAILED, CSimpleStringA::Format("rm(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, errno));
  609. nDelSucCnt += tDelSucCnt;
  610. nDelFailedCnt += tDelFailedCnt;
  611. return fileCnt;
  612. }
  613. nDelSucCnt += tDelSucCnt;
  614. }
  615. closedir(d);
  616. #else
  617. CSimpleStringA inPath = lpszPath;
  618. inPath.Append("\\*"); // "D:aaa\bbb\ccc\* " 匹配目录下的所有文件和文件夹
  619. int fileLength = inPath.GetLength();
  620. WIN32_FIND_DATA wfd;
  621. HANDLE hFind;
  622. hFind = FindFirstFile(inPath.GetData(), &wfd);
  623. //单文件操作
  624. if (hFind == INVALID_HANDLE_VALUE) // 非文件夹 (inPath "D:aaa\bbb\ccc\* "格式的情况下,如果前面是文件,会找不到匹配)
  625. {
  626. if (saveBackDay != 0)
  627. {
  628. //读取文件时间
  629. time_t lSystemTime;
  630. time(&lSystemTime);
  631. time_t fileTime = GetPathTimeSeconds(lpszPath); //获取文件的最后改动时间
  632. int delDays = (lSystemTime - fileTime) / SECONDS_OF_DAY;
  633. if (delDays < saveBackDay) // 未达到需要清理的天数阈值,无需清理
  634. {
  635. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("存留天数[%d], 删除阈值[%u],无需清理.", (int)delDays, saveBackDay);
  636. return fileCnt;
  637. }
  638. }
  639. if (DeleteFile(lpszPath) == true)
  640. {
  641. nDelSucCnt++;
  642. fileCnt++;
  643. }
  644. else
  645. {
  646. nDelFailedCnt++;
  647. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A08").setAPI("DeleteFiles")
  648. ("Delete [%s] failed, GLE = %u.", lpszPath, GetLastError());
  649. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_FILE_DELETE_FAILED, CSimpleStringA::Format("RemoveFileA [%s] failed, GLE = %u.", lpszPath, errno));
  650. }
  651. if (searchFilePath) delete[] searchFilePath;
  652. if (tempFilePath) delete[] tempFilePath;
  653. searchFilePath = NULL;
  654. tempFilePath = NULL;
  655. return fileCnt;
  656. }
  657. //文件夹操作
  658. do
  659. {
  660. if (wfd.cFileName[0] != '.')
  661. {
  662. strcpy_s(tempFilePath, MAX_PATH, inPath.GetData());
  663. tempFilePath[fileLength - 1] = '\0';
  664. if (strlen(tempFilePath) + strlen(wfd.cFileName) + 3 >= MAX_PATH)
  665. {
  666. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("filePath is too long for current.");
  667. }
  668. else
  669. {
  670. strcat_s(tempFilePath, MAX_PATH, wfd.cFileName); //"D:aaa\bbb\ccc\fileName"
  671. if (saveBackDay != 0)
  672. {
  673. time_t lSystemTime;
  674. time(&lSystemTime);
  675. time_t fileTime = GetPathTimeSeconds(tempFilePath); //获取文件的最后改动时间
  676. if (fileTime == 0)
  677. {
  678. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get file time (%s) failed. skip clean", (LPCTSTR)tempFilePath);
  679. nDelFailedCnt++;
  680. continue;
  681. }
  682. int delDays = (lSystemTime - fileTime) / SECONDS_OF_DAY;
  683. if (delDays < saveBackDay) // 未达到需要清理的天数阈值,无需清理
  684. {
  685. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Dir[%s], 存留天数[%d], 删除阈值[%u],无需清理.", tempFilePath, (int)delDays, saveBackDay);
  686. continue;
  687. }
  688. }
  689. int tDelSucCnt = 0, tDelFailedCnt = 0;
  690. fileCnt += ProcessFileDelete((LPCTSTR)tempFilePath, tDelSucCnt, tDelFailedCnt, true); //子目录要删除
  691. if (tDelFailedCnt != 0)
  692. {
  693. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A08").setAPI("DeleteFiles")
  694. ("rm(%s) failed, GLE = %u.", (LPCTSTR)tempFilePath, GetLastError());
  695. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_FILE_DELETE_FAILED, CSimpleStringA::Format("RemoveFileA [%s] failed, GLE = %u.", (LPCTSTR)tempFilePath, errno));
  696. nDelFailedCnt += tDelFailedCnt;
  697. return fileCnt;
  698. }
  699. nDelFailedCnt += tDelFailedCnt;
  700. nDelSucCnt += tDelSucCnt;
  701. }
  702. }
  703. } while (FindNextFileA(hFind, &wfd));
  704. FindClose(hFind);
  705. #endif // RVC_OS_LINUX
  706. if (delDir) //删除目录
  707. {
  708. #ifdef RVC_OS_WIN
  709. RemoveDirectoryA(lpszPath);
  710. #else
  711. RemoveDirRecursive(lpszPath);
  712. #endif
  713. }
  714. if (searchFilePath) delete[] searchFilePath;
  715. if (tempFilePath) delete[] tempFilePath;
  716. searchFilePath = NULL;
  717. tempFilePath = NULL;
  718. return fileCnt;
  719. }
  720. //终端默认执行的终端清理策略
  721. void ResourceWatcherFSM::AutoDeleteFiles()
  722. {
  723. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  724. CSmartPointer<IConfigInfo> spConfig;
  725. pFunc->OpenConfig(Config_CenterSetting, spConfig);
  726. //判断是否升级完毕,未完成升级不进行删除任务
  727. CSimpleStringA strRunInfo, strStartTime;
  728. if (m_pEntity->GetFunction()->GetPath("RunInfo", strRunInfo) == Error_Succeed) {
  729. strStartTime = strRunInfo + SPLIT_SLASH_STR + "runcfg" + SPLIT_SLASH_STR + "starttime.dat";
  730. if (!ExistsFileA(strStartTime.GetData())) {
  731. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade prpcess done, try to delete version files.");//完成升级过程,通过
  732. }
  733. else
  734. {
  735. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade process is not end ,should not delete files.");
  736. return;//升级未完成,不进行删除
  737. }
  738. }
  739. else
  740. {
  741. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("upgrade process is not end ,get runinfo path error, should not version files.");
  742. return;//失败,继续等待
  743. }
  744. //清理版本相关文件
  745. DeleteVersionPackage();
  746. //清理录像文件
  747. DeleteVideoFiles();
  748. return;
  749. }
  750. //终端升级后会执行版本清理功能 包含dump和 upgaraded清理
  751. BOOL ResourceWatcherFSM::DeleteVersionPackage()
  752. {
  753. ErrorCodeEnum erroCode = Error_Succeed;
  754. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  755. CSmartPointer<IConfigInfo> spConfigRun;
  756. CSmartPointer<IConfigInfo> spConfig;
  757. CSystemStaticInfo info;
  758. if (pFunc->GetSystemStaticInfo(info) != Error_Succeed) {
  759. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get system static info error");
  760. return FALSE;
  761. }
  762. //清理执行成功与否的判断变量
  763. int nLastTaskTime = 0;
  764. int nLstFailed = 0;
  765. int nDelCount = 0;
  766. UINT64 utVersion = 0;
  767. pFunc->OpenConfig(Config_CenterSetting, spConfig);
  768. pFunc->OpenConfig(Config_Run, spConfigRun);
  769. spConfigRun->ReadConfigValueHexInt("VersionClear", "OptVer", utVersion);
  770. spConfigRun->ReadConfigValueInt("VersionClear", "DelVerCnt", nDelCount);
  771. spConfigRun->ReadConfigValueInt("VersionClear", "LastCondi", nLstFailed); //失败标志
  772. spConfigRun->ReadConfigValueInt("VersionClear", "LastTime", nLastTaskTime);
  773. CVersion optVer(utVersion);
  774. SYSTEMTIME stTaskTime = CSmallDateTime(nLastTaskTime).ToSystemTime();
  775. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("LastTime<%04d-%02d-%02d %02d:%02d:%02d>: OptVer: %s, LastFailed: %d",
  776. stTaskTime.wYear, stTaskTime.wMonth, stTaskTime.wDay,
  777. stTaskTime.wHour, stTaskTime.wMinute, stTaskTime.wSecond,
  778. (LPCTSTR)optVer.ToString(), nLstFailed);
  779. //判断是否需要执行清理任务,若此版本之前成功清理过则不再继续执行后续操作
  780. if (optVer.IsValid() && optVer == info.InstallVersion && !nLstFailed) {
  781. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("VersionPackage cleaning has been done before.");
  782. return TRUE;
  783. }
  784. //--------------------------------------------------------------------------------------------
  785. //版本清理中默认进行upgrade清理
  786. int closeUpgradeClear = 0;
  787. spConfig->ReadConfigValueInt("ResourceWatcher", "CloseUpgradeClear", closeUpgradeClear);
  788. if (!closeUpgradeClear)
  789. {
  790. //删除rvc/Upgraded目录下的文件
  791. CSimpleStringA upPath;
  792. ErrorCodeEnum upError = pFunc->GetPath("Upgraded", upPath);
  793. if (Error_Succeed != upError) {
  794. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Try to clean Upgraded Dir. But get Upgraded path error = %u.", upError);
  795. return FALSE;
  796. }
  797. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  798. nFileCount = ProcessFileDelete(upPath.GetData(), nDelSuc, nDelFail, false);
  799. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete [Upgraded] result(%s): count(%d), suc(%d), failed(%d).", upPath.GetData(), nFileCount, nDelSuc, nDelFail);
  800. }
  801. //--------------------------------------------------------------------------------------------
  802. //版本清理中默认进行dump清理
  803. int closeDmpClear = 0;
  804. spConfig->ReadConfigValueInt("ResourceWatcher", "CloseDmpClear", closeDmpClear);
  805. if (!closeDmpClear)
  806. { //执行删除流程rvc/dmp
  807. CSimpleStringA dmpPath;
  808. ErrorCodeEnum dmpError = pFunc->GetPath("Temp", dmpPath);
  809. if (Error_Succeed != dmpError) {
  810. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Try to clean Dump Dir. But get Temp path error = %u.", dmpError);
  811. return FALSE;
  812. }
  813. #ifdef RVC_OS_LINUX
  814. dmpPath = dmpPath + SPLIT_SLASH_STR + ".." + SPLIT_SLASH_STR + "dmp"; // +"/../dmp"
  815. #else
  816. dmpPath = dmpPath + CSimpleStringA::Format("\\..\\dmp");
  817. #endif // RVC_OS_LINUX
  818. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  819. nFileCount = ProcessFileDelete(dmpPath.GetData(), nDelSuc, nDelFail, false);
  820. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete [Dump] result(%s): count(%d), suc(%d), failed(%d).", dmpPath.GetData(), nFileCount, nDelSuc, nDelFail);
  821. }
  822. //--------------------------------------------------------------------------------------------
  823. //清理ver文件夹
  824. int closeVerClear = 0;
  825. spConfig->ReadConfigValueInt("ResourceWatcher", "CloseVerClear", closeVerClear);
  826. if (!closeVerClear)
  827. {
  828. int verSaved = DEFAULT_VERSION_SAVED_COUNT;
  829. int tmpSaved = 0;
  830. vector<CVersion> intallInfoVects;
  831. vector<string> files;
  832. spConfig->ReadConfigValueInt("ResourceWatcher", "VerSaveCnt", tmpSaved);
  833. if (tmpSaved > DEFAULT_VERSION_SAVED_COUNT) {
  834. verSaved = tmpSaved;
  835. }
  836. //获取当前目录下的文件夹名称, 将符合命名规则的终端版本名称push_back
  837. CSimpleStringA csPath, verPath;
  838. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
  839. if (Error_Succeed == Error) {
  840. if (csPath.IsNullOrEmpty()) {
  841. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("get currVer path is null");
  842. return FALSE;
  843. }
  844. else
  845. {
  846. verPath = csPath; //csPath在后面被用了,还需要个存储version路径变量
  847. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CUR VERSION PATH = %s.", csPath.GetData());
  848. }
  849. }
  850. else
  851. {
  852. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get Ver path error = %u.", Error);
  853. return FALSE;
  854. }
  855. //判断哪些是版本文件夹
  856. #ifdef RVC_OS_LINUX
  857. DIR* dp;
  858. struct dirent* dirp;
  859. //过滤非目标版本文件夹
  860. if ((dp = opendir(csPath.GetData())) != NULL) {
  861. while ((dirp = readdir(dp)) != NULL) {
  862. //files.push_back(string(dirp->d_name));
  863. CInstallInfo verInfo = {};
  864. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  865. int n = sscanf(dirp->d_name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  866. if (n != 4)
  867. {
  868. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", dirp->d_name);
  869. continue;
  870. }
  871. else {
  872. CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
  873. if (verName.IsValid() && verName < info.InstallVersion) //对高于自身版本的文件不予删除
  874. {
  875. intallInfoVects.push_back(verName);
  876. }
  877. else {
  878. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", dirp->d_name);
  879. }
  880. }
  881. }
  882. closedir(dp);
  883. }
  884. #else
  885. long hFile = 0;
  886. struct _finddata_t fileinfo;//文件信息读取结构
  887. string p;
  888. if ((hFile = _findfirst(p.assign(string(csPath.GetData())).append("\\*").c_str(), &fileinfo)) != -1) {
  889. do {
  890. CInstallInfo verInfo = {};
  891. DWORD dwMajor(0), dwMinor(0), dwRevision(0), dwBuild(0);
  892. int n = sscanf(fileinfo.name, "%d.%d.%d.%d", &dwMajor, &dwMinor, &dwRevision, &dwBuild);
  893. if (n != 4)
  894. {
  895. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", fileinfo.name);
  896. continue;
  897. }
  898. else {
  899. CVersion verName(dwMajor, dwMinor, dwRevision, dwBuild);
  900. if (verName.IsValid() && verName < info.InstallVersion)
  901. {
  902. intallInfoVects.push_back(verName);
  903. }
  904. else {
  905. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not version file.[%s]", fileinfo.name);
  906. }
  907. }
  908. } while (_findnext(hFile, &fileinfo) == 0);
  909. _findclose(hFile);
  910. }
  911. #endif // RVC_OS_LINUX
  912. int nPackCount = intallInfoVects.size();
  913. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Install Package's count: %d", nPackCount);
  914. bool bFailFlag = false;
  915. int nDelVersionCnt = 0;
  916. std::string tInfo("");
  917. //执行版本删除流程
  918. if (nPackCount != 0) {
  919. int nSavedCount = 0;
  920. sort(intallInfoVects.begin(), intallInfoVects.end());
  921. vector<CVersion>::reverse_iterator riter = intallInfoVects.rbegin();
  922. while (riter != intallInfoVects.rend()) {
  923. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("InstallPackage Info: %s", (LPCTSTR)(*riter).ToString());
  924. if (++nSavedCount <= verSaved) {
  925. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Save above version");
  926. riter++;
  927. continue;
  928. }
  929. CSimpleStringA tVerPath;
  930. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  931. #ifdef RVC_OS_LINUX
  932. tVerPath = verPath + SPLIT_SLASH_STR + (*riter).ToString();
  933. #else
  934. tVerPath = verPath + "\\" + (*riter).ToString();
  935. #endif // RVC_OS_LINUX
  936. nFileCount = ProcessFileDelete(tVerPath.GetData(), nDelSuc, nDelFail, true); //版本文件夹连目录一起清理
  937. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete Version result(%s): count(%d), suc(%d), failed(%d).",
  938. tVerPath.GetData(), nFileCount, nDelSuc, nDelFail);
  939. if (nDelFail)
  940. {
  941. bFailFlag = true;
  942. }
  943. else
  944. {
  945. nDelVersionCnt++;
  946. tInfo = tInfo + "|" + std::string((*riter).ToString().GetData());
  947. }
  948. riter++;
  949. }
  950. }
  951. nLstFailed = bFailFlag ? 1 : 0;
  952. spConfigRun->WriteConfigValueHexInt("VersionClear", "OptVer", info.InstallVersion.GetVersion64());
  953. spConfigRun->WriteConfigValueInt("VersionClear", "DelVerCnt", nDelCount + nDelVersionCnt);
  954. spConfigRun->WriteConfigValueInt("VersionClear", "LastCondi", nLstFailed);
  955. spConfigRun->WriteConfigValue("VersionClear", "LastTime",
  956. (LPCTSTR)CSimpleStringA::Format("0x%08X", (DWORD)CSmallDateTime::GetNow()));
  957. if (nDelVersionCnt > 0) {
  958. std::string warn = "Delete Vesion file count : " + std::to_string((long long)nDelVersionCnt) + ". ----- " + tInfo + ".";
  959. LogWarn(Severity_Low, Error_Debug, LOG_WARN_VER_DELETE, CSimpleStringA::Format("%s", warn.c_str()));
  960. }
  961. }
  962. return TRUE;
  963. }
  964. void ResourceWatcherFSM::DeleteVideoFiles()
  965. {
  966. int backDays = 0, closeVideoClear = 0;
  967. CSmartPointer<IEntityFunction> pFunc = GetEntityBase()->GetFunction();
  968. CSmartPointer<IConfigInfo> spConfig;
  969. pFunc->OpenConfig(Config_CenterSetting, spConfig);
  970. spConfig->ReadConfigValueInt("ResourceWatcher", "CloseVideoClear", closeVideoClear);
  971. if (closeVideoClear)
  972. {
  973. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("CenterSetting no need video clear.");
  974. return;
  975. }
  976. spConfig->ReadConfigValueInt("ResourceWatcher", "VideoBackDays", backDays);
  977. if (backDays <= 0)
  978. {
  979. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("video default backdays:30 days.");
  980. backDays = VIDEO_DEFAULT_BACKDAYS;
  981. }
  982. CSimpleStringA videoPath, verPath;
  983. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("LocalVideo", videoPath); //获取Video路径
  984. if (Error_Succeed == Error) {
  985. if (videoPath.IsNullOrEmpty()) {
  986. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get LocalVideo path NULL");
  987. return;
  988. }
  989. else
  990. {
  991. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("VIDEO PATH = %s.", videoPath.GetData());
  992. }
  993. }
  994. else
  995. {
  996. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("get LocalVideo error. error = %u.", Error);
  997. return;
  998. }
  999. int nDelSuc = 0, nDelFail = 0, nFileCount = 0;
  1000. nFileCount = ProcessFileDelete(videoPath.GetData(), nDelSuc, nDelFail, false, backDays);
  1001. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Delete [Video] result(%s): count(%d), suc(%d), failed(%d).", videoPath.GetData(), nFileCount, nDelSuc, nDelFail);
  1002. }
  1003. void ResourceWatcherFSM::SelfTest(EntityTestEnum eTestType,
  1004. CSmartPointer<ITransactionContext> pTransactionContext)
  1005. {
  1006. if (Test_ShakeHand == eTestType)
  1007. {
  1008. pTransactionContext->SendAnswer(Error_Succeed);
  1009. }
  1010. }
  1011. void ResourceWatcherFSM::HardwareInfoTimer(void* pData)
  1012. {
  1013. if (hardwareCheckFlag > 0) {
  1014. GetSystemCPUStatus();
  1015. GetSystemMemoryStatus();
  1016. }
  1017. GetEntityBase()->GetFunction()->ResetTimer(TIMER_HARDWARE_CHECK, hardwareCheckTime);
  1018. }
  1019. void ResourceWatcherFSM::DiskCheckTimer(void* pData)
  1020. {
  1021. if (diskCheckFlag > 0) {
  1022. GetSystemDiskStatus();
  1023. }
  1024. GetEntityBase()->GetFunction()->ResetTimer(TIMER_DISK_CHECK, diskCheckTime);
  1025. }
  1026. ErrorCodeEnum ResourceWatcherFSM::CheckNetType(
  1027. SpReqAnsContext<ResourceWatcherService_CheckNetType_Req, ResourceWatcherService_CheckNetType_Ans>::Pointer ctx)
  1028. {
  1029. ErrorCodeEnum ec = Error_Succeed;
  1030. int netType = 0; //默认未知
  1031. #ifdef RVC_OS_LINUX
  1032. int i = 0;
  1033. int sockfd;
  1034. struct ifconf ifconf;
  1035. struct ifreq* ifreq;
  1036. char buf[1024];
  1037. //初始化ifconf
  1038. ifconf.ifc_len = 1024;
  1039. ifconf.ifc_buf = buf;
  1040. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
  1041. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("socket error");
  1042. }
  1043. //获取所有接口信息
  1044. ioctl(sockfd, SIOCGIFCONF, &ifconf);
  1045. //逐个获取Ip地址
  1046. int size = ifconf.ifc_len / sizeof(struct ifreq);
  1047. ifreq = (struct ifreq*)buf;
  1048. string netName(ifreq->ifr_name);
  1049. if (size == 1 && netName == "lo") //只有逻辑地址 -- 网线被拔出
  1050. {
  1051. netType = 1;
  1052. }
  1053. else
  1054. {
  1055. for (i = size; i > 0; i--) {
  1056. string netName(ifreq->ifr_name); //有其他网卡 -- 有线
  1057. if (netName != "lo") {
  1058. netType = 2;
  1059. }
  1060. ifreq++;
  1061. }
  1062. }
  1063. #else
  1064. CoInitialize(NULL);
  1065. // 通过NLA接口获取网络状态
  1066. IUnknown* pUnknown = NULL;
  1067. bool bOnline = true;//是否在线
  1068. HRESULT Result = CoCreateInstance(CLSID_NetworkListManager, NULL, CLSCTX_ALL,
  1069. IID_IUnknown, (void**)&pUnknown);
  1070. if (SUCCEEDED(Result)) {
  1071. INetworkListManager* pNetworkListManager = NULL;
  1072. if (pUnknown)
  1073. Result = pUnknown->QueryInterface(IID_INetworkListManager, (void
  1074. **)&pNetworkListManager);
  1075. if (SUCCEEDED(Result)) {
  1076. VARIANT_BOOL IsConnect = VARIANT_FALSE;
  1077. if (pNetworkListManager) {
  1078. //Result = pNetworkListManager->get_IsConnectedToInternet(&IsConnect); //检测互联网连接
  1079. Result = pNetworkListManager->get_IsConnected(&IsConnect); //检测本地网络
  1080. }
  1081. if (SUCCEEDED(Result)) {
  1082. bOnline = (IsConnect == VARIANT_TRUE) ? true : false;
  1083. }
  1084. }
  1085. if (pNetworkListManager)
  1086. pNetworkListManager->Release();
  1087. }
  1088. if (pUnknown)
  1089. pUnknown->Release();
  1090. if (bOnline == true) {
  1091. netType = 2;
  1092. }
  1093. else
  1094. {
  1095. netType = 1;
  1096. }
  1097. #endif // RVC_OS_LINUX
  1098. if (ctx != NULL) {
  1099. ctx->Ans.netType = netType;
  1100. ctx->Answer(ec);
  1101. }
  1102. return ec;
  1103. }
  1104. ErrorCodeEnum ResourceWatcherFSM::GetBizLinks(
  1105. SpReqAnsContext<ResourceWatcherService_GetBizLinks_Req, ResourceWatcherService_GetBizLinks_Ans>::Pointer ctx)
  1106. {
  1107. LOG_FUNCTION();
  1108. ErrorCodeEnum ec = Error_Succeed;
  1109. int filter = ctx->Req.filter; //后续过滤使用
  1110. CAutoArray<CSimpleStringA> bizLinks;
  1111. CAutoArray<CSimpleStringA> bizNames;
  1112. CSmartPointer<IConfigInfo> spCtSettingConfig;
  1113. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  1114. if (filter == 0) //用户管理桌面业务网址
  1115. {
  1116. CSimpleStringA mLink(""), adLink(""), tLink("");
  1117. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrUrlFulture", mLink);
  1118. if (mLink.GetLength() != 0) {
  1119. CSimpleStringA tName = CSimpleStringA("主站点");
  1120. bizNames.Append(&tName, 0, 1);
  1121. bizLinks.Append(&mLink, 0, 1);
  1122. }
  1123. spCtSettingConfig->ReadConfigValue("Chromium", "UserMgrAd", adLink);
  1124. if (adLink.GetLength() != 0) {
  1125. CSimpleStringA tName = CSimpleStringA("广告站点");
  1126. bizNames.Append(&tName, 0, 1);
  1127. bizLinks.Append(&adLink, 0, 1);
  1128. }
  1129. int bizCnt = 0;
  1130. CSimpleStringA info(""), getLink("");
  1131. do {// 主站点|www.test.com
  1132. bizCnt++;
  1133. CSimpleStringA chineseName("");
  1134. CSimpleStringA url("");
  1135. getLink = CSimpleStringA("DesktopDetectUrl").Append(std::to_string(bizCnt).c_str());
  1136. spCtSettingConfig->ReadConfigValue("ResourceWatcher", getLink.GetData(), info);
  1137. if (info.GetLength() != 0) {
  1138. CAutoArray<CSimpleStringA> arr = info.Split('|');
  1139. int len = arr.GetCount();
  1140. if (len != 2) {
  1141. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s]Not Detect Url", info.GetData());
  1142. }
  1143. else
  1144. {
  1145. chineseName = arr[0];
  1146. url = arr[1];
  1147. bizNames.Append(&chineseName, 0, 1);
  1148. bizLinks.Append(&url, 0, 1);
  1149. }
  1150. }
  1151. } while (info.GetLength() != 0);
  1152. }
  1153. else if (filter == 1) //错误页集中配置、准入网址
  1154. {
  1155. int bizCnt = 0;
  1156. CSimpleStringA info(""), getLink("");
  1157. do {// 准入服务|AccessAuth|accessUrl
  1158. bizCnt++;
  1159. CSimpleStringA chineseName(""), entityName(""), key("");
  1160. CSimpleStringA url("");
  1161. getLink = CSimpleStringA("ErrPageDetectUrl").Append(std::to_string(bizCnt).c_str());
  1162. spCtSettingConfig->ReadConfigValue("ResourceWatcher", (LPCTSTR)getLink, info);
  1163. if (info.GetLength() != 0) {
  1164. CAutoArray<CSimpleStringA> arr = info.Split('|');
  1165. int len = arr.GetCount();
  1166. if (len != 3) {
  1167. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[%s]Not errPage Check config info.", info.GetData());
  1168. }
  1169. else
  1170. {
  1171. chineseName = arr[0];
  1172. entityName = arr[1];
  1173. key = arr[2];
  1174. spCtSettingConfig->ReadConfigValue(entityName.GetData(), key.GetData(), url);
  1175. if (url.GetLength() != 0) {
  1176. bizNames.Append(&chineseName, 0, 1);
  1177. bizLinks.Append(&url, 0, 1);
  1178. }
  1179. else
  1180. {
  1181. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Get errPage detecet url failed. EntityName:(%s), Key:(%s).",
  1182. entityName.GetData(), key.GetData());
  1183. }
  1184. }
  1185. }
  1186. } while (info.GetLength() != 0);
  1187. }
  1188. ctx->Ans.bizLinks = bizLinks;
  1189. ctx->Ans.bizNames = bizNames;
  1190. if (ctx != NULL) {
  1191. ctx->Answer(ec);
  1192. }
  1193. return ec;
  1194. }
  1195. #ifdef _MSC_VER
  1196. bool ResourceWatcherFSM::CreateLinkFile(const CSimpleStringA& szStartAppPath, const CSimpleStringA& szAddCmdLine,
  1197. const CSimpleStringA& szDestLnkPath, const CSimpleStringA& szIconPath)
  1198. {
  1199. HRESULT hr = CoInitialize(NULL);
  1200. bool bRet = false;
  1201. if (SUCCEEDED(hr))
  1202. {
  1203. IShellLink* pShellLink;
  1204. hr = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (void**)&pShellLink);
  1205. if (SUCCEEDED(hr))
  1206. {
  1207. pShellLink->SetPath(szStartAppPath);
  1208. string strTmp = szStartAppPath;
  1209. int nStart = strTmp.find_last_of("/\\");
  1210. pShellLink->SetWorkingDirectory(strTmp.substr(0, nStart).c_str());
  1211. pShellLink->SetArguments(szAddCmdLine);
  1212. if (szIconPath)
  1213. {
  1214. pShellLink->SetIconLocation(szIconPath, 0);
  1215. }
  1216. IPersistFile* pPersistFile;
  1217. hr = pShellLink->QueryInterface(IID_IPersistFile, (void**)&pPersistFile);
  1218. if (SUCCEEDED(hr))
  1219. {
  1220. hr = pPersistFile->Save(CSimpleStringA2W(szDestLnkPath).GetData(), FALSE);
  1221. if (SUCCEEDED(hr))
  1222. {
  1223. bRet = true;
  1224. }
  1225. pPersistFile->Release();
  1226. }
  1227. pShellLink->Release();
  1228. }
  1229. CoUninitialize();
  1230. }
  1231. return bRet;
  1232. }
  1233. void ResourceWatcherFSM::CreateLink(const CSimpleStringA& exePath, const CSimpleStringA& csVersion)
  1234. {
  1235. LPITEMIDLIST lp;
  1236. SHGetSpecialFolderLocation(0, CSIDL_DESKTOPDIRECTORY, &lp);
  1237. CHAR lstr[100] = "";
  1238. SHGetPathFromIDList(lp, lstr);
  1239. CSimpleStringA s = lstr;
  1240. s += "\\可视柜台.lnk";
  1241. CSimpleStringA icoPath;
  1242. ErrorCodeEnum Error = GetEntityBase()->GetFunction()->GetPath("RootVer", icoPath);
  1243. icoPath = icoPath + "\\" + csVersion.GetData() + "\\bin\\VTM.ico";
  1244. if (!CreateLinkFile(exePath, "", s, icoPath))
  1245. {
  1246. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CreateLinkFile DESKTOP fail");
  1247. }
  1248. SHGetSpecialFolderLocation(0, CSIDL_PROGRAMS, &lp);
  1249. memset(lstr, 0, strlen(lstr));
  1250. SHGetPathFromIDList(lp, lstr);
  1251. s = lstr;
  1252. s += "\\可视柜台.lnk";
  1253. if (!CreateLinkFile(exePath, "", s, icoPath))
  1254. {
  1255. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CreateLinkFile CSIDL_PROGRAMS fail");
  1256. }
  1257. }
  1258. bool ResourceWatcherFSM::CopyExeToRoot(const CSimpleStringA& csVersion)
  1259. {
  1260. CSimpleStringA rootVerPath, exePath;
  1261. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  1262. exePath = rootVerPath + "\\VTM.exe";
  1263. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("exePath:%s", exePath.GetData());
  1264. if (rc == Error_Succeed)
  1265. {
  1266. CSimpleStringA srcExePath, csPath = rootVerPath;
  1267. srcExePath = rootVerPath + "\\" + csVersion.GetData() + "\\bin\\VTM.exe";
  1268. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("srcExePath:%s exePath:%s", srcExePath.GetData(), exePath.GetData());
  1269. if (!ExistsFileA(srcExePath)) {
  1270. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s is not exist!", srcExePath.GetData());
  1271. return false;
  1272. }
  1273. if (!CopyFileA(srcExePath.GetData(), exePath.GetData(), FALSE))
  1274. {
  1275. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("CopyFileA Fail error :%d ", GetLastError());
  1276. return false;
  1277. }
  1278. }
  1279. else {
  1280. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetPath 4 RootVer failed: %s", SpStrError(rc));
  1281. return false;
  1282. }
  1283. return true;
  1284. }
  1285. bool ResourceWatcherFSM::GetVtmVersionFromActiveTxt(CSimpleStringA& csVersion)
  1286. {
  1287. bool bRet = false;
  1288. CSimpleStringA rootVerPath;
  1289. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);//获取version根路径
  1290. if (rc != Error_Succeed) {
  1291. LogWarn(Severity_Middle, Error_Exception, LOG_RESOURCEWATCHER_OPEN_ACTIVE_FAIL, "testActive fail , get RootVer path is failed");
  1292. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A06")("testActive fail , get RootVer path is failed!");
  1293. return false;
  1294. }
  1295. CSimpleStringA strActiveFile = CSimpleStringA::Format("%s\\active.txt", rootVerPath.GetData());
  1296. FILE* pFile = fopen(strActiveFile.GetData(), "rb+");
  1297. if (pFile != NULL)
  1298. {
  1299. char szTemp[256] = {};
  1300. char szVersion[32] = {};
  1301. int n = fread(szTemp, 1, 256, pFile);
  1302. strncpy_s(szVersion, sizeof(szVersion), szTemp, _TRUNCATE);
  1303. csVersion = szVersion;
  1304. fclose(pFile);
  1305. bRet = true;
  1306. }
  1307. else
  1308. {
  1309. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open active.txt failed.");
  1310. bRet = false;
  1311. }
  1312. return bRet;
  1313. }
  1314. bool ResourceWatcherFSM::GetRegValue(HKEY hKey, LPCTSTR lpcszParam,
  1315. CHAR* pSzValue, DWORD* pDwSizeOfSz)
  1316. {
  1317. DWORD dwType = REG_SZ;
  1318. TCHAR szValue[MAX_PATH + 1] = { 0 };
  1319. DWORD dwSize = MAX_PATH * sizeof(CHAR);
  1320. LONG lResult = RegQueryValueEx(hKey, lpcszParam, NULL, &dwType, (LPBYTE)szValue, pDwSizeOfSz);
  1321. if (lResult == ERROR_SUCCESS) {
  1322. strcpy_s(pSzValue, *pDwSizeOfSz, szValue);
  1323. return true;
  1324. }
  1325. else {
  1326. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegQueryValueEx for \"%s\" error, result=%ld.", lpcszParam, lResult);
  1327. return false;
  1328. }
  1329. }
  1330. void ResourceWatcherFSM::DetectAutoStartupCover()
  1331. {
  1332. const int nStartupType = DetectAutoStartupType();
  1333. ErrorCodeEnum rc = Error_InvalidState;
  1334. const int setType = InitialAutoStartupSetType();
  1335. bool toCheckAndDelteAutostartFile(false);
  1336. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("current startup type:%d, aim start type:%d", nStartupType, setType);
  1337. switch (setType)
  1338. {
  1339. case 1://将VBS改成EXE,前提是VBS必须已在注册表
  1340. if (nStartupType == 1) {
  1341. rc = ChangeAutoStartupWithExe();
  1342. }
  1343. break;
  1344. case 2: //设置使用EXE注册表自启动
  1345. if (nStartupType == 1 || nStartupType == 0 || nStartupType == 3) {
  1346. rc = ChangeAutoStartupWithExe();
  1347. if (rc == Error_Succeed && nStartupType == 3) {
  1348. toCheckAndDelteAutostartFile = true;
  1349. }
  1350. }
  1351. break;
  1352. case 5: //设置使用EXE注册表自启动(涵盖所有类型)
  1353. if (nStartupType == 1 || nStartupType == 0 || nStartupType == 3 || nStartupType == 4) {
  1354. rc = ChangeAutoStartupWithExe();
  1355. if (rc == Error_Succeed && (nStartupType == 3 || nStartupType == 4)) {
  1356. toCheckAndDelteAutostartFile = true;
  1357. }
  1358. }
  1359. break;
  1360. case 3: //不设置开机自启动
  1361. if (nStartupType == 1 || nStartupType == 2) {
  1362. rc = ChangeAutoStartupWithExe(false, true);
  1363. }
  1364. else if (nStartupType == 3 || nStartupType == 4) {
  1365. toCheckAndDelteAutostartFile = true;
  1366. }
  1367. break;
  1368. case 4: //恢复VBS启动(防止EXE启动失败)
  1369. if (nStartupType == 2 || nStartupType == 0) {
  1370. rc = ChangeAutoStartupWithExe(true);
  1371. }
  1372. break;
  1373. default:
  1374. break;
  1375. }
  1376. if (toCheckAndDelteAutostartFile) {
  1377. CSimpleStringA strLnkPath(true);
  1378. bool scriptTypeOrNot;
  1379. if (IsHasSetAutoStartupByFolder(strLnkPath, scriptTypeOrNot) && !strLnkPath.IsNullOrEmpty()) {
  1380. BOOL rmRet = RemoveFileA(strLnkPath);
  1381. if (!rmRet && ExistsFileA(strLnkPath)) {
  1382. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("remove auto start lnk file failed: %s, GLE=%u", strLnkPath.GetData(), GetLastError());
  1383. }
  1384. else {
  1385. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("remove auto start lnk file: %s", strLnkPath.GetData());
  1386. }
  1387. }
  1388. }
  1389. }
  1390. static int Is32R64Platform()
  1391. {
  1392. static int isWow64 = -1;
  1393. typedef BOOL(WINAPI* LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
  1394. if (isWow64 == -1) {
  1395. BOOL bIsWow64 = FALSE;
  1396. LPFN_ISWOW64PROCESS fnIsWow64Process =
  1397. (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle("kernel32"), "IsWow64Process");
  1398. if (NULL != fnIsWow64Process) {
  1399. if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64)) {
  1400. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("detect is running with 64bit or not failed: %u", GetLastError());
  1401. return -1;
  1402. }
  1403. else
  1404. {
  1405. isWow64 = bIsWow64 ? 1 : 0;
  1406. }
  1407. }
  1408. }
  1409. return isWow64;
  1410. }
  1411. int ResourceWatcherFSM::DetectAutoStartupType()
  1412. {
  1413. LOG_FUNCTION();
  1414. int vbsType = -1;
  1415. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  1416. if (Is32R64Platform() != 0) {
  1417. dwFlag |= KEY_WOW64_64KEY;
  1418. }
  1419. bool explorerSet = false;
  1420. CSimpleStringA regeditValue(true);
  1421. HKEY hKey;
  1422. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
  1423. TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"),
  1424. 0, dwFlag, &hKey);
  1425. if (lResult == ERROR_SUCCESS) {
  1426. DWORD dwType = REG_SZ;
  1427. DWORD dwSize = MAX_PATH * sizeof(TCHAR);
  1428. TCHAR szValue[MAX_PATH + 1] = { 0 };
  1429. memset(szValue, '\0', MAX_PATH + 1);
  1430. lResult = RegQueryValueEx(hKey, "Shell", NULL, &dwType, (LPBYTE)szValue, &dwSize);
  1431. if (lResult == ERROR_SUCCESS) {
  1432. std::string strValue(szValue);
  1433. regeditValue = szValue;
  1434. strValue = SP::Utility::ToLower(strValue);
  1435. CSimpleStringA value(strValue.c_str());
  1436. if (value.IsStartWith("wscript", true) && value.IsEndWith(".vbs", true)) {
  1437. LogWarn(Severity_Low, Error_Debug, LOG_WARN_AUTO_STARTUP_FROM_REGIST, regeditValue);
  1438. vbsType = 1;
  1439. }
  1440. else if (value.IsEndWith("vtm.exe", true)) {
  1441. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_WITH_EXE, regeditValue);
  1442. vbsType = 2;
  1443. }
  1444. else if (value.Compare("explorer.exe") == 0) {
  1445. vbsType = 0;
  1446. explorerSet = true;
  1447. }
  1448. else {
  1449. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_UNKNOWN, regeditValue);
  1450. vbsType = 0;
  1451. }
  1452. }
  1453. else {
  1454. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_CHECK_AUTO_STARTUP_FROM_REGIST_FAILED,
  1455. CSimpleStringA::Format("RegQueryValueEx error returned %u, GLE=%u.", lResult, GetLastError()));
  1456. }
  1457. }
  1458. else {
  1459. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_CHECK_AUTO_STARTUP_FROM_REGIST_FAILED,
  1460. CSimpleStringA::Format("RegOpenKeyEx error, GLE=%u.", GetLastError()));
  1461. }
  1462. RegCloseKey(hKey);
  1463. if (vbsType == 0 || vbsType == -1) {
  1464. CSimpleStringA strLnkPath(true);
  1465. bool scriptType = false;
  1466. if (IsHasSetAutoStartupByFolder(strLnkPath, scriptType)) {
  1467. if (!scriptType) {
  1468. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_WITH_STARTMENU_FROMSETUP, strLnkPath);
  1469. vbsType = 3;
  1470. }
  1471. else {
  1472. LogWarn(Severity_Low, Error_Debug, LOG_WARN_CHECK_AUTO_STARTUP_WITH_STARTMENU_FROMSCRIPT, strLnkPath);
  1473. vbsType = 4;
  1474. }
  1475. }
  1476. else if (vbsType == 0 && explorerSet) {
  1477. LogWarn(Severity_Low, Error_Debug, LOG_WARN_NOT_AUTO_STARTUP_FROM_REGIST, regeditValue);
  1478. }
  1479. }
  1480. return vbsType;
  1481. }
  1482. ErrorCodeEnum ResourceWatcherFSM::ChangeAutoStartupWithExe(bool resetVBS, bool resetExplorer)
  1483. {
  1484. const char* exploreExe = "explorer.exe";
  1485. ErrorCodeEnum result(Error_Succeed);
  1486. CSimpleStringA exePath(true);
  1487. if (resetExplorer) {
  1488. exePath = exploreExe;
  1489. }
  1490. else
  1491. {
  1492. result = GetEntityBase()->GetFunction()->GetPath("RootVer", exePath);
  1493. if (exePath.IsNullOrEmpty() || result != Error_Succeed) {
  1494. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A09").setAPI("ChangeAutoStartupWithExe")("Get RootVer path failed: %d", result);
  1495. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED, CSimpleStringA::Format("Get RootVer path failed: %d", result));
  1496. return Error_Unexpect;
  1497. }
  1498. if (!resetVBS)
  1499. exePath.Append("\\VTM.exe");
  1500. else
  1501. exePath.Append("\\spexplorerfast.vbs");
  1502. if (!ExistsFileA(exePath)) {
  1503. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A09").setAPI("ChangeAutoStartupWithExe")("[%s] is not existed!", exePath.GetData());
  1504. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED, CSimpleStringA::Format("[%s] is not existed!", exePath.GetData()));
  1505. return Error_NotExist;
  1506. }
  1507. }
  1508. DWORD dwFlag = KEY_WRITE;
  1509. if (Is32R64Platform() != 0) {
  1510. dwFlag |= KEY_WOW64_64KEY;
  1511. }
  1512. HKEY hKey;
  1513. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
  1514. TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon"), 0, dwFlag, &hKey);
  1515. if (lResult == ERROR_SUCCESS) {
  1516. lResult = RegSetValueExA(hKey, "Shell", 0, REG_SZ, (const BYTE*)exePath.GetData(), exePath.GetLength());
  1517. if (lResult == ERROR_SUCCESS) {
  1518. LogWarn(Severity_Low, Error_Debug, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_SUCC
  1519. , CSimpleStringA::Format("RegSetValueExA for Shell with %s succ!", exePath.GetData()));
  1520. result = Error_Succeed;
  1521. }
  1522. else
  1523. {
  1524. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A09").setAPI("ChangeAutoStartupWithExe")
  1525. ("RegSetValueExA for Shell with %s failed: %d", exePath.GetData(), lResult);
  1526. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED
  1527. , CSimpleStringA::Format("RegSetValueExA for Shell with %s failed: %d", exePath.GetData(), lResult));
  1528. result = Error_Unexpect;
  1529. }
  1530. }
  1531. else
  1532. {
  1533. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A09").setAPI("ChangeAutoStartupWithExe")
  1534. ("RegOpenKeyEx for write %s failed: %d", exePath.GetData(), lResult);
  1535. LogWarn(Severity_Middle, Error_Unexpect, LOG_WARN_UPDATE_AUTO_STARTUP_WITH_EXE_FAILED
  1536. , CSimpleStringA::Format("RegOpenKeyEx for write %s failed: %d", exePath.GetData(), lResult));
  1537. result = Error_Unexpect;
  1538. }
  1539. RegCloseKey(hKey);
  1540. return result;
  1541. }
  1542. int ResourceWatcherFSM::InitialAutoStartupSetType()
  1543. {
  1544. int ret = 0;
  1545. CSmartPointer<IConfigInfo> spConfig;
  1546. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spConfig);
  1547. int value(0);
  1548. spConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "AutoStartCMD", value);
  1549. if (value != 0) {
  1550. ret = value;
  1551. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Get AutoStartCMD from CS: %d", ret);
  1552. }
  1553. return ret;
  1554. }
  1555. BOOL ResourceWatcherFSM::IsHasSetAutoStartupByFolder(CSimpleStringA& strPath, bool& scriptsType)
  1556. {
  1557. BOOL result(FALSE);
  1558. strPath.Clear();
  1559. scriptsType = false;
  1560. const char* STARTUP_DIR_FULL_PATH = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp";
  1561. const char* STRATUP_FILENAME_FROM_SCRIPTS = "spexplorerauto.lnk";
  1562. #ifdef DEVOPS_ON_ST /*DevOps流水线编译,ST环境*/
  1563. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(ST测试).lnk";
  1564. #elif defined(DEVOPS_ON_UAT)/*DevOps流水线编译,UAT环境*/
  1565. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(UAT测试).lnk";
  1566. #elif defined(DEVOPS_ON_PRD)/*DevOps流水线编译,PRD环境*/
  1567. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台.lnk";
  1568. #elif defined(DEVOPS_ON_DEV)/*DevOps流水线编译,Dev环境*/
  1569. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台(开发).lnk";
  1570. #else/*本地编译等非DevOps环境编译的版本*/
  1571. const char* CMB_LINK_FILE_NAME = "招商银行可视柜台.lnk";
  1572. #endif
  1573. if (!ExistsDirA(STARTUP_DIR_FULL_PATH)) {
  1574. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] dir is not exist!", STARTUP_DIR_FULL_PATH);
  1575. return result;
  1576. }
  1577. strPath = STARTUP_DIR_FULL_PATH;
  1578. strPath += "\\";
  1579. strPath += CMB_LINK_FILE_NAME;
  1580. if (ExistsFileA(strPath)) {
  1581. result = TRUE;
  1582. }
  1583. else {
  1584. auto arr = fileutil_get_sub_files(STARTUP_DIR_FULL_PATH);
  1585. if (arr != NULL) {
  1586. for (int i = 0; i < arr->nelts; ++i) {
  1587. char* file = ARRAY_IDX(arr, i, char*);
  1588. char* filename = strrchr(file, '\\');
  1589. if (filename != NULL) { filename += 1; }
  1590. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("autostartup[%s]", filename);
  1591. if (filename != NULL/* && strcmp(filename, CMB_LINK_FILE_NAME) == 0*/) {
  1592. CSimpleStringA strfilename(filename);
  1593. if (strfilename.IsStartWith("招商银行可视柜台") && strfilename.IsEndWith(".lnk")) {
  1594. strPath = file;
  1595. result = TRUE;
  1596. break;
  1597. }
  1598. }
  1599. }
  1600. toolkit_array_free2(arr);
  1601. }
  1602. }
  1603. if (!result) {
  1604. CSimpleStringA fullStartFileNameFromScripts(STARTUP_DIR_FULL_PATH);
  1605. fullStartFileNameFromScripts += "\\";
  1606. fullStartFileNameFromScripts += STRATUP_FILENAME_FROM_SCRIPTS;
  1607. if (ExistsFileA(fullStartFileNameFromScripts)) {
  1608. strPath = fullStartFileNameFromScripts;
  1609. scriptsType = true;
  1610. result = TRUE;
  1611. }
  1612. else {
  1613. // Get and display the user name.
  1614. const DWORD INFO_BUFFER_SIZE = 2048;
  1615. char infoBuf[INFO_BUFFER_SIZE];
  1616. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  1617. DWORD bufCharCount = INFO_BUFFER_SIZE;
  1618. if (!GetUserName(infoBuf, &bufCharCount)) {
  1619. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetUserName failed, GLE=%u", GetLastError());
  1620. }
  1621. else {
  1622. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("User name:%s", infoBuf);
  1623. fullStartFileNameFromScripts = CSimpleStringA::Format("C:\\Users\\%s\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup", infoBuf);
  1624. fullStartFileNameFromScripts += "\\";
  1625. fullStartFileNameFromScripts += STRATUP_FILENAME_FROM_SCRIPTS;
  1626. if (ExistsFileA(fullStartFileNameFromScripts)) {
  1627. scriptsType = true;
  1628. strPath = fullStartFileNameFromScripts;
  1629. result = TRUE;
  1630. }
  1631. }
  1632. }
  1633. }
  1634. return result;
  1635. }
  1636. void ResourceWatcherFSM::DetectVersionHasChangedAndWarn()
  1637. {
  1638. CSmartPointer<IConfigInfo> spRunConfig;
  1639. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  1640. UINT64 utVersion = 0;
  1641. spRunConfig->ReadConfigValueHexInt("VersionMonitor", "LastVer", utVersion);
  1642. CVersion lastVer(utVersion);
  1643. if (lastVer.IsValid() && lastVer > m_RvcSysinfo.InstallVersion) {
  1644. CSimpleStringA rootVerPath;
  1645. CSimpleStringA warnInfo = CSimpleStringA::Format("version changed from %s to %s", lastVer.ToString().GetData(), m_RvcSysinfo.InstallVersion.ToString().GetData());
  1646. GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  1647. CSimpleStringA csPath = rootVerPath + SPLIT_SLASH_STR + "active.txt";
  1648. if (!ExistsFileA(csPath)) {
  1649. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A0A").setAPI(__FUNCTION__)
  1650. ("%s: active.txt not exist!", warnInfo.GetData());
  1651. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format("%s: active.txt not exist!", warnInfo.GetData()));
  1652. }
  1653. else
  1654. {
  1655. CSimpleFileComponent activeFileInfo;
  1656. HANDLE hFile = CreateFileA(
  1657. csPath,
  1658. GENERIC_READ,
  1659. FILE_SHARE_READ,
  1660. NULL,
  1661. OPEN_EXISTING,
  1662. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS,
  1663. NULL);
  1664. if (hFile == INVALID_HANDLE_VALUE) {
  1665. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A0A").setAPI(__FUNCTION__)
  1666. ("%s: active.txt open failed %u", warnInfo.GetData(), GetLastError());
  1667. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format("%s: active.txt open failed %u", warnInfo.GetData(), GetLastError()));
  1668. }
  1669. else
  1670. {
  1671. GetFileTime(hFile, (LPFILETIME)&activeFileInfo.mftCreate,
  1672. (LPFILETIME)&activeFileInfo.mftAccess, (LPFILETIME)&activeFileInfo.mftModified);
  1673. CloseHandle(hFile);
  1674. char szFormat1[128] = { 0 };
  1675. GetTimeFormatStr(szFormat1, 128, (FILETIME*)&activeFileInfo.mftCreate);
  1676. char szFormat2[128] = { 0 };
  1677. GetTimeFormatStr(szFormat2, 128, (FILETIME*)&activeFileInfo.mftAccess);
  1678. char szFormat3[128] = { 0 };
  1679. GetTimeFormatStr(szFormat3, 128, (FILETIME*)&activeFileInfo.mftModified);
  1680. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A0A").setAPI(__FUNCTION__)
  1681. ("%s: active.txt create at %s, access at %s, modified at %s", warnInfo.GetData(), szFormat1, szFormat2, szFormat3);
  1682. LogWarn(Severity_Middle, Error_Debug, LOG_WARN_ACTIVE_FILE_CHANGE, CSimpleStringA::Format(
  1683. "%s: active.txt create at %s, access at %s, modified at %s", warnInfo.GetData(), szFormat1, szFormat2, szFormat3));
  1684. }
  1685. }
  1686. }
  1687. if (!lastVer.IsValid() || lastVer != m_RvcSysinfo.InstallVersion) {
  1688. spRunConfig->WriteConfigValueHexInt("VersionMonitor", "LastVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  1689. }
  1690. }
  1691. void ResourceWatcherFSM::DetectDestopFileAndWarn(bool bClear, CSimpleStringA& strFileSaveList)
  1692. {
  1693. const DWORD INFO_BUFFER_SIZE = 2048;
  1694. char infoBuf[INFO_BUFFER_SIZE];
  1695. DWORD bufCharCount = INFO_BUFFER_SIZE;
  1696. char sys_disk = '\0';
  1697. bufCharCount = INFO_BUFFER_SIZE;
  1698. if (!GetComputerName(infoBuf, &bufCharCount))
  1699. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetComputerName failed, GLE=%u", GetLastError());
  1700. else DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Computer name: %s", infoBuf);
  1701. // Get and display the user name.
  1702. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  1703. bufCharCount = INFO_BUFFER_SIZE;
  1704. if (!GetUserName(infoBuf, &bufCharCount)) {
  1705. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetUserName failed, GLE=%u", GetLastError());
  1706. }
  1707. else
  1708. {
  1709. CSimpleStringA filelist(true);
  1710. int dirCount(0), fileCount(0);
  1711. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("User name: %s", infoBuf);
  1712. CSimpleStringA desktopFullPath = CSimpleStringA::Format("C:\\Users\\%s\\Desktop", infoBuf);
  1713. CSimpleStringA desktopPublicPath("C:\\Users\\Public\\Desktop");
  1714. CAutoArray<CSimpleStringA> desktopPaths;
  1715. desktopPaths.Init(2);
  1716. desktopPaths[0] = desktopFullPath;
  1717. desktopPaths[1] = desktopPublicPath;
  1718. for (int k = 0; k < desktopPaths.GetCount(); ++k) {
  1719. CSimpleStringA& curPath = desktopPaths[k];
  1720. auto arr = fileutil_get_sub_files(curPath);
  1721. if (arr != NULL) {
  1722. for (int i = 0; i < arr->nelts; ++i) {
  1723. char* file = ARRAY_IDX(arr, i, char*);
  1724. char* filename = strrchr(file, '\\');
  1725. if (filename != NULL) { filename += 1; }
  1726. else { filename = file; }
  1727. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("filename:%s", filename);
  1728. bool toRecord = true;
  1729. if (bClear) {
  1730. std::string strLowFileName = SP::Utility::ToLower(std::string(filename));
  1731. if (strFileSaveList.IsNullOrEmpty() || strFileSaveList.IndexOf(strLowFileName.c_str()) == -1) {
  1732. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("delete desktop file:%s", filename);
  1733. RemoveFileA(file);
  1734. if (!ExistsFileA(file)) {
  1735. toRecord = false;
  1736. }
  1737. }
  1738. else {
  1739. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("skip to delete: %s", filename);
  1740. }
  1741. }
  1742. if (toRecord) {
  1743. fileCount++;
  1744. if (!filelist.IsNullOrEmpty()) {
  1745. filelist += "|";
  1746. }
  1747. filelist += filename;
  1748. }
  1749. }
  1750. if (arr->nelts > 0) {
  1751. filelist += ";";
  1752. }
  1753. toolkit_array_free2(arr);
  1754. }
  1755. arr = fileutil_get_sub_dirs(curPath);
  1756. if (arr != NULL) {
  1757. for (int i = 0; i < arr->nelts; ++i) {
  1758. char* dir = ARRAY_IDX(arr, i, char*);
  1759. char* dirname = strrchr(dir, '\\');
  1760. if (dirname != NULL) { dirname += 1; }
  1761. else { dirname = dir; }
  1762. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("dir name:%s", dirname);
  1763. bool toRecord = true;
  1764. if (bClear) {
  1765. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("remove desktop dir:%s", dirname);
  1766. RemoveDirRecursiveA(dir);
  1767. if (!ExistsDirA(dir)) {
  1768. toRecord = false;
  1769. }
  1770. }
  1771. if (toRecord) {
  1772. dirCount++;
  1773. if (!filelist.IsNullOrEmpty() && i != 0) {
  1774. filelist += "|";
  1775. }
  1776. filelist += dirname;
  1777. }
  1778. }
  1779. if (arr->nelts > 0) {
  1780. filelist += ";";
  1781. }
  1782. toolkit_array_free2(arr);
  1783. }
  1784. }
  1785. LogWarn(Severity_Low, Error_Debug, LOG_INFO_DESKTOP_FILESTATUS
  1786. ,CSimpleStringA::Format("{\"subject\":\"desktop_file\",\"clear_flag\":\"%d\",\"username\":\"%s\",\"file_count\":%d,\"dir_count\":%d,\"content\":\"%s\"}"
  1787. , bClear ? 1 : 0, infoBuf, fileCount, dirCount, filelist.GetLength() < 950 ? filelist.GetData() : (filelist.SubString(0, 950) + "....").GetData()));
  1788. }
  1789. }
  1790. void ResourceWatcherFSM::DetectAutoStartFileAndWarn()
  1791. {
  1792. const DWORD INFO_BUFFER_SIZE = 2048;
  1793. char infoBuf[INFO_BUFFER_SIZE];
  1794. DWORD bufCharCount = INFO_BUFFER_SIZE;
  1795. char sys_disk = '\0';
  1796. bufCharCount = INFO_BUFFER_SIZE;
  1797. if (!GetComputerName(infoBuf, &bufCharCount))
  1798. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetComputerName failed, GLE=%u", GetLastError());
  1799. else DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("Computer name: %s", infoBuf);
  1800. // Get and display the user name.
  1801. ZeroMemory(infoBuf, INFO_BUFFER_SIZE);
  1802. bufCharCount = INFO_BUFFER_SIZE;
  1803. if (!GetUserName(infoBuf, &bufCharCount)) {
  1804. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("GetUserName failed, GLE=%u", GetLastError());
  1805. }
  1806. else
  1807. {
  1808. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("User name: %s", infoBuf);
  1809. CSimpleStringA startMenuFullPath = CSimpleStringA::Format("C:\\Users\\%s\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup", infoBuf);
  1810. CSimpleStringA startMenuPublicPath("C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp");
  1811. CAutoArray<CSimpleStringA> desktopPaths;
  1812. CAutoArray<CSimpleStringA> fileContents;
  1813. CAutoArray<unsigned int> fileCounts;
  1814. desktopPaths.Init(2);
  1815. fileContents.Init(2);
  1816. fileCounts.Init(2);
  1817. desktopPaths[0] = startMenuFullPath;
  1818. desktopPaths[1] = startMenuPublicPath;
  1819. fileContents[0] = "";
  1820. fileContents[1] = "";
  1821. fileCounts[0] = 0;
  1822. fileCounts[1] = 0;
  1823. for (int k = 0; k < desktopPaths.GetCount(); ++k) {
  1824. CSimpleStringA& curPath = desktopPaths[k];
  1825. CSimpleStringA& curVal = fileContents[k];
  1826. auto arr = fileutil_get_sub_files(curPath);
  1827. if (arr != NULL) {
  1828. for (int i = 0; i < arr->nelts; ++i) {
  1829. char* file = ARRAY_IDX(arr, i, char*);
  1830. char* filename = strrchr(file, '\\');
  1831. if (filename != NULL) { filename += 1; }
  1832. else { filename = file; }
  1833. fileCounts[k]++;
  1834. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM).setAPI(__FUNCTION__)("filename:%s", filename);
  1835. if (!curVal.IsNullOrEmpty()) {
  1836. curVal += "|";
  1837. }
  1838. curVal += filename;
  1839. }
  1840. toolkit_array_free2(arr);
  1841. }
  1842. }
  1843. LogWarn(Severity_Low, Error_Debug, LOG_INFO_AUTOSTART_FILESTATUS
  1844. , CSimpleStringA::Format("{\"subject\":\"autostart_file\",\"username\":\"%s\",\"user\":\"%s\",\"public\":\"%s\"}"
  1845. ,infoBuf, fileContents[0].GetData(), fileContents[1].GetData()));
  1846. }
  1847. }
  1848. ErrorCodeEnum ResourceWatcherFSM::DetectVTMInstalledBySetup(BOOL& fYes)
  1849. {
  1850. HKEY key;
  1851. ErrorCodeEnum result(Error_Succeed);
  1852. fYes = FALSE;
  1853. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{123BBC1D-8555-4E90-96CA-70E678FF5C24}_is1";
  1854. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key);
  1855. if (ERROR_SUCCESS == lResult) {
  1856. fYes = TRUE;
  1857. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Found {123BBC1D-8555-4E90-96CA-70E678FF5C24}");
  1858. LogWarn(Severity_Low, Error_Debug, LOG_INFO_INSTALL_BY_SETUP, "Intalled by Setup");
  1859. }
  1860. else if (ERROR_FILE_NOT_FOUND == lResult)
  1861. {
  1862. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Not Found {123BBC1D-8555-4E90-96CA-70E678FF5C24}");
  1863. fYes = FALSE;
  1864. }
  1865. else
  1866. {
  1867. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegOpenKeyEx For{123BBC1D-8555-4E90-96CA-70E678FF5C24} error, Result=%ld.", lResult);
  1868. fYes = FALSE;
  1869. result = Error_Unexpect;
  1870. }
  1871. RegCloseKey(key);
  1872. return result;
  1873. }
  1874. bool ResourceWatcherFSM::RegRdVtmVersion(CSimpleStringA& VTMpath, CSimpleStringA& vtmVersion)
  1875. {
  1876. bool bRet = false;
  1877. HKEY key;
  1878. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\VTM";
  1879. CSimpleStringA regParaPath = "path";
  1880. CSimpleStringA regParaVersion = "version";
  1881. LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key);
  1882. char arrVTMpath[MAX_PATH] = { 0 }, arrVTMversion[MAX_PATH] = { 0 };
  1883. if (ERROR_SUCCESS == lResult)
  1884. {
  1885. DWORD dwValue = MAX_PATH * sizeof(CHAR);
  1886. bool res1 = GetRegValue(key, regParaPath, arrVTMpath, &dwValue);
  1887. if (res1) {
  1888. bRet = true;
  1889. VTMpath = arrVTMpath;
  1890. }
  1891. else {
  1892. bRet = false;
  1893. RegCloseKey(key);
  1894. return bRet;
  1895. }
  1896. dwValue = MAX_PATH * sizeof(CHAR);
  1897. bool res2 = GetRegValue(key, regParaVersion, arrVTMversion, &dwValue);
  1898. if (res2) {
  1899. bRet = true;
  1900. vtmVersion = arrVTMversion;
  1901. }
  1902. else {
  1903. bRet = false;
  1904. RegCloseKey(key);
  1905. return bRet;
  1906. }
  1907. }
  1908. else
  1909. {
  1910. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("%s::RegOpenKeyEx error, Result=%ld.", __FUNCTION__, lResult);
  1911. bRet = false;
  1912. }
  1913. RegCloseKey(key);
  1914. return bRet;
  1915. }
  1916. bool ResourceWatcherFSM::RegWtVtmPath()
  1917. {
  1918. bool bRet = true;
  1919. HKEY key;
  1920. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths";
  1921. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key))
  1922. {
  1923. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open Reg failed.");
  1924. bRet = false;
  1925. }
  1926. DWORD dwDisposition;
  1927. regPath += "\\VTM";
  1928. if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, NULL,
  1929. REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dwDisposition))
  1930. {
  1931. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Create key failed");
  1932. bRet = false;
  1933. }
  1934. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, KEY_ALL_ACCESS, &key))
  1935. {
  1936. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  1937. bRet = false;
  1938. }
  1939. CSimpleStringA para = "path";
  1940. CSimpleStringA exePath;
  1941. ErrorCodeEnum Error = GetEntityBase()->GetFunction()->GetPath("RootVer", exePath);
  1942. if (Error_Succeed == Error)
  1943. {
  1944. exePath += "\\VTM.exe";
  1945. if (ERROR_SUCCESS != RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)exePath.GetData(), MAX_PATH))
  1946. {
  1947. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set path value failed");
  1948. bRet = false;
  1949. }
  1950. }
  1951. else
  1952. {
  1953. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get path of VTM.exe failed.");
  1954. }
  1955. ::RegCloseKey(key);
  1956. return bRet;
  1957. }
  1958. bool ResourceWatcherFSM::RegWtVtmVersion()
  1959. {
  1960. bool bRet = true;
  1961. HKEY key;
  1962. CSimpleStringA regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths";
  1963. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath, 0, KEY_ALL_ACCESS, &key))
  1964. {
  1965. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Open Reg failed.");
  1966. bRet = false;
  1967. }
  1968. DWORD dwDisposition;
  1969. regPath += "\\VTM";
  1970. if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, NULL,
  1971. REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &key, &dwDisposition))
  1972. {
  1973. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Create key failed");
  1974. bRet = false;
  1975. }
  1976. if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, regPath.GetData(), 0, KEY_ALL_ACCESS, &key))
  1977. {
  1978. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  1979. bRet = false;
  1980. }
  1981. CSimpleStringA para = "version";
  1982. CSimpleStringA csVersion;
  1983. if (GetVtmVersionFromActiveTxt(csVersion))
  1984. {
  1985. //RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)csVersion.GetData(), MAX_PATH);
  1986. if (ERROR_SUCCESS != RegSetValueEx(key, para.GetData(), 0, REG_SZ, (BYTE*)csVersion.GetData(), MAX_PATH))
  1987. {
  1988. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set value failed");
  1989. bRet = false;
  1990. }
  1991. }
  1992. else
  1993. {
  1994. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Get version of VTM.exe failed.");
  1995. }
  1996. ::RegCloseKey(key);
  1997. return bRet;
  1998. }
  1999. bool ResourceWatcherFSM::RegOperation()
  2000. {
  2001. bool bRet = true;
  2002. CSimpleStringA csVersion, VtmRegPath, VtmRegVersion;
  2003. bool bGetActive = GetVtmVersionFromActiveTxt(csVersion);
  2004. bool bRegRead = RegRdVtmVersion(VtmRegPath, VtmRegVersion);
  2005. CSimpleStringA rootVerPath, exePath;
  2006. ErrorCodeEnum rc = GetEntityBase()->GetFunction()->GetPath("RootVer", rootVerPath);
  2007. exePath = rootVerPath + "\\VTM.exe";
  2008. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("csVersion :%s ,VtmRegVersion:%s ", csVersion.GetData(), VtmRegVersion.GetData());
  2009. if (!ExistsFileA(exePath) || !bGetActive || !bRegRead || (0 != VtmRegVersion.Compare(csVersion, true)))
  2010. {
  2011. if (!ExistsFileA(exePath) && !CopyExeToRoot(csVersion))
  2012. {
  2013. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Copy VTM.exe to version root fail.");
  2014. bRet = false;
  2015. }
  2016. else
  2017. {
  2018. if (!RegWtVtmPath())
  2019. {
  2020. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegWtVtmPath failed.");
  2021. }
  2022. if (!RegWtVtmVersion())
  2023. {
  2024. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("RegWtVtmVersion failed.");
  2025. }
  2026. CreateLink(exePath, csVersion);
  2027. }
  2028. }
  2029. return bRet;
  2030. }
  2031. bool ResourceWatcherFSM::UpdateExe()
  2032. {
  2033. int updateExe = 0;
  2034. CSmartPointer<IConfigInfo> spCtSettingConfig;
  2035. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  2036. spCtSettingConfig->ReadConfigValueInt("NonExclusive", "UpdateExe", updateExe);
  2037. if (updateExe == 1)
  2038. return true;
  2039. return false;
  2040. }
  2041. void ResourceWatcherFSM::VerifySignature()
  2042. {
  2043. LOG_FUNCTION();
  2044. CSimpleStringA strMsg(true);
  2045. char* buffer = new char[MAX_PATH];
  2046. getcwd(buffer, MAX_PATH);
  2047. strcat(buffer, "\\*");
  2048. DWORD elapsed = 0;
  2049. DWORD dwStart = GetTickCount();
  2050. DWORD dwEnd = GetTickCount();
  2051. VerifySignature(buffer);
  2052. if (m_nonSignedFiles.size() > 0)
  2053. {
  2054. CSimpleStringA fileList = "";
  2055. for (size_t i = 0; i < m_nonSignedFiles.size(); i++)
  2056. {
  2057. fileList += GetFileName(m_nonSignedFiles[i]);
  2058. if (i < m_nonSignedFiles.size() - 1)
  2059. fileList += ",";
  2060. }
  2061. int toDisplay = m_iNonSignedTotal < m_iNonSignedDisplay ? m_iNonSignedTotal : m_iNonSignedDisplay;
  2062. strMsg = CSimpleStringA::Format("共有%d个文件未签名,其中%d个为:%s.",
  2063. m_iNonSignedTotal, toDisplay, fileList.GetData());
  2064. }
  2065. dwEnd = GetTickCount();
  2066. elapsed = dwEnd - dwStart;
  2067. strMsg = strMsg + CSimpleStringA::Format("签名耗时:%dms", elapsed);
  2068. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_FILE_NOT_TRUSTED, (LPCTSTR)strMsg);
  2069. delete buffer;
  2070. }
  2071. void ResourceWatcherFSM::VerifySignature(const CSimpleStringA& filePath)
  2072. {
  2073. HANDLE hFind = NULL;
  2074. WIN32_FIND_DATA fileInfo;
  2075. DWORD64 dwSize = 0;
  2076. hFind = FindFirstFile(filePath, &fileInfo);
  2077. if (hFind == INVALID_HANDLE_VALUE)
  2078. return;
  2079. string strDirPath = filePath;
  2080. do
  2081. {
  2082. if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
  2083. {
  2084. if (!strcmp(fileInfo.cFileName, ".") || !strcmp(fileInfo.cFileName, ".."))
  2085. {
  2086. //Do nothing for "." and ".." folders
  2087. }
  2088. else
  2089. {
  2090. strDirPath.insert(strDirPath.find("*"), string(fileInfo.cFileName) + "\\");
  2091. VerifySignature(strDirPath.c_str());
  2092. strDirPath = filePath;
  2093. }
  2094. }
  2095. else
  2096. {
  2097. CSimpleStringA fileName = fileInfo.cFileName;
  2098. string strFileName = fileName;
  2099. string strFilePath;
  2100. if(strFileName.empty()
  2101. || (strFileName.rfind(".dll") != strFileName.length() - 4
  2102. && strFileName.rfind(".exe") != strFileName.length() - 4))
  2103. continue;
  2104. strFilePath = strDirPath;
  2105. strFilePath.replace(strFilePath.find("*"), strFilePath.length(), string(fileInfo.cFileName));
  2106. if (!RetrieveDigitalSignatureInfo(strFilePath.c_str()))
  2107. {
  2108. if (m_iNonSignedTotal < m_iNonSignedDisplay)
  2109. {
  2110. m_nonSignedFiles.push_back(strFilePath.c_str());
  2111. }
  2112. m_iNonSignedTotal++;
  2113. }
  2114. }
  2115. } while (FindNextFile(hFind, &fileInfo));
  2116. FindClose(hFind);
  2117. }
  2118. void ResourceWatcherFSM::DetectAndClearDesktopFile()
  2119. {
  2120. #if defined(RVC_OS_WIN)
  2121. CSmartPointer<IConfigInfo> spCtSettingConfig;
  2122. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  2123. int clearDesktopFlag(0);
  2124. CSimpleStringA strFileWhiteSheet(true);
  2125. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "ClearDesktopSwitch", clearDesktopFlag);
  2126. if (!!clearDesktopFlag) {
  2127. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), "DesktopWhiteSheet", strFileWhiteSheet);
  2128. if (!strFileWhiteSheet.IsNullOrEmpty()) {
  2129. std::string strLowFileName = SP::Utility::ToLower(std::string(strFileWhiteSheet.GetData()));
  2130. strFileWhiteSheet = strLowFileName.c_str();
  2131. }
  2132. }
  2133. DetectDestopFileAndWarn(!!clearDesktopFlag, strFileWhiteSheet);
  2134. #endif //RVC_OS_WIN
  2135. }
  2136. CSimpleStringA ResourceWatcherFSM::GetFileName(const CSimpleStringA& filePath)
  2137. {
  2138. CSimpleStringA tmp = filePath;
  2139. auto arrPath = tmp.Split('\\');
  2140. int size = arrPath.GetCount();
  2141. return arrPath[size - 1];
  2142. }
  2143. bool ResourceWatcherFSM::RetrieveDigitalSignatureInfo(const char* pFilePath)
  2144. {
  2145. HCERTSTORE hStore = NULL;
  2146. HCRYPTMSG hMsg = NULL;
  2147. WCHAR* wpFilePath = NULL;
  2148. int len = ::MultiByteToWideChar(CP_ACP, 0, pFilePath, -1, NULL, 0);
  2149. if (len > 0) {
  2150. wpFilePath = new wchar_t[len + 1];
  2151. std::memset(wpFilePath, 0, (len + 1) * sizeof(wchar_t));
  2152. ::MultiByteToWideChar(CP_ACP, 0, pFilePath, -1, &wpFilePath[0], len);
  2153. }
  2154. if (CryptQueryObject(CERT_QUERY_OBJECT_FILE,
  2155. wpFilePath,
  2156. CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
  2157. CERT_QUERY_FORMAT_FLAG_BINARY,
  2158. 0,
  2159. NULL,
  2160. NULL,
  2161. NULL,
  2162. &hStore,
  2163. &hMsg,
  2164. NULL))
  2165. {
  2166. DWORD dwCountSigners = 0;
  2167. DWORD dwcbSz = sizeof(dwCountSigners);
  2168. if (CryptMsgGetParam(hMsg, CMSG_SIGNER_COUNT_PARAM, 0, &dwCountSigners, &dwcbSz))
  2169. {
  2170. if (dwCountSigners != 0)
  2171. {
  2172. dwcbSz = 0;
  2173. CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwcbSz);
  2174. if (dwcbSz)
  2175. {
  2176. PCMSG_SIGNER_INFO pSignerInfo = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwcbSz];
  2177. if (pSignerInfo)
  2178. {
  2179. DWORD dwcbSz2 = dwcbSz;
  2180. if (CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, pSignerInfo, &dwcbSz) &&
  2181. dwcbSz == dwcbSz2)
  2182. {
  2183. if (VerifyFirstCertificate(hStore, pSignerInfo)
  2184. || VerifyOtherCertificate(pSignerInfo))
  2185. return true;
  2186. }
  2187. delete[] pSignerInfo;
  2188. pSignerInfo = NULL;
  2189. }
  2190. }
  2191. }
  2192. }
  2193. }
  2194. if (hStore != NULL)
  2195. {
  2196. CertCloseStore(hStore, 0);
  2197. hStore = NULL;
  2198. }
  2199. if (hMsg != NULL)
  2200. {
  2201. CryptMsgClose(hMsg);
  2202. hMsg = NULL;
  2203. }
  2204. return false;
  2205. }
  2206. bool ResourceWatcherFSM::VerifyFirstCertificate(HCERTSTORE hStore, PCMSG_SIGNER_INFO pSignerInfo)
  2207. {
  2208. CERT_INFO ci = { 0 };
  2209. ci.Issuer = pSignerInfo->Issuer;
  2210. ci.SerialNumber = pSignerInfo->SerialNumber;
  2211. PCCERT_CONTEXT pCertContext = NULL;
  2212. int c = 0;
  2213. bool ret = false;
  2214. for (;; c++)
  2215. {
  2216. pCertContext = CertFindCertificateInStore(hStore,
  2217. ENCODING, 0, CERT_FIND_SUBJECT_CERT,
  2218. (PVOID)&ci, pCertContext);
  2219. if (!pCertContext)
  2220. {
  2221. break;
  2222. }
  2223. DWORD dwcbSz;
  2224. char* pBuff;
  2225. dwcbSz = CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, NULL, 0);
  2226. if (dwcbSz != 0)
  2227. {
  2228. pBuff = new (std::nothrow) char[dwcbSz];
  2229. if (pBuff)
  2230. {
  2231. if (CertGetNameString(pCertContext, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, NULL, pBuff, dwcbSz) == dwcbSz)
  2232. {
  2233. if (!strcmp(pBuff, "China Merchants Bank Co., Ltd") || !strcmp(pBuff, "Microsoft Corporation"))
  2234. ret = true;
  2235. }
  2236. delete[] pBuff;
  2237. pBuff = NULL;
  2238. }
  2239. }
  2240. }
  2241. if (pCertContext)
  2242. {
  2243. CertFreeCertificateContext(pCertContext);
  2244. pCertContext = NULL;
  2245. }
  2246. return ret;
  2247. }
  2248. bool ResourceWatcherFSM::VerifyOtherCertificate(PCMSG_SIGNER_INFO pSignerInfo)
  2249. {
  2250. int ret = false;
  2251. for (DWORD a = 0; a < pSignerInfo->UnauthAttrs.cAttr; a++)
  2252. {
  2253. #ifndef szOID_NESTED_SIGNATURE
  2254. #define szOID_NESTED_SIGNATURE "1.3.6.1.4.1.311.2.4.1"
  2255. #endif
  2256. if (pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId &&
  2257. lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId, szOID_NESTED_SIGNATURE) == 0)
  2258. {
  2259. HCRYPTMSG hMsg = ::CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, 0, NULL, NULL, NULL);
  2260. if (hMsg)
  2261. {
  2262. if (::CryptMsgUpdate(hMsg,
  2263. pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData,
  2264. pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData,
  2265. TRUE))
  2266. {
  2267. DWORD dwSignerInfo = 0;
  2268. ::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
  2269. if (dwSignerInfo != 0)
  2270. {
  2271. PCMSG_SIGNER_INFO pSignerInfo2 = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwSignerInfo];
  2272. if (pSignerInfo2)
  2273. {
  2274. if (::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM,
  2275. 0, (PVOID)pSignerInfo2, &dwSignerInfo))
  2276. {
  2277. CRYPT_DATA_BLOB c7Data;
  2278. c7Data.cbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData;
  2279. c7Data.pbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData;
  2280. //ret = FindAppropriateStoreAndVerifyFirstCertificate(pSignerInfo2, &c7Data);
  2281. HCERTSTORE hStore = NULL;
  2282. hStore = CertOpenStore(CERT_STORE_PROV_PKCS7, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, NULL, 0, &c7Data);
  2283. ret = hStore && VerifyFirstCertificate(hStore, pSignerInfo2);
  2284. if (hStore)
  2285. {
  2286. ::CertCloseStore(hStore, CERT_CLOSE_STORE_FORCE_FLAG);
  2287. hStore = NULL;
  2288. }
  2289. }
  2290. delete[] pSignerInfo2;
  2291. pSignerInfo2 = NULL;
  2292. }
  2293. }
  2294. }
  2295. ::CryptMsgClose(hMsg);
  2296. }
  2297. }
  2298. }
  2299. return ret;
  2300. }
  2301. long long GetDirSizeFsm(string dirPath)
  2302. {
  2303. long long fileLen = 0;
  2304. long hFile = 0;
  2305. //文件信息
  2306. struct _finddata_t fileinfo;
  2307. string p;
  2308. if ((hFile = _findfirst(p.assign(dirPath).append("\\*").c_str(), &fileinfo)) != -1)
  2309. {
  2310. do
  2311. {
  2312. //如果是目录,迭代之
  2313. //如果不是,加入列表
  2314. if ((fileinfo.attrib & _A_SUBDIR))
  2315. {
  2316. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  2317. fileLen += GetDirSizeFsm(p.assign(dirPath).append("\\").append(fileinfo.name));
  2318. }
  2319. else
  2320. {
  2321. fileLen += fileinfo.size;
  2322. }
  2323. } while (_findnext(hFile, &fileinfo) == 0);
  2324. _findclose(hFile);
  2325. }
  2326. return fileLen;
  2327. }
  2328. struct CmpByValueFromBiggest //从最大的排起
  2329. {
  2330. bool operator()(const pair<string, long>& l, const pair<string, long>& r) {
  2331. return l.second > r.second;
  2332. }
  2333. };
  2334. //unordered_map<string, long> fileSpace;
  2335. unordered_map<string, long> fileIncreasedSpace;
  2336. vector<pair<string, long>> sortFileIncreasedSpace;
  2337. unordered_map<string, long> fileSpace;
  2338. vector<pair<string, long>> sortFileSpace;
  2339. static bool spaceLock = false;
  2340. void ResourceWatcherFSM::CheckDiskFileSpace()
  2341. {
  2342. if (spaceLock)
  2343. {
  2344. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("当前已有硬盘扫描进行中,跳过。");
  2345. return;
  2346. }
  2347. else
  2348. {
  2349. spaceLock = true; //加锁
  2350. }
  2351. CSmartPointer<IConfigInfo> spConfigRun;
  2352. CSmartPointer<IConfigInfo> spCtSettingConfig;
  2353. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  2354. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  2355. int lastDiskUsed = 0;
  2356. unsigned long long lastVer = 0;
  2357. int spaceIncrease = 0; //硬盘增长阈值
  2358. spConfigRun->ReadConfigValueHexInt("SpaceInfo", "OptVer", lastVer);
  2359. spConfigRun->ReadConfigValueInt("SpaceInfo", "DiskTotalUsed(GB)", lastDiskUsed);
  2360. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "DiskUsedIncreaseInt(GB)", spaceIncrease);
  2361. if (spaceIncrease == 0)
  2362. {
  2363. spaceIncrease = 5; //默认阈值5GB
  2364. }
  2365. if (!m_bNeedForceDiskCheck) //是否需要强制全盘扫描 - 硬盘使用过高是会强制
  2366. {
  2367. if (lastVer == m_RvcSysinfo.InstallVersion.GetVersion64())
  2368. {
  2369. if (lastDiskUsed != 0 && ((int)(GetDiskUsedByte() / (1024 * 1024 * 1024)) - lastDiskUsed) < spaceIncrease) //增长值判定
  2370. {
  2371. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("硬盘空间增长未超过阈值,无需扫描。");
  2372. if (spaceLock)
  2373. {
  2374. spaceLock = false; //释放锁
  2375. }
  2376. return;
  2377. }
  2378. else
  2379. {
  2380. //降低磁盘扫描频率
  2381. SYSTEMTIME localTime;
  2382. GetLocalTime(&localTime);
  2383. if (m_diskLastWarnHour != localTime.wHour)
  2384. {
  2385. m_diskLastWarnHour = localTime.wHour;
  2386. CSmartPointer<IConfigInfo> spConfigRun;
  2387. ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  2388. if (eErr == Error_Succeed) {
  2389. spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  2390. }
  2391. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("硬盘增长超过阈值,重点目录扫描!");
  2392. }
  2393. else
  2394. {
  2395. //DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("磁盘增长最近1小时已扫描一次,暂不扫描。");
  2396. if (spaceLock)
  2397. {
  2398. spaceLock = false; //释放锁
  2399. }
  2400. return;
  2401. }
  2402. }
  2403. }
  2404. else
  2405. {
  2406. spConfigRun->WriteConfigValueHexInt("SpaceInfo", "OptVer", m_RvcSysinfo.InstallVersion.GetVersion64());
  2407. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("新版本,重点目录扫描");
  2408. }
  2409. }
  2410. else
  2411. {
  2412. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("强制扫描。");
  2413. }
  2414. string path = "D:";
  2415. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("扫描D盘。");
  2416. long long fileLen = 0;
  2417. long hFile = 0;
  2418. //文件信息
  2419. struct _finddata_t fileinfo;
  2420. string p;
  2421. if ((hFile = _findfirst(p.assign(path).append("\\*").c_str(), &fileinfo)) != -1)
  2422. {
  2423. do
  2424. {
  2425. //如果是目录,迭代之
  2426. //如果不是,加入列表
  2427. if ((fileinfo.attrib & _A_SUBDIR))
  2428. {
  2429. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  2430. fileLen = GetDirSizeFsm(p.assign(path).append("\\").append(fileinfo.name));
  2431. else
  2432. {
  2433. continue;
  2434. }
  2435. }
  2436. else
  2437. {
  2438. fileLen = fileinfo.size;
  2439. }
  2440. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  2441. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  2442. {
  2443. DOUBLE len = (DOUBLE)fileLen / 1024;
  2444. resLen = CSimpleStringA::Format("%.2f KB", len);
  2445. }
  2446. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  2447. {
  2448. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  2449. resLen = CSimpleStringA::Format("%.2f MB", len);
  2450. }
  2451. else if (fileLen >= (1024 * 1024 * 1024))
  2452. {
  2453. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  2454. resLen = CSimpleStringA::Format("%.2f GB", len);
  2455. }
  2456. CSimpleStringA oldLenStr("");
  2457. long oldLen = 0;
  2458. spConfigRun->ReadConfigValue("SpaceInfo",
  2459. p.assign(path).append("\\").append(fileinfo.name).c_str(), oldLenStr);
  2460. oldLen = atol(oldLenStr.GetData());
  2461. fileIncreasedSpace[p.assign(path).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  2462. fileSpace[p.assign(path).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  2463. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  2464. p.assign(path).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
  2465. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  2466. {
  2467. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(path).append("\\").append(fileinfo.name).c_str(),
  2468. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  2469. }
  2470. } while (_findnext(hFile, &fileinfo) == 0);
  2471. _findclose(hFile);
  2472. }
  2473. //获取version目录下的文件夹大小
  2474. CSimpleStringA csPath;
  2475. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("RootVer", csPath); //获取当前版本路劲 例如:C:\Run
  2476. fileLen = 0;
  2477. hFile = 0;
  2478. p = "";
  2479. if ((hFile = _findfirst(p.assign(csPath.GetData()).append("\\*").c_str(), &fileinfo)) != -1)
  2480. {
  2481. do
  2482. {
  2483. //如果是目录,迭代之
  2484. //如果不是,加入列表
  2485. if ((fileinfo.attrib & _A_SUBDIR))
  2486. {
  2487. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  2488. fileLen = GetDirSizeFsm(p.assign(csPath.GetData()).append("\\").append(fileinfo.name));
  2489. else
  2490. {
  2491. continue;
  2492. }
  2493. }
  2494. else
  2495. {
  2496. fileLen = fileinfo.size;
  2497. }
  2498. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  2499. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  2500. {
  2501. DOUBLE len = (DOUBLE)fileLen / 1024;
  2502. resLen = CSimpleStringA::Format("%.2f KB", len);
  2503. }
  2504. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  2505. {
  2506. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  2507. resLen = CSimpleStringA::Format("%.2f MB", len);
  2508. }
  2509. else if (fileLen >= (1024 * 1024 * 1024))
  2510. {
  2511. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  2512. resLen = CSimpleStringA::Format("%.2f GB", len);
  2513. }
  2514. CSimpleStringA oldLenStr(""); //MB
  2515. long oldLen = 0;
  2516. spConfigRun->ReadConfigValue("SpaceInfo",
  2517. p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(), oldLenStr);
  2518. oldLen = atol(oldLenStr.GetData());
  2519. fileIncreasedSpace[p.assign(csPath.GetData()).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  2520. fileSpace[p.assign(csPath.GetData()).append("\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  2521. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  2522. p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(), resLen.GetData());
  2523. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  2524. {
  2525. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(csPath.GetData()).append("\\").append(fileinfo.name).c_str(),
  2526. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  2527. }
  2528. } while (_findnext(hFile, &fileinfo) == 0);
  2529. _findclose(hFile);
  2530. }
  2531. //获取rvc目录下的文件夹大小
  2532. fileLen = 0;
  2533. hFile = 0;
  2534. p = "";
  2535. if ((hFile = _findfirst(p.assign(path).append("\\rvc\\*").c_str(), &fileinfo)) != -1)
  2536. {
  2537. do
  2538. {
  2539. //如果是目录,迭代之
  2540. //如果不是,加入列表
  2541. if ((fileinfo.attrib & _A_SUBDIR))
  2542. {
  2543. if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0)
  2544. fileLen = GetDirSizeFsm(p.assign(path).append("\\rvc\\").append(fileinfo.name));
  2545. else
  2546. {
  2547. continue;
  2548. }
  2549. }
  2550. else
  2551. {
  2552. fileLen = fileinfo.size;
  2553. }
  2554. CSimpleStringA resLen = CSimpleStringA::Format("%lld B", fileLen);
  2555. if (fileLen >= 1024 && fileLen < (1024 * 1024))
  2556. {
  2557. DOUBLE len = (DOUBLE)fileLen / 1024;
  2558. resLen = CSimpleStringA::Format("%.2f KB", len);
  2559. }
  2560. else if (fileLen >= (1024 * 1024) && fileLen < (1024 * 1024 * 1024))
  2561. {
  2562. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024);
  2563. resLen = CSimpleStringA::Format("%.2f MB", len);
  2564. }
  2565. else if (fileLen >= (1024 * 1024 * 1024))
  2566. {
  2567. DOUBLE len = (DOUBLE)fileLen / (1024 * 1024 * 1024);
  2568. resLen = CSimpleStringA::Format("%.2f GB", len);
  2569. }
  2570. CSimpleStringA oldLenStr("");
  2571. long oldLen = 0;
  2572. spConfigRun->ReadConfigValue("SpaceInfo",
  2573. p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(), oldLenStr);
  2574. oldLen = atol(oldLenStr.GetData());
  2575. fileIncreasedSpace[p.assign(path).append("\\rvc\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024)) - oldLen; //保存在unordered_map中
  2576. fileSpace[p.assign(path).append("\\rvc\\").append(fileinfo.name)] = (long)(fileLen / (1024 * 1024));
  2577. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("[%s] 大小为 [%s]",
  2578. p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(), resLen.GetData());
  2579. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  2580. {
  2581. spConfigRun->WriteConfigValue("SpaceInfo", p.assign(path).append("\\rvc\\").append(fileinfo.name).c_str(),
  2582. CSimpleStringA::Format("%ld MB", (long)(fileLen / (1024 * 1024))));
  2583. }
  2584. } while (_findnext(hFile, &fileinfo) == 0);
  2585. _findclose(hFile);
  2586. }
  2587. if (lastVer != m_RvcSysinfo.InstallVersion.GetVersion64())
  2588. {
  2589. //写入硬盘量
  2590. spConfigRun->WriteConfigValueInt("SpaceInfo", "DiskTotalUsed(GB)", GetDiskUsedByte() / (1024 * 1024 * 1024));
  2591. if (spaceLock)
  2592. {
  2593. spaceLock = false; //释放锁
  2594. }
  2595. return; //新版本无需上报文件信息,更新完运行时文件后即可结束
  2596. }
  2597. //获取增量最大的前十文件夹信息
  2598. sortFileIncreasedSpace = vector<pair<string, long>>(fileIncreasedSpace.begin(), fileIncreasedSpace.end());
  2599. sort(sortFileIncreasedSpace.begin(), sortFileIncreasedSpace.end(), CmpByValueFromBiggest());
  2600. int topFileNum = sortFileIncreasedSpace.size();
  2601. if (topFileNum > 10)
  2602. {
  2603. topFileNum = 10;
  2604. }
  2605. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("变化最大的%d个文件夹信息。", topFileNum);
  2606. fileLen = 0;
  2607. for (int i = 0; i < topFileNum; i++)
  2608. {
  2609. fileLen = sortFileIncreasedSpace[i].second;
  2610. if (fileLen == 0) break;
  2611. CSimpleStringA warn1 = CSimpleStringA::Format("TOP %d: [%s], 增量[%ld]MB",
  2612. i + 1, sortFileIncreasedSpace[i].first.c_str(), sortFileIncreasedSpace[i].second);
  2613. LogWarn(Severity_Low, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPINCREASED_SPACE, warn1.GetData());
  2614. }
  2615. if (m_bNeedForceDiskCheck)
  2616. {
  2617. //获取空间占用最大前十文件夹信息
  2618. sortFileSpace = vector<pair<string, long>>(fileSpace.begin(), fileSpace.end());
  2619. sort(sortFileSpace.begin(), sortFileSpace.end(), CmpByValueFromBiggest());
  2620. int topFileSize = sortFileSpace.size();
  2621. if (topFileSize > 10)
  2622. {
  2623. topFileSize = 10;
  2624. }
  2625. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("空间占用最大的%d个文件夹信息。", topFileSize);
  2626. fileLen = 0;
  2627. for (int i = 0; i < topFileSize; i++)
  2628. {
  2629. fileLen = sortFileSpace[i].second;
  2630. if (fileLen == 0) break;
  2631. CSimpleStringA warn2 = CSimpleStringA::Format("空间占用排名 %d: [%s], 大小[%ld]MB",
  2632. i + 1, sortFileSpace[i].first.c_str(), sortFileSpace[i].second);
  2633. LogWarn(Severity_Low, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPUSED_SPACE, warn2.GetData());
  2634. }
  2635. m_bNeedForceDiskCheck = false;
  2636. }
  2637. if (spaceLock)
  2638. {
  2639. spaceLock = false; //释放锁
  2640. }
  2641. }
  2642. void ResourceWatcherFSM::GetSystemDiskStatus()
  2643. {
  2644. if (m_diskHighPercent <= 0)
  2645. {
  2646. m_diskHighPercent = 90; //默认硬盘告警百分比90%
  2647. }
  2648. ULARGE_INTEGER ulAvailFree, ulTotalBytes, ulTotalFree;
  2649. BOOL ret = GetDiskFreeSpaceEx(NULL, &ulAvailFree, &ulTotalBytes, &ulTotalFree);
  2650. if (ret == 0)
  2651. {
  2652. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDiskStatus.GetDiskFreeSpaceEx failed(%d).", GetLastError());
  2653. return;
  2654. }
  2655. CSimpleStringA csBinPath;
  2656. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Bin", csBinPath); //获取当前终端运行磁盘位置
  2657. DWORD dwAvFree = ulAvailFree.QuadPart / MILLION;
  2658. DWORD dwTotal = ulTotalBytes.QuadPart / MILLION;
  2659. DWORD dwTotalFree = ulTotalFree.QuadPart / MILLION;
  2660. int ratio = dwTotalFree * 100 / dwTotal;
  2661. if ((100 - ratio) > m_diskHighPercent)
  2662. {
  2663. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("The disk has %d MB(%d%%) available.\n", dwTotalFree, ratio);
  2664. string test(csBinPath.GetData());
  2665. char diskMessage[1024];
  2666. sprintf(diskMessage, "{\"Disk\":\"%c:\",\"total\":\"%0.2f GByte\",\"free ratio\":\"%d%%\"}",
  2667. csBinPath.GetData()[0], (double)dwTotal / 1024, ratio);
  2668. //oilyang@20200526 根据wq建议,降低磁盘空间偏少的告警频率
  2669. //SYSTEMTIME localTime;
  2670. //GetLocalTime(&localTime);
  2671. //if (m_diskLastWarnHour != localTime.wHour) //需要告警时才强制全盘扫描
  2672. //{
  2673. // m_diskLastWarnHour = localTime.wHour;
  2674. // CSmartPointer<IConfigInfo> spConfigRun;
  2675. // ErrorCodeEnum eErr = GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spConfigRun);
  2676. // if (eErr == Error_Succeed) {
  2677. // spConfigRun->WriteConfigValueInt("WarnRecord", "disk", m_diskLastWarnHour);
  2678. // }
  2679. // //LogWarn(Severity_Low, Error_Resource, LOG_EVT_SELFCHECK_HARDDISK_TOO_HIGH, "Harddisk free space is few.");
  2680. // LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH, diskMessage);
  2681. // m_bNeedForceDiskCheck = true;
  2682. //}
  2683. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH, diskMessage);
  2684. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A05").setAPI("DiskUsedCheck")(diskMessage);
  2685. m_bNeedForceDiskCheck = true;
  2686. }
  2687. else
  2688. {
  2689. m_bNeedForceDiskCheck = false;
  2690. }
  2691. CheckDiskFileSpaceTask* task4 = new CheckDiskFileSpaceTask(this);
  2692. GetEntityBase()->GetFunction()->PostThreadPoolTask(task4);
  2693. }
  2694. ULONGLONG ResourceWatcherFSM::GetDiskUsedByte()
  2695. {
  2696. ULARGE_INTEGER ulAvailFree, ulTotalBytes, ulTotalFree;
  2697. BOOL ret = GetDiskFreeSpaceEx(NULL, &ulAvailFree, &ulTotalBytes, &ulTotalFree);
  2698. if (ret == 0)
  2699. {
  2700. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("GetSystemDiskStatus.GetDiskFreeSpaceEx failed(%d).", GetLastError());
  2701. return -1;
  2702. }
  2703. CSimpleStringA csBinPath;
  2704. ErrorCodeEnum Error = m_pEntity->GetFunction()->GetPath("Bin", csBinPath); //获取当前终端运行磁盘位置
  2705. return ulTotalBytes.QuadPart - ulTotalFree.QuadPart;
  2706. }
  2707. __int64 Filetime2Int64(const FILETIME& ftime)
  2708. {
  2709. LARGE_INTEGER li;
  2710. li.LowPart = ftime.dwLowDateTime;
  2711. li.HighPart = ftime.dwHighDateTime;
  2712. return li.QuadPart;
  2713. }
  2714. __int64 CompareFileTime2(const FILETIME& preTime, const FILETIME& nowTime)
  2715. {
  2716. return Filetime2Int64(nowTime) - Filetime2Int64(preTime);
  2717. }
  2718. unordered_map<int, long long> oldProcessTime;
  2719. unordered_map<int, long long> newProcessTime;
  2720. unordered_map<int, CSimpleStringA> processName;
  2721. unordered_map<int, double> processCpu;
  2722. string sysProcName = "[System Process]|System|Registry|smss.exe|csrss.exe|services.exe|wininit.exe";
  2723. bool cmp(const pair<int, double>& a, const pair<int, double>& b) {
  2724. return a.second > b.second;
  2725. }
  2726. void ResourceWatcherFSM::GetSystemCPUStatus()
  2727. {
  2728. oldProcessTime.clear();
  2729. newProcessTime.clear();
  2730. processName.clear();
  2731. processCpu.clear();
  2732. FILETIME preIdleTime;
  2733. FILETIME preKernelTime;
  2734. FILETIME preUserTime;
  2735. FILETIME preProcCreateTime;
  2736. FILETIME preProcExitTime;
  2737. FILETIME preProcKernelTime;
  2738. FILETIME preProcUserTime;
  2739. GetSystemTimes(&preIdleTime, &preKernelTime, &preUserTime);
  2740. PROCESSENTRY32 pe32Old;
  2741. pe32Old.dwSize = sizeof(pe32Old);
  2742. //获得系统进程快照的句柄
  2743. HANDLE hProcessSnapOld = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  2744. if (hProcessSnapOld == INVALID_HANDLE_VALUE)
  2745. {
  2746. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  2747. return;
  2748. }
  2749. //首先获得第一个进程
  2750. BOOL bProcessOld = Process32First(hProcessSnapOld, &pe32Old);
  2751. //循环获得所有进程
  2752. while (bProcessOld)
  2753. {
  2754. //进程名和进程ID
  2755. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32Old.th32ProcessID);
  2756. GetProcessTimes(hProcess, &preProcCreateTime, &preProcExitTime, &preProcKernelTime, &preProcUserTime);
  2757. oldProcessTime[pe32Old.th32ProcessID] = Filetime2Int64(preProcKernelTime) + Filetime2Int64(preProcUserTime);
  2758. bProcessOld = Process32Next(hProcessSnapOld, &pe32Old);
  2759. }
  2760. CloseHandle(hProcessSnapOld);
  2761. // 等待一段时间
  2762. Sleep(1000); // 1000毫秒
  2763. FILETIME idleTime;
  2764. FILETIME kernelTime;
  2765. FILETIME userTime;
  2766. FILETIME ProcCreateTime;
  2767. FILETIME ProcExitTime;
  2768. FILETIME procKernelTime;
  2769. FILETIME procUserTime;
  2770. GetSystemTimes(&idleTime, &kernelTime, &userTime);
  2771. PROCESSENTRY32 pe32New;
  2772. pe32New.dwSize = sizeof(pe32New);
  2773. //获得系统进程快照的句柄
  2774. HANDLE hProcessSnapNew = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  2775. if (hProcessSnapNew == INVALID_HANDLE_VALUE)
  2776. {
  2777. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("CreateToolhelp32Snapshot error.");
  2778. return;
  2779. }
  2780. //首先获得第一个进程
  2781. BOOL bProcessNew = Process32First(hProcessSnapNew, &pe32New);
  2782. //循环获得所有进程
  2783. while (bProcessNew)
  2784. {
  2785. //进程名和进程ID
  2786. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pe32New.th32ProcessID);
  2787. GetProcessTimes(hProcess, &ProcCreateTime, &ProcExitTime, &procKernelTime, &procUserTime);
  2788. newProcessTime[pe32New.th32ProcessID] = Filetime2Int64(procKernelTime) + Filetime2Int64(procUserTime);
  2789. processName[pe32New.th32ProcessID] = CSimpleStringA(pe32New.szExeFile);
  2790. bProcessNew = Process32Next(hProcessSnapNew, &pe32New);
  2791. }
  2792. CloseHandle(hProcessSnapNew);
  2793. auto idle = CompareFileTime2(preIdleTime, idleTime);
  2794. auto kernel = CompareFileTime2(preKernelTime, kernelTime);
  2795. auto user = CompareFileTime2(preUserTime, userTime);
  2796. if (kernel + user == 0)
  2797. return;
  2798. CSystemRunInfo runInfo = { 0 };
  2799. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  2800. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++) //实体进程的名称默认全为sphost,需转换为对应实体名
  2801. {
  2802. runInfo.strRunningEntityNames[i];
  2803. CEntityRunInfo entityInfo = { 0 };
  2804. GetEntityBase()->GetFunction()->GetEntityRunInfo(runInfo.strRunningEntityNames[i].GetData(), entityInfo);
  2805. processName[entityInfo.dwProcessID] = runInfo.strRunningEntityNames[i];
  2806. }
  2807. unordered_map<int, long long>::iterator it;
  2808. for (it = newProcessTime.begin(); it != newProcessTime.end(); ++it)
  2809. {
  2810. int tPid = it->first;
  2811. //进程的占用率 = 单位时间间隔里进程的CPU时间片占用 / 单位时间间隔里CPU的整体时间片
  2812. if (oldProcessTime.find(tPid) == oldProcessTime.end())
  2813. {
  2814. continue;
  2815. }
  2816. if (sysProcName.find(processName[tPid].GetData()) != std::string::npos)
  2817. {
  2818. continue;
  2819. }
  2820. // 转换为百分比
  2821. double tRatio = 100.0 * (newProcessTime[tPid] - oldProcessTime[tPid]) / (kernel + user);
  2822. if (tRatio > 0.0);
  2823. {
  2824. processCpu[tPid] = tRatio;
  2825. }
  2826. }
  2827. vector<pair<int, double>> vec(processCpu.begin(), processCpu.end());
  2828. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  2829. int len = min(10, vec.size());
  2830. CSimpleStringA procWarn = "";
  2831. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  2832. {
  2833. procWarn = procWarn + ",\"" + processName[vec[i].first] + "\":\"" + CSimpleStringA::Format("%.2f", vec[i].second) + "%\"";
  2834. }
  2835. double cpuRatio = 100.0 * (kernel + user - idle) / (kernel + user);
  2836. if (m_cpuHighPercent <= 0)
  2837. {
  2838. m_cpuHighPercent = 80; //默认告警百分比80%
  2839. }
  2840. if (cpuWarnThreshold <= 0)
  2841. {
  2842. cpuWarnThreshold = 10; //默认满10次告一次警
  2843. }
  2844. if (cpuRatio > (double)m_cpuHighPercent)
  2845. {
  2846. cpuWarnTime = cpuWarnTime % cpuWarnThreshold;
  2847. if (cpuWarnThreshold == 0) //每达到一次阈值告警一次
  2848. {
  2849. CSimpleStringA warn = CSimpleStringA::Format("{\"type\":\"cpu\", \"total_used\":\" %.2f", cpuRatio);
  2850. warn = warn + "%\"" + procWarn + "}";
  2851. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, warn.GetData());
  2852. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A03").setAPI("CpuUsedCheck")(warn.GetData());
  2853. if (cpuRatio > 98) //cpu极端异常情况
  2854. {
  2855. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_CPU_ERROR, warn.GetData());
  2856. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A02")(warn.GetData());
  2857. }
  2858. }
  2859. cpuWarnTime++;
  2860. }
  2861. }
  2862. unsigned long long convert_time_format(const FILETIME* ftime)
  2863. {
  2864. LARGE_INTEGER li;
  2865. li.LowPart = ftime->dwLowDateTime;
  2866. li.HighPart = ftime->dwHighDateTime;
  2867. return li.QuadPart;
  2868. }
  2869. /// 时间转换
  2870. static uint64_t file_time_2_utc(const FILETIME* ftime)
  2871. {
  2872. LARGE_INTEGER li;
  2873. li.LowPart = ftime->dwLowDateTime;
  2874. li.HighPart = ftime->dwHighDateTime;
  2875. return li.QuadPart;
  2876. }
  2877. /// 获得CPU的核数
  2878. static int get_processor_number()
  2879. {
  2880. SYSTEM_INFO info;
  2881. GetSystemInfo(&info);
  2882. return (int)info.dwNumberOfProcessors;
  2883. }
  2884. int ResourceWatcherFSM::GetCpuUsageRatio(int pid)
  2885. {
  2886. //cpu数量
  2887. static int processor_count_ = -1;
  2888. //上一次的时间
  2889. static int64_t last_time_ = 0;
  2890. static int64_t last_system_time_ = 0;
  2891. FILETIME now;
  2892. FILETIME creation_time;
  2893. FILETIME exit_time;
  2894. FILETIME kernel_time;
  2895. FILETIME user_time;
  2896. int64_t system_time;
  2897. int64_t time;
  2898. int64_t system_time_delta;
  2899. int64_t time_delta;
  2900. int cpu = -1;
  2901. if (processor_count_ == -1)
  2902. {
  2903. processor_count_ = get_processor_number();
  2904. }
  2905. GetSystemTimeAsFileTime(&now);
  2906. HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
  2907. if (!GetProcessTimes(hProcess, &creation_time, &exit_time, &kernel_time, &user_time))
  2908. {
  2909. return -1;
  2910. }
  2911. system_time = (file_time_2_utc(&kernel_time) + file_time_2_utc(&user_time))
  2912. / processor_count_;
  2913. time = file_time_2_utc(&now);
  2914. if ((last_system_time_ == 0) || (last_time_ == 0))
  2915. {
  2916. last_system_time_ = system_time;
  2917. last_time_ = time;
  2918. return -1;
  2919. }
  2920. system_time_delta = system_time - last_system_time_;
  2921. time_delta = time - last_time_;
  2922. if (time_delta == 0)
  2923. return -1;
  2924. cpu = (int)((system_time_delta * 100 + time_delta / 2) / time_delta);
  2925. last_system_time_ = system_time;
  2926. last_time_ = time;
  2927. return cpu;
  2928. }
  2929. double GetMemoryUsageGB(int pid)
  2930. {
  2931. #ifdef WIN32
  2932. DWORDLONG mem = 0, vmem = 0;
  2933. PROCESS_MEMORY_COUNTERS pmc;
  2934. // get process hanlde by pid
  2935. HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
  2936. if (GetProcessMemoryInfo(process, &pmc, sizeof(pmc)))
  2937. {
  2938. mem = pmc.WorkingSetSize;
  2939. vmem = pmc.PagefileUsage;
  2940. }
  2941. CloseHandle(process);
  2942. // use GetCurrentProcess() can get current process and no need to close handle
  2943. // convert mem from B to GB
  2944. double memGB = mem / (1024.0 * 1024.0 * 1024.0);
  2945. return memGB;
  2946. #else
  2947. char file_name[64] = { 0 };
  2948. FILE* fd;
  2949. char line_buff[512] = { 0 };
  2950. sprintf(file_name, "/proc/%d/status", pid);
  2951. fd = fopen(file_name, "r");
  2952. if (nullptr == fd)
  2953. return 0;
  2954. char name[64];
  2955. int vmrss = 0;
  2956. for (int i = 0; i < VMRSS_LINE - 1; i++)
  2957. fgets(line_buff, sizeof(line_buff), fd);
  2958. fgets(line_buff, sizeof(line_buff), fd);
  2959. sscanf(line_buff, "%s %d", name, &vmrss);
  2960. fclose(fd);
  2961. // cnvert VmRSS from KB to MB
  2962. return vmrss / 1024.0;
  2963. #endif
  2964. }
  2965. unordered_map<int, double> processMem;
  2966. void ResourceWatcherFSM::GetSystemMemoryStatus()
  2967. {
  2968. MEMORYSTATUSEX statex;
  2969. statex.dwLength = sizeof(statex);
  2970. GlobalMemoryStatusEx(&statex);
  2971. double totalMem = statex.ullTotalPhys / (1024.0 * 1024.0 * 1024.0); //GB
  2972. unordered_map<int, CSimpleStringA>::iterator it;
  2973. for (it = processName.begin(); it != processName.end(); ++it)
  2974. {
  2975. int tPid = it->first;
  2976. double tmp = GetMemoryUsageGB(it->first);
  2977. if (tmp > 0.0 && tmp < 100)
  2978. {
  2979. processMem[tPid] = 100 * (tmp / totalMem);
  2980. }
  2981. }
  2982. //return;
  2983. vector<pair<int, double>> vec(processMem.begin(), processMem.end());
  2984. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  2985. int len = min(10, vec.size());
  2986. CSimpleStringA procWarn = "";
  2987. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  2988. {
  2989. procWarn = procWarn + ",\"" + processName[vec[i].first] + "\":\"" + CSimpleStringA::Format("%.1f", vec[i].second) + "%\"";
  2990. }
  2991. if (m_memHighPercent <= 0)
  2992. {
  2993. m_memHighPercent = 80; //默认告警百分比80%
  2994. }
  2995. if (memWarnThreshold <= 0)
  2996. {
  2997. memWarnThreshold = 10; //默认告警阈值10次
  2998. }
  2999. if (statex.dwMemoryLoad > m_memHighPercent)
  3000. {
  3001. memWarnTime = memWarnTime % memWarnThreshold;
  3002. if (memWarnTime == 0) //每达到阈值告警一次
  3003. {
  3004. CSimpleStringA warn = CSimpleStringA::Format("{\"type\":\"mem\", \"total\":\"%.1f GByte\",\"total_used\":\" %d%%\"", totalMem, statex.dwMemoryLoad);
  3005. warn = warn + procWarn + "}";
  3006. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, warn.GetData());
  3007. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A04").setAPI("MemUsedCheck")(warn.GetData());
  3008. }
  3009. memWarnTime++;
  3010. }
  3011. }
  3012. int ResourceWatcherFSM::IsWifiConnected()
  3013. {
  3014. DWORD service_ver;
  3015. HANDLE handle = NULL;
  3016. int result = -1;
  3017. DWORD err = WlanOpenHandle(WLAN_API_VERSION, NULL, &service_ver, &handle);
  3018. if (err != 0) {
  3019. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("open wlan handle failed %d", err);
  3020. return result;
  3021. }
  3022. PWLAN_INTERFACE_INFO_LIST info_list = NULL;
  3023. PWLAN_INTERFACE_INFO interface_info = NULL;
  3024. err = WlanEnumInterfaces(handle, NULL, &info_list);
  3025. if (err != ERROR_SUCCESS) {
  3026. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("Enum wlan interface failed %d", err);
  3027. WlanCloseHandle(handle, NULL);
  3028. return -1;
  3029. }
  3030. const int count = info_list->dwNumberOfItems;
  3031. for (int i = 0; i < count; ++i) {
  3032. interface_info = &info_list->InterfaceInfo[i];
  3033. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("wireless interface name: %s", SP::Module::Util::W2S(interface_info->strInterfaceDescription).c_str());
  3034. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("state: %d", interface_info->isState);
  3035. if (interface_info->isState == wlan_interface_state_connected) {
  3036. result = 1;
  3037. }
  3038. DWORD radio_state_info_size = sizeof(WLAN_RADIO_STATE);
  3039. PWLAN_RADIO_STATE radio_state_info_ptr = NULL;
  3040. WLAN_OPCODE_VALUE_TYPE op_code = wlan_opcode_value_type_invalid;
  3041. err = WlanQueryInterface(handle, &interface_info->InterfaceGuid, wlan_intf_opcode_radio_state,
  3042. NULL, &radio_state_info_size, (PVOID*)&radio_state_info_ptr, &op_code);
  3043. if (err != ERROR_SUCCESS) {
  3044. DbgWithLink(LOG_LEVEL_ERROR, LOG_TYPE_SYSTEM)("WlanQueryInterface failed %d", err);
  3045. }
  3046. else
  3047. {
  3048. const uint32_t count_of_phys = radio_state_info_ptr->dwNumberOfPhys;
  3049. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Number of valid PHYs: %d", count_of_phys);
  3050. if (count_of_phys > 0 && result == -1) {
  3051. if (dot11_radio_state_on == radio_state_info_ptr->PhyRadioState[0].dot11SoftwareRadioState) {
  3052. result = 0;
  3053. }
  3054. else
  3055. {
  3056. /*
  3057. for (int j = 0; j < count_of_phys; ++j) {
  3058. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("software radio state: %d, %d", j , radio_state_info_ptr->PhyRadioState[j].dot11SoftwareRadioState);
  3059. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("hardware radio state: %d, %d", j, radio_state_info_ptr->PhyRadioState[j].dot11HardwareRadioState);
  3060. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("**********************");
  3061. }
  3062. */
  3063. }
  3064. }
  3065. }
  3066. }
  3067. if (info_list != NULL) {
  3068. WlanFreeMemory(info_list);
  3069. }
  3070. WlanCloseHandle(handle, NULL);
  3071. return result;
  3072. }
  3073. void ResourceWatcherFSM::DetectWallpaperAndWarn()
  3074. {
  3075. int vbsType = -1;
  3076. DWORD dwFlag = KEY_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS;
  3077. if (Is32R64Platform() != 0) {
  3078. dwFlag |= KEY_WOW64_64KEY;
  3079. }
  3080. bool explorerSet = false;
  3081. CSimpleStringA regeditValue(true);
  3082. HKEY hKey;
  3083. LONG lResult = RegOpenKeyEx(HKEY_CURRENT_USER,"Control Panel\\Desktop", 0, dwFlag, &hKey);
  3084. if (lResult == ERROR_SUCCESS) {
  3085. DWORD dwType = REG_SZ;
  3086. DWORD dwSize = MAX_PATH * sizeof(TCHAR);
  3087. TCHAR szValue[MAX_PATH + 1] = { 0 };
  3088. memset(szValue, '\0', MAX_PATH + 1);
  3089. lResult = RegQueryValueEx(hKey, "Wallpaper", NULL, &dwType, (LPBYTE)szValue, &dwSize);
  3090. if (lResult == ERROR_SUCCESS) {
  3091. CSimpleStringA strMsg = CSimpleStringA::Format("{\"subject\":\"wallpaper_path\",\"value\":\"%s\"}", szValue);
  3092. LogWarn(Severity_Low, Error_Debug, LOG_INFO_DESKTOP_WALLPAPER_PATH, strMsg);
  3093. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("WallpaperSettings")(strMsg.GetData());
  3094. }
  3095. else {
  3096. CSimpleStringA strMsg = CSimpleStringA::Format("{\"subject\":\"wallpaper_path\",\"error\":\"RegQueryValueEx for Wallpaper returned %u, GLE=%u\"}", lResult, GetLastError());
  3097. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_DESKTOP_WALLPAPER_PATH_FETCHFAILE, strMsg);
  3098. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("WallpaperSettings").setResultCode("RTA5A0E")(strMsg.GetData());
  3099. }
  3100. }
  3101. else {
  3102. CSimpleStringA strMsg = CSimpleStringA::Format("{\"subject\":\"wallpaper_path\",\"error\":\"RegOpenKeyEx for Desktop returned %u, GLE=%u\"}", lResult, GetLastError());
  3103. LogWarn(Severity_Low, Error_Unexpect, LOG_WARN_DESKTOP_WALLPAPER_PATH_FETCHFAILE, strMsg);
  3104. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("WallpaperSettings").setResultCode("RTA5A0E")(strMsg.GetData());
  3105. }
  3106. RegCloseKey(hKey);
  3107. }
  3108. #endif // _MSC_VER end硬件资源监控相关系统功能 CPU、内存、硬盘、网络wifi
  3109. #ifdef RVC_OS_LINUX
  3110. static bool spaceLock = false;
  3111. void ResourceWatcherFSM::CheckDiskFileSpace()
  3112. {
  3113. if (spaceLock)
  3114. {
  3115. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("当前已有硬盘扫描进行中,跳过。");
  3116. return;
  3117. }
  3118. else
  3119. {
  3120. spaceLock = true; //加锁
  3121. }
  3122. //获取opt文件夹下的文件占用信息
  3123. FILE* fp = NULL;
  3124. CSimpleStringA cmd = "du -h -s /opt/* | sort -rn | head";
  3125. if ((fp = popen(cmd.GetData(), "r")) == NULL) {
  3126. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("popen failed:%d", GetLastError());
  3127. return;
  3128. }
  3129. char buf[1024] = { 0 };
  3130. CSimpleStringA warnMsg(true);
  3131. while (fgets(buf, sizeof(buf), fp))
  3132. {
  3133. warnMsg = warnMsg + "|" + buf;
  3134. }
  3135. if (warnMsg.GetLength() > 0)
  3136. {
  3137. LogWarn(Severity_Low, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPUSED_SPACE, warnMsg.GetData()); //告警opt下的文件夹
  3138. }
  3139. pclose(fp);
  3140. //获取opt/rvc文件夹下的文件占用信息
  3141. FILE* fp2 = NULL;
  3142. CSimpleStringA cmd2 = "du -h -s /opt/rvc/* | sort -rn | head";
  3143. if ((fp2 = popen(cmd2.GetData(), "r")) == NULL) {
  3144. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("popen failed:%d", GetLastError());
  3145. return;
  3146. }
  3147. CSimpleStringA warnMsg2(true);
  3148. char buf2[1024] = { 0 };
  3149. while (fgets(buf2, sizeof(buf2), fp2))
  3150. {
  3151. warnMsg2 = warnMsg2 + "|" + buf2;
  3152. }
  3153. if (warnMsg2.GetLength() > 0)
  3154. {
  3155. LogWarn(Severity_Low, Error_Resource, LOG_RESOURCEWATCHER_FILE_TOPUSED_SPACE, warnMsg2.GetData()); //告警opt/rvc下的文件夹
  3156. }
  3157. pclose(fp2);
  3158. if (spaceLock)
  3159. {
  3160. spaceLock = false; //释放锁
  3161. }
  3162. }
  3163. #endif // RVC_OS_LINUX
  3164. ErrorCodeEnum ResourceWatcherFSM::CatchSystemBasicInfo(SystemBasicInfo& info)
  3165. {
  3166. #if defined(RVC_OS_WIN)
  3167. ///**TODO(Gifur@10/10/2023): 待实现 */
  3168. return Error_NotImpl;
  3169. #else
  3170. CSimpleStringA runCfgPath;
  3171. ErrorCodeEnum errCode = GetEntityBase()->GetFunction()->GetPath("RunCfg", runCfgPath);
  3172. if (runCfgPath.IsNullOrEmpty()) return Error_Null;
  3173. CSimpleStringA storeFilePath = runCfgPath + SPLIT_SLASH_STR + "SMBIOSData.txt";
  3174. if (!ExistsFileA(storeFilePath)) {
  3175. RemoveFileA(storeFilePath);
  3176. }
  3177. std::string succStr, errStr;
  3178. std::string runStr("dmidecode -t system > ");
  3179. runStr += storeFilePath.GetData();
  3180. if (!SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3181. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("execute '%s' failed!", runStr.c_str());
  3182. if (!ExistsFileA(storeFilePath)) {
  3183. RemoveFileA(storeFilePath);
  3184. }
  3185. return Error_Unexpect;
  3186. }
  3187. do {
  3188. std::string succStr, errStr;
  3189. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Manufacturer\"){print$2}' ");
  3190. runStr += storeFilePath.GetData();
  3191. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3192. info.strManufacturer = SP::Utility::ToTrim(succStr).c_str();
  3193. }
  3194. else
  3195. {
  3196. succStr = "";
  3197. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Manufacturer' failed!");
  3198. }
  3199. } while (false);
  3200. do {
  3201. std::string succStr, errStr;
  3202. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Product Name\"){print$2}' ");
  3203. runStr += storeFilePath.GetData();
  3204. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3205. info.strProductName = SP::Utility::ToTrim(succStr).c_str();
  3206. }
  3207. else
  3208. {
  3209. succStr = "";
  3210. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Product Name' failed!");
  3211. }
  3212. } while (false);
  3213. do {
  3214. std::string succStr, errStr;
  3215. std::string runStr("awk -F ':' '(NR>=7)&&(NR<=14)&&($0~\"Serial Number\"){print$2}' ");
  3216. runStr += storeFilePath.GetData();
  3217. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3218. info.strSerialNumber = SP::Utility::ToTrim(succStr).c_str();
  3219. }
  3220. else
  3221. {
  3222. succStr = "";
  3223. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("fetch 'Serial Number' failed!");
  3224. }
  3225. } while (false);
  3226. if (!ExistsFileA(storeFilePath)) {
  3227. RemoveFileA(storeFilePath);
  3228. }
  3229. return Error_Succeed;
  3230. #endif //RVC_OS_WIN
  3231. }
  3232. void ResourceWatcherFSM::AlarmSystemBasicInfo()
  3233. {
  3234. SystemBasicInfo info;
  3235. if (Error_Succeed == CatchSystemBasicInfo(info)) {
  3236. CSimpleStringA strResult("{");
  3237. if (!info.strManufacturer.IsNullOrEmpty()) {
  3238. strResult += CSimpleStringA::Format("\"Manufacturer\":\"%s\"", info.strManufacturer.GetData());
  3239. }
  3240. if (!info.strProductName.IsNullOrEmpty()) {
  3241. if (strResult.GetLength() > 1) {
  3242. strResult += ", ";
  3243. }
  3244. strResult += CSimpleStringA::Format("\"Product Name\":\"%s\"", info.strProductName.GetData());
  3245. }
  3246. if (!info.strSerialNumber.IsNullOrEmpty()) {
  3247. if (strResult.GetLength() > 1) {
  3248. strResult += ", ";
  3249. }
  3250. strResult += CSimpleStringA::Format("\"Serial Number\":\"%s\"", info.strSerialNumber.GetData());
  3251. }
  3252. strResult += "}";
  3253. LogWarn(Severity_Low, Error_Debug, LOG_INFO_DEVICE_SMBIOS_GET, strResult);
  3254. }
  3255. }
  3256. BOOL ResourceWatcherFSM::DetectIsFirstRunAtBoot()
  3257. {
  3258. const BOOL bSet = SP::Module::Comm::IsFirsRunAppAfterSystemBoot(GetEntityBase(), LOG_RESOURCEWATCHER_FIRST_RUN_AFTER_BOOT);
  3259. if (bSet) {
  3260. ErrorCodeEnum eRet = GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES);
  3261. if (eRet != Error_Succeed) {
  3262. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM)("Set %s with %s failed: %d", SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_YES, eRet);
  3263. }
  3264. }
  3265. else {
  3266. GetEntityBase()->GetFunction()->SetSysVar(SYSVAR_FRAMEWORK_FIRST_BOOT, SYSVAR_FRAMEWORK_FIRST_BOOT_NO);
  3267. }
  3268. return bSet;
  3269. }
  3270. #ifdef RVC_OS_LINUX
  3271. void ResourceWatcherFSM::UploadMonitorSettings()
  3272. {
  3273. CSmartPointer<IConfigInfo> spCtSettingConfig;
  3274. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  3275. int nSwitchOff(0);
  3276. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MonitorListenOFF", nSwitchOff);
  3277. if (!!nSwitchOff) {
  3278. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Cancel monitor change listen!");
  3279. if (m_bFirstRunAfterBoot) {
  3280. CSimpleStringA value(true);
  3281. bool res = GetMonitorInfo(value);
  3282. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  3283. }
  3284. }
  3285. else
  3286. {
  3287. int nInterval(10000);
  3288. int nValue(0);
  3289. spCtSettingConfig->ReadConfigValueInt(GetEntityBase()->GetEntityName(), "MonitorListenInterval", nValue);
  3290. if (nValue >= 10000) {
  3291. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Update monitor listen interval from %d to %d", nInterval, nValue);
  3292. nInterval = nValue;
  3293. }
  3294. CSimpleStringA strLastMonitor(true);
  3295. bool readFromCfgFalg(true);
  3296. CSmartPointer<IConfigInfo> spRunConfig;
  3297. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  3298. spRunConfig->ReadConfigValue("MonitorAttribute", "LastInfo", strLastMonitor);
  3299. do
  3300. {
  3301. CSimpleStringA value(true);
  3302. bool res = GetMonitorInfo(value);
  3303. if (!value.IsNullOrEmpty() && (strLastMonitor.IsNullOrEmpty() || (strLastMonitor.Compare(value) != 0))) {
  3304. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  3305. CSmartPointer<IConfigInfo> spRunConfig;
  3306. GetEntityBase()->GetFunction()->OpenConfig(Config_Run, spRunConfig);
  3307. spRunConfig->WriteConfigValue("MonitorAttribute", "LastInfo", value);
  3308. strLastMonitor = value;
  3309. if (readFromCfgFalg) {
  3310. readFromCfgFalg = false;
  3311. }
  3312. }
  3313. else if (readFromCfgFalg && !strLastMonitor.IsNullOrEmpty() && strLastMonitor.Compare(value) == 0)
  3314. {
  3315. LogWarn(Severity_Low, Error_Debug, LOG_INFO_MONITOR_SETTINGS, value);
  3316. readFromCfgFalg = false;
  3317. }
  3318. Sleep(nInterval);
  3319. } while (true);
  3320. }
  3321. }
  3322. void ResourceWatcherFSM::DetectSoftwareInstallStatus()
  3323. {
  3324. CSmartPointer<IConfigInfo> spCtSettingConfig;
  3325. GetEntityBase()->GetFunction()->OpenConfig(Config_CenterSetting, spCtSettingConfig);
  3326. CSimpleStringA strSoftwaresNames[MAX_SOFTWARE_INSTALLED_DETECT_COUNT];
  3327. CSimpleStringA strSoftwaresVers[MAX_SOFTWARE_INSTALLED_DETECT_COUNT];
  3328. int nNameCounts = 0;
  3329. for (int i = 0; i < MAX_SOFTWARE_INSTALLED_DETECT_COUNT; i++) {
  3330. strSoftwaresNames[i] = "";
  3331. strSoftwaresVers[i] = "";
  3332. CSimpleStringA item = CSimpleStringA::Format("SoftwareInstallDetect%d", i);
  3333. CSimpleStringA value(true);
  3334. spCtSettingConfig->ReadConfigValue(GetEntityBase()->GetEntityName(), item, value);
  3335. if (value.IsNullOrEmpty()) {
  3336. break;
  3337. }
  3338. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("CenterSettings:[%s]", value.GetData());
  3339. if (value.IndexOf("#") != -1) {
  3340. /** CSimpleString会带Trim操作,在这里不适用 [Gifur@202485]*/
  3341. auto items = SP::Utility::Split(std::string(value.GetData()), '#');
  3342. strSoftwaresNames[i] = items[0].c_str();
  3343. strSoftwaresVers[i] = items[1].c_str();
  3344. }
  3345. else
  3346. {
  3347. strSoftwaresNames[i] = value;
  3348. }
  3349. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("Detect SoftDetect from CentralSetting, %d: [%s],[%s],[%s]"
  3350. , i, item.GetData(), strSoftwaresNames[i].GetData(), strSoftwaresVers[i].GetData());
  3351. nNameCounts++;
  3352. }
  3353. if (nNameCounts > 0) {
  3354. for (int i = 0; i < nNameCounts; ++i) {
  3355. CSimpleStringA runItem = CSimpleStringA::Format("dpkg -l | grep \"%s\" | awk '{print $3}'", strSoftwaresNames[i].GetData());
  3356. std::string additional("");
  3357. std::string succStr, errStr;
  3358. std::string runStr(runItem.GetData());
  3359. if (SP::Module::Util::ShellExecute(runStr, succStr, errStr)) {
  3360. if (succStr.empty()) {
  3361. CSimpleStringA strMsg = CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"not installed\",\"detect_flag\":0}", strSoftwaresNames[i].GetData());
  3362. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_NOT_EXISTS_BASE + i, strMsg);
  3363. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SoftwareInstallStatus")(strMsg.GetData());
  3364. }
  3365. else
  3366. {
  3367. succStr = SP::Utility::ToTrim(succStr);
  3368. if (strSoftwaresVers[i].IsNullOrEmpty() || strSoftwaresVers[i].Compare(succStr.c_str()) == 0) {
  3369. CSimpleStringA strMsg = CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"%s\",\"detect_flag\":1}"
  3370. , strSoftwaresNames[i].GetData(), succStr.c_str(), strSoftwaresVers[i].GetData());
  3371. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_EXISTS_BASE + i, strMsg);
  3372. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SoftwareInstallStatus")(strMsg.GetData());
  3373. }
  3374. else
  3375. {
  3376. CSimpleStringA strMsg = CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"%s\", \"expected\":\"%s\",\"detect_flag\":0}"
  3377. , strSoftwaresNames[i].GetData(), succStr.c_str(), strSoftwaresVers[i].GetData());
  3378. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_NOT_EXISTS_BASE + i, strMsg);
  3379. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM).setAPI("SoftwareInstallStatus")(strMsg.GetData());
  3380. }
  3381. }
  3382. }
  3383. else
  3384. {
  3385. CSimpleStringA strMsg = CSimpleStringA::Format("{\"software_name\":\"%s\", \"version_status\":\"detect failed\", \"expected\":\"%s\",\"detect_flag\":0}"
  3386. , strSoftwaresNames[i].GetData(), strSoftwaresVers[i].GetData());
  3387. LogWarn(Severity_Low, Error_Debug, LOG_WARN_SOFTWARE_DETECT_EXISTS_STATUS_FAILED, strMsg);
  3388. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setAPI("SoftwareInstallStatus").setResultCode("RTA5A0D")(strMsg.GetData());
  3389. }
  3390. }
  3391. }
  3392. }
  3393. UINT ResourceWatcherFSM::GetSystemDisplayVersion(CSimpleStringA& strVersion)
  3394. {
  3395. UINT result = 0;
  3396. const char filePath[] = "/etc/os-version";
  3397. strVersion.Clear();
  3398. char tmp[33];
  3399. memset(tmp, 0, 33);
  3400. inifile_read_str_s("Version", "MajorVersion", "unknown", tmp, 32, filePath);
  3401. strVersion = tmp;
  3402. strVersion += ".";
  3403. memset(tmp, 0, 33);
  3404. inifile_read_str_s("Version", "MinorVersion", "unknown", tmp, 32, filePath);
  3405. strVersion += tmp;
  3406. strVersion += ".";
  3407. result = atoi(tmp);
  3408. memset(tmp, 0, 33);
  3409. inifile_read_str_s("Version", "OsBuild", "unknown", tmp, 32, filePath);
  3410. strVersion += tmp;
  3411. return result;
  3412. }
  3413. void ResourceWatcherFSM::UploadSysVersionInfo(UINT& ver)
  3414. {
  3415. std::map<std::string, std::string> srcData;
  3416. CSimpleStringA osver;
  3417. ver = GetSystemDisplayVersion(osver);
  3418. srcData.insert(std::make_pair("os-version", osver)); ////当前操作系统版本(系统信息)
  3419. tk_utsname_t t;
  3420. osutil_uname(&t);
  3421. srcData.insert(std::make_pair("sysname", t.sysname)); ////当前操作系统名
  3422. srcData.insert(std::make_pair("release", t.release)); ////当前发布级别
  3423. srcData.insert(std::make_pair("version", t.version)); ////当前发布版本
  3424. srcData.insert(std::make_pair("machine", t.machine)); ////当前硬件体系类型
  3425. do {
  3426. std::string sucContent, failedContent;
  3427. std::string cmd("cat /proc/cpuinfo |grep \"model name\" | awk 'NR==1'");
  3428. bool ret = SP::Module::Util::ShellExecute(cmd, sucContent, failedContent);
  3429. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("{%s}:{%s}{%s}", cmd.c_str(), sucContent.c_str(), failedContent.c_str());
  3430. auto elems = SP::Utility::Split(sucContent, ':');
  3431. if (elems.size() > 1) {
  3432. sucContent = SP::Utility::ToTrim(elems[1]);
  3433. }
  3434. srcData.insert(std::make_pair("cpu-type", sucContent));
  3435. } while (false);
  3436. auto ret = generateJsonStr(srcData);
  3437. LogWarn(Severity_Low, Error_Hardware, LOG_RESOURCEWATCHER_SYSTEMINFO, ret.second.c_str());
  3438. }
  3439. string ResourceWatcherFSM::MemoryProcessStatus()
  3440. {
  3441. CSmartPointer<IEntityFunction> spFunction = this->GetEntityBase()->GetFunction();
  3442. ErrorCodeEnum erroCode = Error_Unexpect;
  3443. int memTop = 10; //10个进程
  3444. map<string, string> nameProcess;
  3445. CSystemRunInfo runInfo = { 0 };
  3446. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  3447. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++)
  3448. {
  3449. string entityName = runInfo.strRunningEntityNames[i].GetData();
  3450. CEntityRunInfo entityInfo = { 0 };
  3451. GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
  3452. nameProcess[to_string(entityInfo.dwProcessID)] = entityName;
  3453. }
  3454. FILE* fp;
  3455. char buffer[2048];
  3456. string cmd = "ps c -eo pid,%mem,rss,command | sort -k3 -rn | head -" + to_string(memTop);
  3457. fp = popen(cmd.c_str(), "r");
  3458. int i = 0;
  3459. string s;
  3460. string str[4];
  3461. //mem
  3462. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("MEM TOP %d PROCESS!", memTop);
  3463. string topMessage = "";
  3464. while (i < memTop)
  3465. {
  3466. fgets(buffer, sizeof(buffer), fp);
  3467. s = buffer;
  3468. istringstream is(s);
  3469. is >> str[0] >> str[1] >> str[2] >> str[3];
  3470. double temp;
  3471. stringstream ss1;
  3472. ss1 << str[2];
  3473. ss1 >> temp;
  3474. temp = temp / (1024 * 1024);
  3475. stringstream ss2;
  3476. ss2 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << temp;
  3477. str[2] = ss2.str();
  3478. if (nameProcess.find(str[0]) != nameProcess.end())
  3479. {
  3480. str[3] = nameProcess[str[0]];
  3481. }
  3482. topMessage = topMessage + "\"" + str[3] + "\"" + ":" + "\"" + str[1] + "%\"";
  3483. if (i != memTop - 1)
  3484. {
  3485. topMessage += ",";
  3486. }
  3487. ++i;
  3488. }
  3489. topMessage += "}";
  3490. pclose(fp);
  3491. return topMessage;
  3492. }
  3493. long ResourceWatcherFSM::GetCPURunTime(CPUInfo* cpu) //获取CPU的当前信息,同时返回CPU使用时间
  3494. {
  3495. FILE* fd;
  3496. char buff[1024] = { 0 };
  3497. CPUInfo* cpuInfo = cpu;
  3498. fd = fopen("/proc/stat", "r");
  3499. if (!fd) {
  3500. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Read CPU Info FAILED!");
  3501. return -1;
  3502. }
  3503. fgets(buff, sizeof(buff), fd);
  3504. char name[64] = { 0 };
  3505. sscanf(buff, "%s %u %u %u %u %u %u %u",
  3506. cpuInfo->name, &cpuInfo->user, &cpuInfo->nice, &cpuInfo->system, &cpuInfo->idle, &cpuInfo->lowait, &cpuInfo->irq, &cpuInfo->softirq);
  3507. fclose(fd);
  3508. return (cpuInfo->user + cpuInfo->nice + cpuInfo->system + cpuInfo->idle + cpuInfo->lowait + cpuInfo->irq + cpuInfo->softirq);
  3509. }
  3510. long ResourceWatcherFSM::ReadProcCPURunTime(DWORD pid, ProcCPUInfo* pInfo) { //根据pid读取进程占用的CPU时间
  3511. char file_name[64] = { 0 };
  3512. FILE* fd;
  3513. char line_buff[1024] = { 0 };
  3514. sprintf(file_name, "/proc/%d/stat", pid);
  3515. fd = fopen(file_name, "r");
  3516. if (nullptr == fd) {
  3517. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Read PROCESS[%d] CPU Info FAILED!", pid);
  3518. return -1;
  3519. }
  3520. fgets(line_buff, sizeof(line_buff), fd);
  3521. sscanf(line_buff, "%u %s", &pInfo->pid, pInfo->pname);
  3522. const char* q = GetItems(line_buff, PROCESS_ITEM);
  3523. sscanf(q, "%ld %ld %ld %ld", &pInfo->utime, &pInfo->stime, &pInfo->cutime, &pInfo->cstime);
  3524. fclose(fd);
  3525. return (pInfo->utime + pInfo->stime + pInfo->cutime + pInfo->cstime);
  3526. }
  3527. //获取第N项开始的指针
  3528. const char* ResourceWatcherFSM::GetItems(const char* buffer, unsigned int item) {
  3529. const char* p = buffer;
  3530. int len = strlen(buffer);
  3531. int count = 0;
  3532. for (int i = 0; i < len; i++) {
  3533. if (' ' == *p) {
  3534. count++;
  3535. if (count == item - 1) {
  3536. p++;
  3537. break;
  3538. }
  3539. }
  3540. p++;
  3541. }
  3542. return p;
  3543. }
  3544. bool cmp(const pair<DWORD, DOUBLE>& a, const pair<DWORD, DOUBLE>& b) {
  3545. return a.second > b.second;
  3546. }
  3547. /* -----------------------
  3548. 根据先后两个时间的CPU信息,
  3549. 计算CPU的总占用量和各个进程的占用量
  3550. ----------------------- */
  3551. void ResourceWatcherFSM::GetSystemCPUStatus()
  3552. {
  3553. //int cpu_num = sysconf(_SC_NPROCESSORS_CONF); //CPU核数
  3554. CPUInfo* cpuOld = new CPUInfo;
  3555. CPUInfo* cpuNew = new CPUInfo;
  3556. const char* tPath = "/proc";
  3557. map<DWORD, string> nameProcess; // <pid, 进程名>
  3558. map<DWORD, DOUBLE> usageProcess; // <pid, CPU占用率>
  3559. long oldTotalTime = GetCPURunTime(cpuOld); //旧CPU运行总时间
  3560. if (oldTotalTime == -1)
  3561. {
  3562. return;
  3563. }
  3564. map<DWORD, long> oldProcCPUTime; // <pid, 旧时刻进程的CPU占用时间>
  3565. struct dirent* oldDirp;
  3566. DIR* oldDp = opendir(tPath);
  3567. if (oldDp != NULL) {
  3568. while ((oldDirp = readdir(oldDp)) != NULL) { //获取旧时刻 每一个进程的pid、CPU运行时间、进程名
  3569. string fileName = oldDirp->d_name;
  3570. BOOL isPid = TRUE;
  3571. for (int i = 0; i < fileName.length(); ++i) //判断进程id的文件夹 是否文件名是否纯数字
  3572. {
  3573. if (!isdigit(fileName[i]))
  3574. {
  3575. isPid = FALSE;
  3576. break;
  3577. }
  3578. }
  3579. if (!isPid) continue;
  3580. DWORD pid;
  3581. long oldTime;
  3582. ProcCPUInfo* oldProcCPU = new ProcCPUInfo;
  3583. sscanf(oldDirp->d_name, "%d", &pid); //读取文件夹名
  3584. oldTime = ReadProcCPURunTime(pid, oldProcCPU);
  3585. if (oldTime == -1)
  3586. {
  3587. return;
  3588. }
  3589. oldProcCPUTime[pid] = oldTime;
  3590. nameProcess[pid] = oldProcCPU->pname;
  3591. delete oldProcCPU;
  3592. }
  3593. closedir(oldDp);
  3594. }
  3595. sleep(1);
  3596. long newTotalTime = GetCPURunTime(cpuNew); //新CPU运行总时间
  3597. if (newTotalTime == -1)
  3598. {
  3599. return;
  3600. }
  3601. map<DWORD, long> newProcCPUTime; // <pid, 新时刻进程的CPU占用时间>
  3602. struct dirent* newDirp;
  3603. DIR* newDp = opendir(tPath);
  3604. if (newDp != NULL) {
  3605. while ((newDirp = readdir(newDp)) != NULL) { //获取新时刻 每一个进程的pid、CPU运行时间、进程名
  3606. string fileName = newDirp->d_name;
  3607. BOOL isPid = TRUE;
  3608. for (int i = 0; i < fileName.length(); ++i) //判断进程id的文件夹 是否文件名是否纯数字
  3609. {
  3610. if (!isdigit(fileName[i]))
  3611. {
  3612. isPid = FALSE;
  3613. break;
  3614. }
  3615. }
  3616. if (!isPid) continue;
  3617. DWORD pid;
  3618. long newTime;
  3619. ProcCPUInfo* newProcCPU = new ProcCPUInfo;
  3620. sscanf(newDirp->d_name, "%d", &pid); //读取文件夹名
  3621. newTime = ReadProcCPURunTime(pid, newProcCPU);
  3622. if (newTime == -1)
  3623. {
  3624. return;
  3625. }
  3626. newProcCPUTime[pid] = newTime;
  3627. string tName = newProcCPU->pname;
  3628. tName.erase(tName.begin());
  3629. tName.erase(tName.begin() + (tName.length() - 1));
  3630. nameProcess[pid] = tName;
  3631. delete newProcCPU;
  3632. }
  3633. closedir(newDp);
  3634. }
  3635. map<DWORD, long>::iterator it;
  3636. for (it = newProcCPUTime.begin(); it != newProcCPUTime.end(); ++it)
  3637. {
  3638. DWORD tPid = it->first;
  3639. //进程的占用率 = 单位时间间隔里进程的CPU时间片占用 / 单位时间间隔里CPU的整体时间片
  3640. DOUBLE tRatio = 100.0 * (newProcCPUTime[tPid] - oldProcCPUTime[tPid]) / (newTotalTime - oldTotalTime);
  3641. usageProcess[tPid] = tRatio;
  3642. }
  3643. CSystemRunInfo runInfo = { 0 };
  3644. GetEntityBase()->GetFunction()->GetSystemRunInfo(runInfo);
  3645. for (int i = 0; i < runInfo.strRunningEntityNames.GetCount(); i++) //实体进程的名称默认全为sphost,需转换为对应实体名
  3646. {
  3647. string entityName = runInfo.strRunningEntityNames[i].GetData();
  3648. CEntityRunInfo entityInfo = { 0 };
  3649. GetEntityBase()->GetFunction()->GetEntityRunInfo(entityName.c_str(), entityInfo);
  3650. nameProcess[entityInfo.dwProcessID] = entityName;
  3651. }
  3652. vector<pair<DWORD, DOUBLE>> vec(usageProcess.begin(), usageProcess.end());
  3653. sort(vec.begin(), vec.end(), cmp); //根据CPU使用率从大到小进行排序
  3654. int cpuTop = 10;
  3655. int len = MIN(cpuTop, vec.size()); //确认要展示的进程数量
  3656. string procWarn = "";
  3657. for (int i = 0; i < len; ++i) //构建进程的CPU使用告警信息
  3658. {
  3659. char* tUsage = new char[20];
  3660. sprintf(tUsage, "%.2lf", vec[i].second);
  3661. procWarn = procWarn + ",\"" + nameProcess[vec[i].first] + "\":\"" + string(tUsage) + "%\"";
  3662. delete tUsage;
  3663. }
  3664. unsigned long oldInfo, newInfo;
  3665. double cUsedRate = 0;
  3666. //第一次(用户+优先级+系统+空闲)的时间
  3667. //oldInfo = (unsigned long)(cpuOld->user + cpuOld->nice + cpuOld->system + cpuOld->idle + cpuOld->lowait + cpuOld->irq + cpuOld->softirq);
  3668. //第二次(用户+优先级+系统+空闲)的时间
  3669. //newInfo = (unsigned long)(cpuNew->user + cpuNew->nice + cpuNew->system + cpuNew->idle + cpuNew->lowait + cpuNew->irq + cpuNew->softirq);
  3670. double totalTime = newTotalTime - oldTotalTime;
  3671. double freeTime = cpuNew->idle - cpuOld->idle;
  3672. cUsedRate = (totalTime - freeTime) / totalTime;
  3673. if (m_cpuHighPercent <= 0)
  3674. {
  3675. m_cpuHighPercent = 80; //默认告警百分比80%
  3676. }
  3677. if (cpuWarnThreshold <= 0)
  3678. {
  3679. cpuWarnThreshold = 10; //默认满10次告一次警
  3680. }
  3681. if ((cUsedRate * 100) > m_cpuHighPercent)
  3682. {
  3683. cpuWarnTime = cpuWarnTime % cpuWarnThreshold;
  3684. if (cpuWarnTime == 0) //每达到一次阈值告警一次
  3685. {
  3686. stringstream tss;
  3687. tss << std::setiosflags(std::ios::fixed) << std::setprecision(2) << cUsedRate * 100;
  3688. string warn = "{ \"total_used\":\"" + tss.str() + "%\"" + procWarn + "}";
  3689. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_CPU_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
  3690. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A03").setAPI("CpuUsedCheck")(warn.c_str());
  3691. }
  3692. cpuWarnTime++;
  3693. }
  3694. delete cpuNew;
  3695. delete cpuOld;
  3696. }
  3697. void ResourceWatcherFSM::GetSystemMemoryStatus()
  3698. {
  3699. MemInfo* memInfo = new MemInfo();
  3700. FILE* fd;
  3701. char buff[256];
  3702. fd = fopen("/proc/meminfo", "r");
  3703. if (!fd) {
  3704. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("Read Memory INFO FAILED!");
  3705. return;
  3706. }
  3707. fgets(buff, sizeof(buff), fd);
  3708. sscanf(buff, "%s %lu ", memInfo->infoName1, &memInfo->memTotal);
  3709. fgets(buff, sizeof(buff), fd);
  3710. sscanf(buff, "%s %lu ", memInfo->infoName2, &memInfo->memFree);
  3711. fgets(buff, sizeof(buff), fd);
  3712. sscanf(buff, "%s %lu ", memInfo->infoName3, &memInfo->memAvail);
  3713. fclose(fd);
  3714. double mUsedRate = 0;
  3715. mUsedRate = (double)(memInfo->memTotal - memInfo->memAvail) / (double)memInfo->memTotal;
  3716. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  3717. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  3718. char szResult3[DEFAULT_OUTPUT_FORMAT_SIZE];
  3719. ByteSprintf(szResult, (double)(memInfo->memTotal) * 1024, 'G'); // 内存信息在 /proc/meminfo 中的单位为 KB
  3720. ByteSprintf(szResult2, (double)(memInfo->memFree) * 1024, 'G');
  3721. ByteSprintf(szResult3, (double)(memInfo->memAvail) * 1024, 'G');
  3722. if (m_memHighPercent <= 0)
  3723. {
  3724. m_memHighPercent = 80; //默认告警百分比80%
  3725. }
  3726. if (memWarnThreshold <= 0)
  3727. {
  3728. memWarnThreshold = 10; //默认告警阈值10次
  3729. }
  3730. if ((mUsedRate * 100) > m_memHighPercent)
  3731. {
  3732. memWarnTime = memWarnTime % memWarnThreshold;
  3733. if (memWarnTime == 0) //每达到阈值告警一次
  3734. {
  3735. char usedResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  3736. ByteSprintf(usedResult, (double)(memInfo->memTotal) * 1024 * mUsedRate, 'G');
  3737. stringstream ss1;
  3738. ss1 << std::setiosflags(std::ios::fixed) << std::setprecision(2) << mUsedRate * 100;
  3739. string warn = "{ \"total\":\"" + string(szResult) + "\"," +
  3740. "\"used\":\"" + ss1.str() + "%\"," + MemoryProcessStatus();
  3741. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_MEMORY_TOO_HIGH, CSimpleStringA::Format("%s", warn.c_str()));
  3742. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A04").setAPI("MemUsedCheck")(warn.c_str());
  3743. }
  3744. memWarnTime++;
  3745. }
  3746. }
  3747. void ResourceWatcherFSM::GetDiskStatusFrom(LPCTSTR path)
  3748. {
  3749. if (m_diskHighPercent <= 0)
  3750. {
  3751. m_diskHighPercent = 90; //默认硬盘告警百分比90%
  3752. }
  3753. unsigned long long uiTotalBytes;
  3754. unsigned long long uiFreeDiskBytes;
  3755. char szResult[DEFAULT_OUTPUT_FORMAT_SIZE];
  3756. char szResult2[DEFAULT_OUTPUT_FORMAT_SIZE];
  3757. BOOL readFlag = DiskInfo::GetDiskSpace(path, uiTotalBytes, uiFreeDiskBytes);
  3758. double dUsedRate = 1 - (uiFreeDiskBytes * kConversion[3]) / (uiTotalBytes * kConversion[3]);
  3759. ByteSprintf(szResult, (double)uiTotalBytes);
  3760. ByteSprintf(szResult2, (double)uiFreeDiskBytes);
  3761. if (readFlag && (dUsedRate * 100 < m_diskHighPercent)) {
  3762. //DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("[Disk# %s] total: %s, free: %s, [Disk] used rate: %.1lf%%.", path, szResult, szResult2, dUsedRate * 100);
  3763. }
  3764. else
  3765. {
  3766. CSimpleStringA warnStr = CSimpleStringA::Format("\"Disk\":\"%s\",\"total\":\"%s\",\"free\":\"%s\",\"used rate\":\"%.1lf%%\"",
  3767. path, szResult, szResult2, dUsedRate * 100);
  3768. LogWarn(Severity_Middle, Error_Resource, LOG_EVT_RESOURCE_HARDDISK_TOO_HIGH, warnStr.GetData());
  3769. DbgWithLink(LOG_LEVEL_WARN, LOG_TYPE_SYSTEM).setResultCode("RTA5A05").setAPI("DiskUsedCheck")(warnStr.GetData());
  3770. CheckDiskFileSpaceTask* task4 = new CheckDiskFileSpaceTask(this);
  3771. GetEntityBase()->GetFunction()->PostThreadPoolTask(task4);
  3772. }
  3773. }
  3774. void ResourceWatcherFSM::GetSystemDiskStatus()
  3775. {
  3776. GetDiskStatusFrom("/");
  3777. }
  3778. void ResourceWatcherFSM::switchWindowsEffect(const char* cfgFilePath, bool enable)
  3779. {
  3780. char tmp[33];
  3781. memset(tmp, 0, 33);
  3782. inifile_read_str_s("Compositing", "Enabled", "", tmp, 32, cfgFilePath);
  3783. if (strlen(tmp) == 0 || stricmp(tmp, "false") == 0) {
  3784. if (enable) {
  3785. inifile_write_str(cfgFilePath, "Compositing", "Enabled", "true");
  3786. LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_ON, "to active window effect");
  3787. }
  3788. }
  3789. else if (stricmp(tmp, "true") == 0) {
  3790. if (!enable) {
  3791. inifile_write_str(cfgFilePath, "Compositing", "Enabled", "false");
  3792. LogWarn(Severity_Low, Error_InvalidState, LOG_RESOURCEWATCHER_COMPOSITING_CHANGE_OFF, "to inactive window effect");
  3793. }
  3794. }
  3795. }
  3796. void ResourceWatcherFSM::RecoverDDEClipboardEnable()
  3797. {
  3798. const std::string clipboardPath = "/usr/bin/dde-clipboard";
  3799. const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
  3800. if (!ExistsFileA(clipboardPath.c_str()) && ExistsFileA(clipboardPathBak.c_str())) {
  3801. fileutil_copy_file(clipboardPath.c_str(), clipboardPathBak.c_str());
  3802. //fileutil_delete_file(clipboardPathBak.c_str());
  3803. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_CLIPBOARD_RECOVER_ENABLE, "recover clipboard succ.");
  3804. }
  3805. else {
  3806. DbgWithLink(LOG_LEVEL_INFO, LOG_TYPE_SYSTEM)("%s exists.", clipboardPath.c_str());
  3807. }
  3808. }
  3809. void ResourceWatcherFSM::ConfirmDDEClipboardDisable()
  3810. {
  3811. const std::string clipboardPath = "/usr/bin/dde-clipboard";
  3812. const std::string clipboardPathBak = "/usr/bin/dde-clipboard.bak";
  3813. char* clipboards[] = { "dde-clipboard", "dde-clipboardloader" };
  3814. if (!ExistsFileA(clipboardPath.c_str())) {
  3815. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("There are no any %s files.", clipboardPath.c_str());
  3816. if (ExistsFileA(clipboardPathBak.c_str())) {
  3817. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("%s exists.", clipboardPathBak.c_str());
  3818. }
  3819. return;
  3820. }
  3821. if (0 != fileutil_copy_file(clipboardPathBak.c_str(), clipboardPath.c_str())) {
  3822. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove clipboard failed");
  3823. }
  3824. else {
  3825. fileutil_delete_file(clipboardPath.c_str());
  3826. osutil_terminate_related_process(clipboards, array_size(clipboards), 0);
  3827. LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_SUCC, "remove clipboard succ.");
  3828. }
  3829. }
  3830. void ResourceWatcherFSM::ConfirmNotificationCenterDisable()
  3831. {
  3832. const char* osd_file_path = "/usr/lib/deepin-daemon/dde-osd";
  3833. const char* osd_bak_file_path = "/usr/lib/deepin-daemon/dde-osd.bak";
  3834. CSmartPointer<IConfigInfo> spConfig;
  3835. GetEntityBase()->GetFunction()->OpenConfig(Config_Cache, spConfig);
  3836. int flag = 0;
  3837. spConfig->ReadConfigValueInt("UOSFeatures", "NotifyCenterSupport", flag);
  3838. if (flag == 1) {
  3839. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("allow the dde-osd process alive.");
  3840. if (!ExistsFileA(osd_file_path) && ExistsFileA(osd_bak_file_path)) {
  3841. fileutil_copy_file(osd_file_path, osd_bak_file_path);
  3842. LogWarn(Severity_Low, Error_Debug, LOG_RESOURCEWATCHER_OSD_RECOVER_ENABLE, "recover dde osd succ.");
  3843. }
  3844. }
  3845. else {
  3846. if (ExistsFileA(osd_file_path) && !ExistsFileA(osd_bak_file_path)) {
  3847. char* relates[] = { "dde-osd" };
  3848. if (0 != fileutil_copy_file(osd_bak_file_path, osd_file_path)) {
  3849. LogWarn(Severity_Low, Error_Unexpect, LOG_RESOURCEWATCHER_CLIPBOARD_REMOVE_FAILED, "remove dde osd failed");
  3850. }
  3851. else {
  3852. osutil_terminate_related_process(relates, array_size(relates), 0);
  3853. fileutil_delete_file(osd_file_path);
  3854. LogWarn(Severity_Low, Error_Process, LOG_RESOURCEWATCHER_OSD_REMOVE_SUCC, "remove dde osd succ.");
  3855. }
  3856. }
  3857. }
  3858. }
  3859. void ResourceWatcherFSM::ConfirmWindowEffectHasBeenOpen()
  3860. {
  3861. array_header_t* arr;
  3862. arr = fileutil_get_sub_dirs_a("/home");
  3863. if (arr) {
  3864. int i;
  3865. for (i = 0; i < arr->nelts; ++i) {
  3866. char szDestSubDir[256] = { 0 };
  3867. char* dir = ARRAY_IDX(arr, i, char*);
  3868. DbgWithLink(LOG_LEVEL_DEBUG, LOG_TYPE_SYSTEM)("sub dir: %s", dir);
  3869. strcpy(szDestSubDir, dir);
  3870. strcat(szDestSubDir, SPLIT_SLASH_STR);
  3871. strcat(szDestSubDir, ".config/kwinrc");
  3872. if (ExistsFileA(szDestSubDir)) {
  3873. switchWindowsEffect(szDestSubDir, true);
  3874. }
  3875. }
  3876. toolkit_array_free2(arr);
  3877. }
  3878. }
  3879. #endif // RVC_OS_LINUX