FileHelper.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. #include "FileHelper.h"
  2. #include "ComDef.h"
  3. // common
  4. #include "File.h"
  5. #include "Locks.h"
  6. // depends
  7. #include "GetNetState.h"
  8. // STD
  9. #include <sstream>
  10. #include <dirent.h>
  11. NAMESPACE_MAS_BEGIN
  12. FileHelper * FileHelper::_ins = nullptr;
  13. tzc::Mutex FileHelper::_insLock;
  14. FileHelper * FileHelper::GetInstance()
  15. {
  16. if (!_ins)
  17. {
  18. _insLock.Lock();
  19. if (!_ins)
  20. {
  21. _ins = new FileHelper();
  22. }
  23. _insLock.Unlock();
  24. }
  25. return _ins;
  26. }
  27. void FileHelper::DestoryInstance()
  28. {
  29. tzc::ScopedLock lock(_insLock);
  30. TZ_delete(_ins);
  31. }
  32. void FileHelper::GetSysStatData(SysStatInfo & data)
  33. {
  34. FILE * file = fopen("/proc/stat", "r");
  35. if (nullptr == file)
  36. {
  37. TZLogError("file[/proc/stat] open failed!!!");
  38. return;
  39. }
  40. TZ_CHAR buff[1024];
  41. if (nullptr == fgets(buff, 1024, file))
  42. {
  43. fclose(file);
  44. TZLogError("file[/proc/stat] read failed!!!");
  45. return;
  46. }
  47. fclose(file);
  48. TZLogDebug(1, "[%s] read from [/proc/stat]~~~", buff);
  49. std::stringstream stream(buff);
  50. char tmp[16];
  51. stream >> tmp; // cpuXX
  52. stream >> data.user;
  53. stream >> data.system;
  54. stream >> data.idle;
  55. stream >> data.iowait;
  56. stream >> data.irq;
  57. stream >> data.softirq;
  58. }
  59. void FileHelper::GetSysMemData(SysMemInfo & data)
  60. {
  61. FILE * file = fopen("/proc/meminfo", "r");
  62. if (nullptr == file)
  63. {
  64. TZLogError("file[/proc/meminfo] open failed!!!");
  65. return;
  66. }
  67. std::string name;
  68. TZ_ULONG num;
  69. TZ_CHAR buff[1024];
  70. while (fgets(buff, 1024, file))
  71. {
  72. TZLogDebug(1, "[%s] read from [/proc/meminfo]~~~", buff);
  73. std::stringstream stream(buff);
  74. stream >> name;
  75. stream >> num;
  76. if ("MemTotal:" == name)
  77. {
  78. data.MemTotal = num;
  79. }
  80. else if ("MemAvailable:" == name)
  81. {
  82. data.MemAvailable = num;
  83. }
  84. }
  85. fclose(file);
  86. }
  87. void FileHelper::GetSysDiskIOData(std::list<SysDiskStatInfo> & datas)
  88. {
  89. FILE * file = fopen("/proc/diskstats", "r");
  90. if (nullptr == file)
  91. {
  92. TZLogError("file[/proc/diskstats] open failed!!!");
  93. return;
  94. }
  95. TZ_CHAR buff[1024];
  96. while (fgets(buff, 1024, file))
  97. {
  98. SysDiskStatInfo data;
  99. std::stringstream stream(buff);
  100. stream >> data.MainDevIndex;
  101. stream >> data.SubDevIndex;
  102. stream >> data.DevName;
  103. /* FIXME: 多磁盘下,筛选要获取的磁盘信息 */
  104. if (data.DevName != "sda" && data.DevName != "sdb"
  105. && data.DevName != "sdc" && data.DevName != "sdd"
  106. /* && info.DevName != "XXX" */
  107. )
  108. continue;
  109. stream >> data.ReadFinishCount;
  110. stream >> data.MergeReadFinishedCount;
  111. stream >> data.ReadSectionCount;
  112. stream >> data.ReadMilinSeconds;
  113. stream >> data.WriteFinishedCount;
  114. stream >> data.MergeWriteFinishedCount;
  115. stream >> data.WriteSectionCount;
  116. stream >> data.WriteMilinSeconds;
  117. stream >> data.ProcingIO;
  118. stream >> data.IOMilinSeconds;
  119. stream >> data.IOMilinSecondsAvg;
  120. struct timeval tv;
  121. gettimeofday(&tv, nullptr);
  122. data.collectTime = tv.tv_sec;
  123. datas.push_back(data);
  124. }
  125. fclose(file);
  126. }
  127. void FileHelper::GetSysNetBandData(std::list<SysNetBandInfo> & datas)
  128. {
  129. FILE * file = fopen("/proc/net/dev", "r");
  130. if (nullptr == file)
  131. {
  132. TZLogError("file[/proc/net/dev] open failed!!!");
  133. return;
  134. }
  135. TZ_CHAR buff[1024];
  136. fgets(buff, 1024, file);
  137. fgets(buff, 1024, file);
  138. while (fgets(buff, 1024, file))
  139. {
  140. SysNetBandInfo data;
  141. std::stringstream stream(buff);
  142. stream >> data.NicName;
  143. data.NicName[data.NicName.size() - 1] = '\0';
  144. stream >> data.Receive.bytes;
  145. stream >> data.Receive.packets;
  146. stream >> data.Receive.errs;
  147. stream >> data.Receive.drop;
  148. stream >> data.Receive.fifo;
  149. stream >> data.Receive.frame;
  150. stream >> data.Receive.compressed;
  151. stream >> data.Receive.multicast;
  152. stream >> data.Transmit.bytes;
  153. stream >> data.Transmit.packets;
  154. stream >> data.Transmit.errs;
  155. stream >> data.Transmit.drop;
  156. stream >> data.Transmit.colls;
  157. stream >> data.Transmit.carrier;
  158. stream >> data.Transmit.compressed;
  159. TZ_INT sock = if_socket();
  160. if (MEC_FAILED == sock)
  161. {
  162. close(sock);
  163. continue;
  164. }
  165. TZ_UINT bandWidth = 0;
  166. get_ifethspeed(sock, data.NicName.c_str(), &bandWidth);
  167. data.BandWidth = bandWidth;
  168. close(sock);
  169. struct timeval tv;
  170. gettimeofday(&tv, nullptr);
  171. data.collectTime = tv.tv_sec;
  172. datas.push_back(data);
  173. }
  174. fclose(file);
  175. }
  176. void FileHelper::GetSystemInfo(SystemInfo & info)
  177. {
  178. getSingalCmdResult("uname -a", info.Origin);
  179. getSingalCmdResult("uname -s", info.KernelName);
  180. getSingalCmdResult("uname -r", info.KernelRelease);
  181. getSingalCmdResult("uname -v", info.KernelVesion);
  182. getSingalCmdResult("uname -o", info.OperatingSystem);
  183. getSingalCmdResult("uname -m", info.Machine);
  184. getSingalCmdResult("uname -n", info.NodeName);
  185. TZLogDebug(10, "Origins),KernelName(%s),KernelRelease(%s),KernelVesion(%s),"
  186. "OperatingSystem(%s),Machine(%s),NodeName(%s)",
  187. info.KernelName.c_str(), info.KernelRelease.c_str(), info.KernelVesion.c_str(),
  188. info.OperatingSystem.c_str(), info.Machine.c_str(), info.NodeName.c_str());
  189. }
  190. void FileHelper::GetCPUInfo(CPUInfo & info)
  191. {
  192. /* FIXME:仅能获取配有多个同型号CPU的信息 */
  193. std::string cmdName = "cat /proc/cpuinfo |grep 'model name'";
  194. FILE * file = popen(cmdName.c_str(), "r");
  195. if (nullptr == file)
  196. {
  197. TZLogError("cmd[%s] exec failed!!!", cmdName.c_str());
  198. return;
  199. }
  200. TZ_CHAR buff[1024];
  201. if (nullptr == fgets(buff, 1024, file))
  202. {
  203. pclose(file);
  204. TZLogError("cmd[%s] read failed!!!", cmdName.c_str());
  205. return;
  206. }
  207. pclose(file);
  208. std::string res(buff);
  209. size_t cur = res.find(":");
  210. if (std::string::npos != cur)
  211. {
  212. info.CPUName.assign(res.c_str() + cur + 2);
  213. info.CPUName[info.CPUName.size() - 1] = '\0';
  214. }
  215. res.clear();
  216. getSingalCmdResult("cat /proc/cpuinfo | grep \"physical id\" | sort | uniq |wc -l", res);
  217. info.CPUPhysicalNum = std::atoi(res.c_str());
  218. res.clear();
  219. getSingalCmdResult("cat /proc/cpuinfo| grep \"processor\"| wc -l", res);
  220. info.CPULogicNum = std::atoi(res.c_str());
  221. /* !! KylinOS 不支持此命令 */
  222. res.clear();
  223. getSingalCmdResult("cat /proc/cpuinfo| grep \"cpu cores\" | uniq", res);
  224. std::stringstream ss(res.c_str());
  225. ss >> res;
  226. ss >> res;
  227. ss >> res;
  228. ss >> info.CPUCoreNum;
  229. TZLogDebug(10, "[%s](%d)(%d)(%d)", info.CPUName.c_str(), info.CPUPhysicalNum,
  230. info.CPUCoreNum, info.CPULogicNum);
  231. }
  232. void FileHelper::GetNetPortInfo(std::list<NetstatInfo> & infos)
  233. {
  234. FILE * file = popen("netstat -anupt", "r");
  235. if (nullptr == file)
  236. {
  237. TZLogError("cmd[netstat -anupt] exec failed!!!");
  238. return;
  239. }
  240. TZ_CHAR buff[4096];
  241. /* 前2行是无效信息(有可能是4行) */
  242. TZ_BOOL isAviled = FALSE;
  243. while (fgets(buff, 4096, file))
  244. {
  245. if (std::string(buff).find("Proto") != std::string::npos)
  246. {
  247. isAviled = TRUE;
  248. break;
  249. }
  250. }
  251. if (isAviled == FALSE)
  252. {
  253. pclose(file);
  254. return;
  255. }
  256. infos.clear();
  257. while (fgets(buff, 4096, file))
  258. {
  259. NetstatInfo info;
  260. std::stringstream stream(buff);
  261. stream >> info.Proto;
  262. stream >> info.RecvQ;
  263. stream >> info.SendQ;
  264. stream >> info.LocalAddress;
  265. stream >> info.ForeignAddress;
  266. stream >> info.State;
  267. stream >> info.Pid_Pname;
  268. infos.push_back(info);
  269. }
  270. pclose(file);
  271. }
  272. void FileHelper::GetDiskInfo(std::list<DiskstatInfo> & infos)
  273. {
  274. FILE * file = popen("df", "r");
  275. if (nullptr == file)
  276. {
  277. TZLogError("cmd[df] exec failed!!!");
  278. return;
  279. }
  280. infos.clear();
  281. TZ_CHAR buff[4096];
  282. fgets(buff, 4096, file);
  283. while (fgets(buff, 4096, file))
  284. {
  285. DiskstatInfo info;
  286. std::stringstream stream(buff);
  287. stream >> info.Filesystem;
  288. stream >> info.Blocks_1K;
  289. stream >> info.Used;
  290. stream >> info.Available;
  291. stream >> info.UseRate;
  292. stream >> info.MountedOn;
  293. infos.push_back(info);
  294. }
  295. pclose(file);
  296. }
  297. void FileHelper::GetGPUInfo(std::string & info)
  298. {
  299. /*
  300. * FIXME: nvidia-smi命令不是必装项,
  301. * 此函数可以完善
  302. */
  303. std::string res;
  304. getSingalCmdResult("lspci | grep -i vga", res);
  305. size_t pos = res.find("controller: ");
  306. if (std::string::npos == pos) return;
  307. info = res.substr(pos + 12, res.length() - pos - 13);
  308. }
  309. TZ_INT FileHelper::GetInterFaceInfo(std::list<InterfaceInfo> & infos)
  310. {
  311. TZ_INT sock = if_socket();
  312. if (MEC_FAILED == sock)
  313. {
  314. close(sock);
  315. return MEC_FAILED;
  316. }
  317. TZ_CHAR addr[64]{ '\0' };
  318. TZ_INT addrlen(64);
  319. TZLogDebug(10, "info size %d", infos.size());
  320. for (auto & iter : infos)
  321. {
  322. if (MEC_FAILED == get_ifhwaddr(sock, iter.Name.c_str(), addr, addrlen))
  323. {
  324. TZLogError("get_ifhwaddr error[%s]!!!", iter.Name.c_str());
  325. }
  326. iter.HwAddr.assign(addr);
  327. memset(addr, '\0', 64);
  328. if (MEC_FAILED == get_ifaddr(sock, iter.Name.c_str(), addr, addrlen))
  329. {
  330. TZLogError("get_ifaddr error[%s]!!!", iter.Name.c_str());
  331. }
  332. iter.InetAddr.assign(addr);
  333. memset(addr, '\0', 64);
  334. if (-1 == get_ifnetMask(sock, iter.Name.c_str(), addr, addrlen))
  335. {
  336. TZLogError("get_ifnetMask error[%s]!!!", iter.Name.c_str());
  337. }
  338. iter.Netmask.assign(addr);
  339. memset(addr, '\0', 64);
  340. if (-1 == get_ifstat(sock, iter.Name.c_str(), &(iter.Status)))
  341. {
  342. TZLogError("get_ifstat error[%s]!!!", iter.Name.c_str());
  343. }
  344. if (35 == iter.Status) iter.Status = 1;
  345. else iter.Status = 0;
  346. }
  347. close(sock);
  348. std::string filename = "/proc/net/if_inet6";
  349. std::string buf, ipv6addr;
  350. /* 该类型打开文件操作可以直接忽略空格进行赋值 */
  351. std::fstream file;
  352. file.open(filename, std::ios::in);
  353. while (!(EOF == file.peek()))
  354. {
  355. for (TZ_INT i = 0; i < 6 && !(EOF == file.peek()); i++)
  356. {
  357. file >> buf;
  358. if (i == 0) ipv6addr = buf;
  359. if (i == 5)
  360. {
  361. for (auto& iter : infos)
  362. {
  363. if (buf == iter.Name)
  364. {
  365. iter.Inet6Addr += ipv6addr.substr(0, 4);
  366. iter.Inet6Addr += "::";
  367. for (TZ_INT i = 0; i < 3; i++)
  368. {
  369. iter.Inet6Addr += ipv6addr.substr(16 + i * 4, 4);
  370. iter.Inet6Addr += ":";
  371. }
  372. iter.Inet6Addr += ipv6addr.substr(28, 4);
  373. }
  374. }
  375. }
  376. }
  377. }
  378. file.close();
  379. return MEC_OK;
  380. }
  381. void FileHelper::GetComponentFilePaths(
  382. const std::string & root, std::set<std::string> & paths)
  383. {
  384. DIR * dirp = opendir(root.c_str());
  385. if(!dirp)
  386. {
  387. TZLogWarn("open dir %s failed!!!", root.c_str());
  388. return;
  389. }
  390. dirent * dir_entry = nullptr;
  391. while(dir_entry = readdir(dirp))
  392. {
  393. std::string relFName = dir_entry->d_name;
  394. if (relFName.size() < sizeof(SO_SUFFIX)) continue;
  395. std::string extname = relFName.substr(
  396. relFName.size() - sizeof(SO_SUFFIX) + 1);
  397. if (extname == SO_SUFFIX)
  398. {
  399. paths.insert(root + relFName);
  400. }
  401. }
  402. closedir(dirp);
  403. }
  404. void FileHelper::getSingalCmdResult(const std::string & cmd, std::string & res)
  405. {
  406. if (cmd.size() <= 0) return;
  407. FILE * pin = popen(cmd.c_str(), "r");
  408. if (!pin) return;
  409. TZ_CHAR buffer[1024] {0};
  410. if (nullptr == fgets(buffer, 1024, pin))
  411. {
  412. pclose(pin);
  413. return;
  414. }
  415. pclose(pin);
  416. TZLogDebug(1, "%s", buffer);
  417. std::string result(buffer);
  418. if (result.size() >= 1) /* 结果最后有一个\n */
  419. {
  420. res.assign(result.c_str(), result.size() - 1);
  421. }
  422. }
  423. void FileHelper::getPairValues(const std::string & str, TZ_ULONG & values)
  424. {
  425. std::stringstream stream(str);
  426. std::string item;
  427. stream >> item;
  428. stream >> values;
  429. }
  430. void FileHelper::getPairValues(const std::string & str, TZ_ULONGLONG & values)
  431. {
  432. std::stringstream stream(str);
  433. std::string item;
  434. stream >> item;
  435. stream >> values;
  436. }
  437. FileHelper::FileHelper()
  438. {
  439. }
  440. FileHelper::~FileHelper()
  441. {
  442. }
  443. NAMESPACE_MAS_END