ab_code.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /***************************************************************************
  2. *
  3. * 通用代码
  4. * 常用函数
  5. * 程序日志输出
  6. * 读取解析配置文件
  7. * 代码转换函数
  8. *
  9. * Author : Li Bo Feng
  10. *
  11. * Update History
  12. * DATE OWNER DESCRIPTION
  13. * ----------- ------------ -----------
  14. * 2010-01-19 Li Bo Feng Generated
  15. *
  16. ***************************************************************************/
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <stddef.h>
  20. #include <stdarg.h>
  21. #include <unistd.h>
  22. #include <string.h>
  23. #include <ctype.h>
  24. #include <time.h>
  25. #include <sys/time.h>
  26. #include <sys/file.h>
  27. #include <sys/dir.h>
  28. #include <sys/stat.h>
  29. #include <pthread.h>
  30. #include <sys/types.h>
  31. #include <regex.h>
  32. #include "ab_map.h"
  33. #include "ab_code.h"
  34. #define MAX_LINE_BUFFER_LENGTH 1024
  35. static int ablog_level = -1;
  36. static int _ablog_stdout = 1;
  37. static int ablog_keep_hours = 120;
  38. static FILE *_ablog_file = NULL;
  39. static struct pattern_instance ablog_filename =
  40. {"", "", "", {0}, 0, 0, 0, MAX_FILEPATH_LENGTH, ""};
  41. static int _ablog_print = 0;
  42. int ablog_print()
  43. {
  44. return _ablog_print;
  45. }
  46. int ablog_file()
  47. {
  48. return ablog_filename.pattern[0];
  49. }
  50. int ablog_stdout()
  51. {
  52. return _ablog_stdout;
  53. }
  54. void set_log_filename(char *filepath_pattern)
  55. {
  56. if (_ablog_print == 0)
  57. {
  58. _ablog_print = get_log_print_level();
  59. }
  60. strncpy(ablog_filename.pattern, filepath_pattern, MAX_FILEPATH_LENGTH);
  61. ablog_filename.expiration_ct = 0;
  62. ablog_filename.expiration_vt = 0;
  63. }
  64. void set_log_keephours(int keep_hours)
  65. {
  66. if (_ablog_print == 0)
  67. {
  68. _ablog_print = get_log_print_level();
  69. }
  70. ablog_keep_hours = keep_hours;
  71. }
  72. void set_log_stdout(int yn)
  73. {
  74. if (_ablog_print == 0)
  75. {
  76. _ablog_print = get_log_print_level();
  77. }
  78. _ablog_stdout = yn ? 1 : 0;
  79. }
  80. static int initialized = 0;
  81. static time_t vt_offset = 0;
  82. static int tzone_hours = 0;
  83. static long code_string_mapping = 0;
  84. function_on_ablog_reinitialized on_ablog_reinitialized = 0;
  85. static pthread_mutex_t thread_mut;
  86. void init_coding()
  87. {
  88. if (initialized == 0)
  89. {
  90. pthread_mutex_init(&thread_mut, NULL);
  91. // 虚拟时间偏移
  92. time_t vt = parse_time(getenv("VIRTUAL_TIME"), NULL);
  93. vt_offset = vt == 0 ? 0 : vt - time(0);
  94. // 当前时区偏移
  95. time_t tzone = 0;
  96. tzone_hours = localtime(&tzone)->tm_hour;
  97. // 初始化返回码-字符串映射
  98. code_string_mapping = new_mapping();
  99. // 初始化完毕
  100. initialized = 1;
  101. }
  102. }
  103. static char _code_string[50];
  104. void set_code_string(int n, char *string)
  105. {
  106. sprintf(_code_string, "%d", n);
  107. put_string_mapping(code_string_mapping, _code_string, string);
  108. }
  109. char *code_string(int n)
  110. {
  111. sprintf(_code_string, "%d", n);
  112. char *ret = (char *)get_string_mapping(code_string_mapping, _code_string);
  113. if (ret)
  114. {
  115. return ret;
  116. }
  117. sprintf(_code_string, "code %d[0x%08X]", n, n);
  118. return _code_string;
  119. }
  120. void clear_coding()
  121. {
  122. clear_pattern_instance(&ablog_filename);
  123. clear_mapping();
  124. }
  125. /**
  126. * 虚拟当前时间 virtual_current_time
  127. * 根据环境变量指定的 VIRTUAL_TIME = `date +"%Y-%m-%d %H:%M:%S"`确定时间偏移
  128. * 返回计算后的虚拟当前时间
  129. * 使用此函数前必须在main开始时调用 init_coding();
  130. */
  131. time_t vtime()
  132. {
  133. return time(0) + vt_offset;
  134. }
  135. static time_t t_debug_flag = 0;
  136. static time_t t_debug_pid_flag = 0;
  137. static int b_debug_current_process = 0;
  138. int debug_current_process()
  139. {
  140. if (t_debug_flag < time(0))
  141. {
  142. t_debug_flag = time(0) + 60;
  143. if (access("debug.pid", 0) == 0)
  144. {
  145. if (t_debug_pid_flag == 0)
  146. {
  147. t_debug_pid_flag = 1;
  148. }
  149. }
  150. else
  151. {
  152. t_debug_pid_flag = 0;
  153. b_debug_current_process = 0;
  154. }
  155. }
  156. if (t_debug_pid_flag > 0 && t_debug_pid_flag < time(0))
  157. {
  158. t_debug_pid_flag = time(0) + 5;
  159. char debug_file[50];
  160. sprintf(debug_file, "debug.%d", getpid());
  161. if (access(debug_file, 0) == 0)
  162. {
  163. b_debug_current_process = 1;
  164. }
  165. else
  166. {
  167. b_debug_current_process = 0;
  168. }
  169. }
  170. return b_debug_current_process;
  171. }
  172. time_t _replace_time_pattern(char *buf, int buf_len, time_t st, char CoS)
  173. {
  174. time_t expiration_t = -1;
  175. struct tm *tms = localtime(&st);
  176. int n = (replace_string(buf, CoS == 'C' ? "[yyyy]" : "[YYYY]",
  177. format_int("%04d", (tms->tm_year + 1900)), buf, buf_len));
  178. n |= (replace_string(buf, CoS == 'C' ? "[mm]" : "[MM]", format_int("%02d", (tms->tm_mon + 1)),
  179. buf, buf_len));
  180. n |= (replace_string(buf, CoS == 'C' ? "[dd]" : "[DD]", format_int("%02d", tms->tm_mday), buf,
  181. buf_len));
  182. if (n)
  183. {
  184. // 每天检查是否需要切换文件
  185. expiration_t = ((((st / 3600)) + tzone_hours + 24) / 24 * 24 - tzone_hours) * 3600;
  186. }
  187. if (replace_string(buf, CoS == 'C' ? "[hh]" : "[HH]", format_int("%02d", tms->tm_hour), buf,
  188. buf_len))
  189. {
  190. // 每小时检查是否需要切换文件
  191. expiration_t = (st + 3600) / 3600 * 3600;
  192. }
  193. if (replace_string(buf, CoS == 'C' ? "[mi]" : "[MI]", format_int("%02d", tms->tm_min), buf,
  194. buf_len))
  195. {
  196. // 每分钟检查是否需要切换文件,主要用于测试
  197. expiration_t = (st + 60) / 60 * 60;
  198. }
  199. return expiration_t;
  200. }
  201. void clear_pattern_instance(struct pattern_instance *pi)
  202. {
  203. if (pi->regex[0] != 0)
  204. {
  205. regfree(&pi->reg);
  206. pi->regex[0] = 0;
  207. }
  208. }
  209. int instantiated_pattern(struct pattern_instance *pi)
  210. {
  211. time_t vt = vtime();
  212. time_t ct = time(0);
  213. if ((pi->expiration_ct >= 0 && ct >= pi->expiration_ct) || (pi->expiration_vt >= 0 && vt >= pi->expiration_vt))
  214. {
  215. strncpy(pi->instance, pi->pattern, pi->instance_buf_len);
  216. replace_string(pi->instance, "[PID]", format_int("%d", getpid()), pi->instance,
  217. pi->instance_buf_len);
  218. replace_string(pi->instance, "[pid]", format_int("%d", getpid()), pi->instance,
  219. pi->instance_buf_len);
  220. if (strcmp(pi->last_pattern, pi->pattern) != 0)
  221. {
  222. char regex[MAX_FILEPATH_LENGTH];
  223. strncpy(regex, pi->pattern, MAX_FILEPATH_LENGTH);
  224. // 正则表达式通配符
  225. replace_string(regex, "\\", "\\\\", regex, MAX_FILEPATH_LENGTH);
  226. replace_string(regex, ".", "\\.", regex, MAX_FILEPATH_LENGTH);
  227. replace_string(regex, "|", "\\|", regex, MAX_FILEPATH_LENGTH);
  228. replace_string(regex, "(", "\\(", regex, MAX_FILEPATH_LENGTH);
  229. replace_string(regex, ")", "\\)", regex, MAX_FILEPATH_LENGTH);
  230. replace_string(regex, "{", "\\{", regex, MAX_FILEPATH_LENGTH);
  231. replace_string(regex, "}", "\\}", regex, MAX_FILEPATH_LENGTH);
  232. replace_string(regex, "*", "\\*", regex, MAX_FILEPATH_LENGTH);
  233. replace_string(regex, "+", "\\+", regex, MAX_FILEPATH_LENGTH);
  234. replace_string(regex, "?", "\\?", regex, MAX_FILEPATH_LENGTH);
  235. replace_string(regex, "^", "\\^", regex, MAX_FILEPATH_LENGTH);
  236. replace_string(regex, "$", "\\$", regex, MAX_FILEPATH_LENGTH);
  237. // 临时转义[]
  238. replace_string(regex, "&", "&a", regex, MAX_FILEPATH_LENGTH);
  239. replace_string(regex, "[", "&[", regex, MAX_FILEPATH_LENGTH);
  240. replace_string(regex, "]", "&]", regex, MAX_FILEPATH_LENGTH);
  241. // 文件名支持定义内容转义
  242. replace_string(regex, "&[PID&]", "[0-9]*", regex, MAX_FILEPATH_LENGTH);
  243. replace_string(regex, "&[pid&]", "[0-9]*", regex, MAX_FILEPATH_LENGTH);
  244. replace_string(regex, "&[YYYY&]", "[0-9]{4}", regex, MAX_FILEPATH_LENGTH);
  245. replace_string(regex, "&[yyyy&]", "[0-9]{4}", regex, MAX_FILEPATH_LENGTH);
  246. replace_string(regex, "&[MM&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH);
  247. replace_string(regex, "&[mm&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH);
  248. replace_string(regex, "&[DD&]", "[0-9]{2}", regex, MAX_FILEPATH_LENGTH);
  249. replace_string(regex, "&[dd&]", "[0-9]{2}", regex,
  250. MAX_FILEPATH_LENGTH);
  251. replace_string(regex, "&[HH&]", "[0-9]{2}", regex,
  252. MAX_FILEPATH_LENGTH);
  253. replace_string(regex, "&[hh&]", "[0-9]{2}", regex,
  254. MAX_FILEPATH_LENGTH);
  255. replace_string(regex, "&[MI&]", "[0-9]{2}", regex,
  256. MAX_FILEPATH_LENGTH);
  257. replace_string(regex, "&[mi&]", "[0-9]{2}", regex,
  258. MAX_FILEPATH_LENGTH);
  259. // []转义
  260. replace_string(regex, "&[", "\\[", regex, MAX_FILEPATH_LENGTH);
  261. replace_string(regex, "&]", "\\]", regex, MAX_FILEPATH_LENGTH);
  262. // 恢复临时转义
  263. replace_string(regex, "&a", "&", regex, MAX_FILEPATH_LENGTH);
  264. if (pi->regex[0] != 0)
  265. {
  266. regfree(&pi->reg);
  267. pi->regex[0] = 0;
  268. }
  269. if (regex[0] != 0)
  270. {
  271. int reti = regcomp(&pi->reg, regex, REG_EXTENDED);
  272. if (reti != 0)
  273. {
  274. char errbuf[256];
  275. regerror(reti, &pi->reg, errbuf, sizeof(errbuf));
  276. log_println("ABLOG_INIT", __FILE__, __LINE__, "ERROR:%s", errbuf);
  277. }
  278. else
  279. {
  280. strncpy(pi->regex, regex, MAX_FILEPATH_LENGTH);
  281. }
  282. }
  283. strncpy(pi->last_pattern, pi->pattern, MAX_FILEPATH_LENGTH);
  284. }
  285. pi->expiration_ct = _replace_time_pattern(pi->instance, pi->instance_buf_len, ct, 'C');
  286. pi->expiration_vt = _replace_time_pattern(pi->instance, pi->instance_buf_len, vt, 'V');
  287. pi->instantiated_time = time(0);
  288. return 1;
  289. }
  290. return 0;
  291. }
  292. int matched_logfile_pattern(struct pattern_instance *pi, char *filepath)
  293. {
  294. if (pi->regex[0] != 0)
  295. {
  296. int reti = regexec(&pi->reg, filepath, 0, NULL, 0);
  297. if (reti == 0)
  298. {
  299. // log_println("I", __FILE__, __LINE__, "%s match %s", filepath, pi->regex);
  300. return 1; // 匹配成功
  301. }
  302. if (reti == REG_NOMATCH)
  303. {
  304. // log_println("I", __FILE__, __LINE__, "%s not match %s", filepath, pi->regex);
  305. return 0; // 不匹配
  306. }
  307. char errbuf[256];
  308. regerror(reti, &pi->reg, errbuf, sizeof(errbuf));
  309. log_println("E", __FILE__, __LINE__, "%s", errbuf);
  310. }
  311. return 0;
  312. }
  313. int lock_file(char *filename, int wait)
  314. {
  315. int lockfd = open(filename, O_RDWR | O_CREAT, 0666);
  316. if (lockfd)
  317. {
  318. int flock_cmd = wait ? F_SETLKW : F_SETLK;
  319. static struct flock flock_args;
  320. flock_args.l_type = F_WRLCK;
  321. flock_args.l_start = 0;
  322. flock_args.l_whence = SEEK_SET;
  323. flock_args.l_len = 0;
  324. flock_args.l_pid = getpid();
  325. if (fcntl(lockfd, flock_cmd, &flock_args) == 0)
  326. {
  327. return lockfd;
  328. }
  329. close(lockfd);
  330. }
  331. return 0;
  332. }
  333. int unlock_file(int lockfd)
  334. {
  335. int ret = 0;
  336. if (lockfd)
  337. {
  338. int flock_cmd = F_SETLK;
  339. static struct flock flock_args;
  340. flock_args.l_type = F_UNLCK;
  341. flock_args.l_start = 0;
  342. flock_args.l_whence = SEEK_SET;
  343. flock_args.l_len = 0;
  344. flock_args.l_pid = getpid();
  345. if (fcntl(lockfd, flock_cmd, &flock_args) == 0)
  346. {
  347. ret = 1;
  348. }
  349. close(lockfd);
  350. }
  351. return ret;
  352. }
  353. int _ablog_lock(char *dir)
  354. {
  355. int ret = 0;
  356. char buf[MAX_LINE_BUFFER_LENGTH];
  357. char lock_filename[MAX_FILEPATH_LENGTH];
  358. sprintf(lock_filename, "%s%s", dir, ".lock");
  359. int ablog_lockfd = lock_file(lock_filename, 0);
  360. if (ablog_lockfd)
  361. {
  362. memset(buf, 0, sizeof(buf));
  363. read(ablog_lockfd, buf, sizeof(buf));
  364. time_t t = parse_time(buf, NULL);
  365. if (t < time(0))
  366. {
  367. strcpy(buf, time_string(time(0) + 60));
  368. lseek(ablog_lockfd, 0, SEEK_SET);
  369. write(ablog_lockfd, buf, strlen(buf));
  370. ret = 1;
  371. }
  372. unlock_file(ablog_lockfd);
  373. }
  374. else
  375. {
  376. log_println("ABLOG_FILE", __FILE__, __LINE__, "lock file[%s] failed.", lock_filename);
  377. }
  378. return ret;
  379. }
  380. int _ablog_rm_old_files(struct pattern_instance *pi, char *dir, time_t time_before)
  381. {
  382. // if (!_ablog_lock(dir))
  383. // {
  384. // // log_println("ABLOG_FILE", __FILE__, __LINE__, "lock dir failed: %s", dir);
  385. // return -1;
  386. // }
  387. DIR *od = opendir(dir);
  388. if (od == NULL)
  389. {
  390. // log_println("ABLOG_FILE", __FILE__, __LINE__, "open dir failed: %s", dir);
  391. return -1;
  392. }
  393. char file[MAX_FILEPATH_LENGTH];
  394. struct stat file_stat;
  395. struct dirent *ent;
  396. int n = 0;
  397. while ((ent = readdir(od)) != NULL)
  398. {
  399. if (ent->d_name[0] != '.')
  400. {
  401. sprintf(file, "%s%s", dir, ent->d_name);
  402. if (matched_logfile_pattern(pi, file))
  403. {
  404. stat(file, &file_stat);
  405. // printf("%32s %s ", namelist[i]->d_name, time_string(file_stat.st_mtime));
  406. if (S_ISREG(file_stat.st_mode) && file_stat.st_mtime < time_before)
  407. {
  408. remove(file);
  409. n++;
  410. log_println("ABLOG_FILE", __FILE__, __LINE__, "remove old log file: %s", file);
  411. }
  412. // printf("\n");
  413. }
  414. }
  415. }
  416. closedir(od);
  417. if (n > 0)
  418. {
  419. log_println("ABLOG_FILE", __FILE__, __LINE__, "%d old log files removed", n);
  420. }
  421. return n;
  422. }
  423. int remove_old_log_files(time_t time_before)
  424. {
  425. if (strlen(ablog_filename.instance) == 0)
  426. {
  427. return 0;
  428. }
  429. char buf[MAX_FILEPATH_LENGTH];
  430. strcpy(buf, ablog_filename.instance);
  431. char *c = buf + strlen(buf) - 1;
  432. while (*c != '/' && c >= buf)
  433. {
  434. *c = '\0';
  435. --c;
  436. }
  437. if (buf[0] == 0)
  438. {
  439. strcpy(buf, "./");
  440. }
  441. return _ablog_rm_old_files(&ablog_filename, buf, time_before);
  442. }
  443. void _ablog_set_log_file()
  444. {
  445. if (instantiated_pattern(&ablog_filename))
  446. {
  447. if (_ablog_file)
  448. {
  449. fclose(_ablog_file);
  450. }
  451. if (strlen(ablog_filename.instance) > 0)
  452. {
  453. if (mk_parent_dir(ablog_filename.instance) != 0)
  454. {
  455. _ablog_stdout = 1;
  456. log_println("ABLOG_FILE", __FILE__, __LINE__, "make parent dir error, '%s'",
  457. ablog_filename.instance);
  458. }
  459. // printf("ablog_filename.instance=%s\n", ablog_filename.instance);
  460. _ablog_file = fopen(ablog_filename.instance, "a");
  461. if (!_ablog_file)
  462. {
  463. _ablog_stdout = 1;
  464. log_println("ABLOG_FILE", __FILE__, __LINE__, "File append error, '%s'",
  465. ablog_filename.instance);
  466. }
  467. // else
  468. // {
  469. // log_println("ABLOG_FILE", __FILE__, __LINE__, "%s", ablog_filename.instance);
  470. // }
  471. }
  472. if (on_ablog_reinitialized)
  473. {
  474. on_ablog_reinitialized();
  475. }
  476. remove_old_log_files(time(0) - ablog_keep_hours * 3600);
  477. }
  478. }
  479. void mc_print_log(long mtc, char *info, char *file, int line)
  480. {
  481. log_println("MEMORY_CHECK", file, line, "malloc %ld, %s", mtc, info);
  482. }
  483. static int ablog_level_setting = LPL_All;
  484. #define CHECK_ABLOG_CLASS(N) (strcasecmp(#N, buf) == 0) ? LPL_##N
  485. #define SHOW_ABLOG_CLASS(N) (ablog_level & LPL_##N) ? #N
  486. int get_log_print_level()
  487. {
  488. if (ablog_level == -1)
  489. {
  490. init_coding();
  491. parse_int(getenv("ABLOG_KEEP_HOURS"), &ablog_keep_hours, ablog_keep_hours);
  492. parse_int(getenv("ABLOG_STDOUT"), &_ablog_stdout, _ablog_stdout);
  493. char *sf = getenv("ABLOG_FILE");
  494. if (sf)
  495. {
  496. strncpy(ablog_filename.pattern, sf, MAX_FILEPATH_LENGTH);
  497. }
  498. _ablog_set_log_file();
  499. // 重定向内存检查输出
  500. mc_print = mc_print_log;
  501. char buf[32];
  502. char *lpls = getenv("ABLOG_CLASS");
  503. if (lpls)
  504. {
  505. ablog_level = 0;
  506. while (*lpls)
  507. {
  508. buf[0] = 0;
  509. lpls = split_string_next(lpls, ',', buf, sizeof(buf));
  510. int n = CHECK_ABLOG_CLASS(All) : CHECK_ABLOG_CLASS(Error) : CHECK_ABLOG_CLASS(Metrics) : CHECK_ABLOG_CLASS(State) : CHECK_ABLOG_CLASS(Detail) : CHECK_ABLOG_CLASS(Flow) : CHECK_ABLOG_CLASS(Flow_Public) : CHECK_ABLOG_CLASS(Flow_Private) : CHECK_ABLOG_CLASS(Flow_Restricted) : CHECK_ABLOG_CLASS(Flow_Minor) : 0;
  511. if (n != 0)
  512. {
  513. log_println("ABLOG_CLASS", __FILE__, __LINE__,
  514. "configured ablog class #%02X %s", n, buf);
  515. ablog_level |= n;
  516. }
  517. }
  518. }
  519. else
  520. {
  521. ablog_level = ablog_level_setting;
  522. }
  523. if (vt_offset != 0)
  524. {
  525. log_println("VIRTUAL_TIME", __FILE__, __LINE__, "configured virtual time [%s]",
  526. time_string(vtime()));
  527. }
  528. ablog_level_setting = ablog_level;
  529. }
  530. return debug_current_process() ? LPL_All : ablog_level_setting;
  531. }
  532. /**
  533. * 输出一行日志信息
  534. */
  535. void log_println(const char *func, const char *file, int line, const char *format, ...)
  536. {
  537. if (ablog_file())
  538. {
  539. va_list vl;
  540. va_start(vl, format);
  541. log_println_vl(1, func, file, line, format, vl);
  542. va_end(vl);
  543. }
  544. if (ablog_stdout())
  545. {
  546. va_list vl;
  547. va_start(vl, format);
  548. log_println_vl(0, func, file, line, format, vl);
  549. va_end(vl);
  550. }
  551. }
  552. void log_println_vl(int fileout, const char *func, const char *file, int line, const char *format, va_list vl)
  553. {
  554. struct timeval tv;
  555. gettimeofday(&tv, NULL);
  556. FILE *fout = stdout;
  557. if (fileout)
  558. {
  559. _ablog_set_log_file();
  560. fout = _ablog_file;
  561. if (!fout)
  562. {
  563. return;
  564. }
  565. }
  566. pthread_mutex_lock(&thread_mut);
  567. fprintf(fout, "%s.%03ld[%s]:", time_string(tv.tv_sec), (tv.tv_usec / 1000l), func);
  568. vfprintf(fout, format, vl);
  569. fprintf(fout, " (%s:%d)\n", file, line);
  570. fflush(fout);
  571. pthread_mutex_unlock(&thread_mut);
  572. }
  573. /**
  574. * 解析十六进制数
  575. * 解析结果通过输出参数o返回
  576. * 解析失败返回0,解析成功返回非0
  577. */
  578. int parse_hex(char *s, int *o, int default_value)
  579. {
  580. int x = 0;
  581. int i = 0;
  582. int n = 0;
  583. int c, t;
  584. *o = default_value;
  585. if (s)
  586. {
  587. for (; isspace((int)s[i]); i++)
  588. ;
  589. if (s[i] == 'h' || s[i] == 'H' || s[i] == 'x' || s[i] == 'X')
  590. {
  591. i++;
  592. }
  593. else if (s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X'))
  594. {
  595. i += 2;
  596. }
  597. for (; (c = s[i]) != 0 && !isspace((int)c); i++, n++)
  598. {
  599. t = c >= '0' && c <= '9' ? (c - '0') : c >= 'A' && c <= 'F' ? (c - 'A' + 10)
  600. : c >= 'a' && c <= 'f' ? (c - 'a' + 10)
  601. : -1;
  602. if (t == -1)
  603. {
  604. return 0;
  605. }
  606. x <<= 4;
  607. x |= t;
  608. }
  609. for (; isspace((int)s[i]); i++)
  610. ;
  611. if (s[i] != 0 || n == 0)
  612. {
  613. return 0;
  614. }
  615. *o = x;
  616. }
  617. return n;
  618. }
  619. /**
  620. * 解析十进制数
  621. * 解析结果通过输出参数o返回
  622. * 解析失败返回0,解析成功返回非0
  623. */
  624. int parse_int(char *s, int *o, int default_value)
  625. {
  626. int x = 0;
  627. int i = 0;
  628. int n = 0;
  629. int c, t;
  630. *o = default_value;
  631. if (s)
  632. {
  633. for (; isspace((int)s[i]); i++)
  634. ;
  635. for (; (c = s[i]) != 0; i++, n++)
  636. {
  637. t = c >= '0' && c <= '9' ? (c - '0') : -1;
  638. if (t == -1)
  639. {
  640. return 0;
  641. }
  642. x = x * 10 + t;
  643. }
  644. for (; isspace((int)s[i]); i++)
  645. ;
  646. if (s[i] != 0 || n == 0)
  647. {
  648. return 0;
  649. }
  650. *o = x;
  651. }
  652. return n;
  653. }
  654. /**
  655. * 解析十进制数
  656. * 解析结果通过输出参数o返回
  657. * 解析失败返回0,解析成功返回非0
  658. */
  659. int parse_double(char *s, double *o, double default_value)
  660. {
  661. int signal = 1;
  662. double x = 0;
  663. double t = 0;
  664. int i = 0;
  665. int n = 0;
  666. int c;
  667. *o = default_value;
  668. if (s)
  669. {
  670. for (; isspace((int)s[i]); i++)
  671. ;
  672. if ((c = s[i]) == '-' || c == '+')
  673. {
  674. signal = c == '-' ? -1 : 1;
  675. i++;
  676. }
  677. for (; (c = s[i]) >= '0' && c <= '9'; i++, n++)
  678. {
  679. x = x * 10 + (c - '0');
  680. }
  681. if ((c = s[i]) == '.')
  682. {
  683. i++;
  684. t = 1;
  685. for (; (c = s[i]) >= '0' && c <= '9'; i++, n++)
  686. {
  687. t /= 10;
  688. x = x + t * (c - '0');
  689. }
  690. }
  691. for (; isspace((int)s[i]); i++)
  692. ;
  693. if (s[i] != 0 || n == 0)
  694. {
  695. return 0;
  696. }
  697. *o = signal * x;
  698. }
  699. return n;
  700. }
  701. /**
  702. * 格式化数字字符串
  703. */
  704. static char int_string_buffer[20][100];
  705. static int int_string_buffer_i = 0;
  706. char *format_int(char *format, int n)
  707. {
  708. int_string_buffer_i++;
  709. if (int_string_buffer_i >= 20)
  710. {
  711. int_string_buffer_i = 0;
  712. }
  713. sprintf(int_string_buffer[int_string_buffer_i], format, n);
  714. return int_string_buffer[int_string_buffer_i];
  715. }
  716. char *format_long(char *format, long n)
  717. {
  718. int_string_buffer_i++;
  719. if (int_string_buffer_i >= 20)
  720. {
  721. int_string_buffer_i = 0;
  722. }
  723. sprintf(int_string_buffer[int_string_buffer_i], format, n);
  724. return int_string_buffer[int_string_buffer_i];
  725. }
  726. char *format_double(char *format, double n)
  727. {
  728. int_string_buffer_i++;
  729. if (int_string_buffer_i >= 20)
  730. {
  731. int_string_buffer_i = 0;
  732. }
  733. sprintf(int_string_buffer[int_string_buffer_i], format, n);
  734. return int_string_buffer[int_string_buffer_i];
  735. }
  736. char *int_string(int n)
  737. {
  738. return format_int("%d", n);
  739. }
  740. /**
  741. * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串
  742. * 返回标准时间秒数,毫秒值通过输出参数ms返回
  743. * 解析失败返回 0
  744. */
  745. time_t parse_time(char *stime, long *ms)
  746. {
  747. if (stime == NULL || stime[0] == 0)
  748. {
  749. return 0;
  750. }
  751. char *c = stime;
  752. while ((isspace((int)*c)))
  753. {
  754. c++;
  755. }
  756. if (*c == 0)
  757. {
  758. return 0;
  759. }
  760. char timestr[25];
  761. strncpy(timestr, c, 24);
  762. struct tm tm;
  763. memset(&tm, 0, sizeof(tm));
  764. int rms = 0;
  765. sscanf(timestr, "%d-%d-%d %d:%d:%d.%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour,
  766. &tm.tm_min, &tm.tm_sec, &rms);
  767. if (ms != NULL)
  768. {
  769. *ms = rms;
  770. }
  771. tm.tm_year -= 1900;
  772. tm.tm_mon -= 1;
  773. tm.tm_isdst = 0;
  774. time_t time_t = mktime(&tm);
  775. return time_t;
  776. }
  777. /**
  778. * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串
  779. * 返回timeval形式
  780. */
  781. struct timeval parse_time_tv(char *stime)
  782. {
  783. struct timeval tv;
  784. tv.tv_usec = 0;
  785. long milliseconds;
  786. tv.tv_sec = parse_time(stime, &milliseconds);
  787. tv.tv_usec = milliseconds * 1000; // microseconds
  788. return tv;
  789. }
  790. /**
  791. * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串
  792. * 返回标准时间毫秒数
  793. */
  794. long parse_time_lms(char *stime)
  795. {
  796. long ms = 0;
  797. long lms = 1000L * parse_time(stime, &ms);
  798. return lms + ms;
  799. }
  800. /**
  801. * 格式化时间字符串
  802. * 返回格式为 yyyy-MM-dd HH:mm:ss的时间字符串
  803. */
  804. static char time_string_buffer[20][25];
  805. static int time_string_buffer_i = 0;
  806. char *time_string(time_t seconds)
  807. {
  808. time_string_buffer_i++;
  809. if (time_string_buffer_i >= 20)
  810. {
  811. time_string_buffer_i = 0;
  812. }
  813. struct tm *tmp = localtime(&seconds);
  814. tmp->tm_year = tmp->tm_year + 1900;
  815. tmp->tm_mon = tmp->tm_mon + 1;
  816. sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d", tmp->tm_year,
  817. tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
  818. return time_string_buffer[time_string_buffer_i];
  819. }
  820. /**
  821. * 格式化时间字符串
  822. * 返回格式为 yyyy-MM-dd HH:mm:ss.SSS的时间字符串
  823. */
  824. char *time_tv_string(struct timeval tv)
  825. {
  826. time_string_buffer_i++;
  827. if (time_string_buffer_i >= 20)
  828. {
  829. time_string_buffer_i = 0;
  830. }
  831. time_t seconds = tv.tv_sec;
  832. int dms = (int)(tv.tv_usec / 1000);
  833. struct tm *tmp = localtime(&seconds);
  834. tmp->tm_year = tmp->tm_year + 1900;
  835. tmp->tm_mon = tmp->tm_mon + 1;
  836. sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d.%03d",
  837. tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, dms);
  838. return time_string_buffer[time_string_buffer_i];
  839. }
  840. /**
  841. * 格式化时间字符串
  842. * 返回格式为 yyyy-MM-dd HH:mm:ss.SSS的时间字符串
  843. */
  844. char *time_lms_string(time_long milliseconds)
  845. {
  846. time_string_buffer_i++;
  847. if (time_string_buffer_i >= 20)
  848. {
  849. time_string_buffer_i = 0;
  850. }
  851. time_t seconds = milliseconds / 1000;
  852. int dms = (int)(milliseconds % 1000);
  853. struct tm *tmp = localtime(&seconds);
  854. tmp->tm_year = tmp->tm_year + 1900;
  855. tmp->tm_mon = tmp->tm_mon + 1;
  856. sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d.%03d",
  857. tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, dms);
  858. return time_string_buffer[time_string_buffer_i];
  859. }
  860. /**
  861. * MUST recv_buf length >= strlen(source) + 1
  862. */
  863. char **split_string(char *source, char split_char, char *recv_buf, int recv_buf_bytes,
  864. char **recv_buf_array, int recv_buf_array_size)
  865. {
  866. ABLOG_Entry(Public, split_string);
  867. int iout = 0;
  868. int n = 0;
  869. char *recv;
  870. char *scur = NULL;
  871. char *snext = source;
  872. while (*snext)
  873. {
  874. scur = snext;
  875. recv_buf_array[iout] = recv_buf;
  876. recv = recv_buf;
  877. iout++;
  878. if (iout >= recv_buf_array_size)
  879. {
  880. split_char = 0;
  881. snext += strlen(scur);
  882. }
  883. else
  884. {
  885. snext = split_string_next(scur, split_char, recv, recv_buf_bytes);
  886. }
  887. n = snext - scur;
  888. recv_buf_bytes -= n;
  889. if (recv_buf_bytes <= 0)
  890. {
  891. ABLOG_(Error, "[W] substring[%d] is too long, length[%d], %s...", iout, n, recv);
  892. }
  893. recv_buf += n;
  894. }
  895. while (iout < recv_buf_array_size)
  896. {
  897. recv_buf_array[iout] = 0;
  898. iout++;
  899. }
  900. ABLOG_Return(recv_buf_array);
  901. }
  902. /**
  903. * 分割字符串 source
  904. * 按指定字符 split_char 分割
  905. * 通过 recv_buf 接收分割出来的字符串
  906. * 接收缓冲区长度 recv_buf_len
  907. * 返回下一分割段的起始位置,没有下一段时*source应该为0;
  908. */
  909. char *split_string_next(char *source, char split_char, char *recv_buf, int recv_buf_len)
  910. {
  911. char c;
  912. int n = 0;
  913. while ((c = *source) && c != split_char)
  914. {
  915. if (n < recv_buf_len - 1)
  916. {
  917. *recv_buf = c;
  918. recv_buf++;
  919. }
  920. source++;
  921. n++;
  922. }
  923. *recv_buf = 0;
  924. if (split_char != 0 && c == split_char)
  925. {
  926. source++;
  927. }
  928. return source;
  929. }
  930. int replace_string(char *source, char *find, char *replace, char *recv_buf, int recv_buf_len)
  931. {
  932. int n = 0;
  933. // 原字符串
  934. char *temp_buf = 0;
  935. if (source == recv_buf)
  936. {
  937. temp_buf = (char *)malloc(strlen(source) + 1);
  938. strcpy(temp_buf, source);
  939. source = temp_buf;
  940. }
  941. int rbfl = recv_buf_len;
  942. // 开始替换
  943. char *found = strstr(source, find);
  944. if (rbfl > 0 && found)
  945. {
  946. int snfl = strlen(find);
  947. int snrl = strlen(replace);
  948. do
  949. {
  950. int cpyn = (found - source);
  951. if (cpyn >= 0)
  952. {
  953. cpyn = cpyn < rbfl ? cpyn : rbfl;
  954. memcpy(recv_buf, source, cpyn);
  955. source = found + snfl;
  956. recv_buf += cpyn;
  957. rbfl -= cpyn;
  958. }
  959. if (rbfl > 0)
  960. {
  961. cpyn = snrl < rbfl ? snrl : rbfl;
  962. memcpy(recv_buf, replace, cpyn);
  963. recv_buf += cpyn;
  964. rbfl -= cpyn;
  965. }
  966. found = strstr(source, find);
  967. n++;
  968. } while (rbfl > 0 && found);
  969. }
  970. if (rbfl > 0)
  971. {
  972. strncpy(recv_buf, source, rbfl);
  973. }
  974. if (temp_buf)
  975. {
  976. free(temp_buf);
  977. }
  978. return n;
  979. }
  980. char *toUpperCase(const char *str, char *rbuf)
  981. {
  982. for (; *str; str++, rbuf++)
  983. {
  984. *rbuf = toupper((int)*str);
  985. }
  986. *rbuf = 0;
  987. return rbuf;
  988. }
  989. char *trimRight(const char *str, char *rbuf)
  990. {
  991. char *c = (char *)str;
  992. if (rbuf == 0)
  993. {
  994. rbuf = c;
  995. }
  996. c += strlen(str) - 1;
  997. while (isspace((int)*c) && c >= str)
  998. {
  999. --c;
  1000. }
  1001. if (c < str)
  1002. {
  1003. rbuf[0] = 0;
  1004. }
  1005. else
  1006. {
  1007. memcpy(rbuf, str, c - str + 1);
  1008. rbuf[c - str + 1] = 0;
  1009. }
  1010. return rbuf;
  1011. }
  1012. char *trimLeft(const char *str, char *rbuf)
  1013. {
  1014. char *c = (char *)str;
  1015. if (rbuf == 0)
  1016. {
  1017. rbuf = c;
  1018. }
  1019. while ((isspace((int)*c)) != 0)
  1020. {
  1021. c++;
  1022. }
  1023. strcpy(rbuf, c);
  1024. return rbuf;
  1025. }
  1026. // char *trim(const char *str, char *rbuf)
  1027. // {
  1028. // if (rbuf == 0)
  1029. // {
  1030. // rbuf = (char *)str;
  1031. // }
  1032. // trimLeft(str, rbuf);
  1033. // trimRight(rbuf, rbuf);
  1034. // return rbuf;
  1035. // }
  1036. // long read_mapping_file(int fd)
  1037. // {
  1038. // ABLOG_Entry(Public, read_mapping_file);
  1039. // long ret_map_id = new_mapping();
  1040. // int flen = lseek(fd, 0, SEEK_END);
  1041. // char *buf = MALLOC(flen + 1);
  1042. // memset(buf, 0, flen + 1);
  1043. // lseek(fd, 0, SEEK_SET);
  1044. // read(fd, buf, flen);
  1045. // char *line_buffer = buf;
  1046. // while (line_buffer[0])
  1047. // {
  1048. // char *newline = strstr(line_buffer, "\n");
  1049. // if (newline)
  1050. // {
  1051. // newline[0] = 0;
  1052. // }
  1053. // trimLeft(line_buffer, 0);
  1054. // if (line_buffer[0] != '#' && strlen(line_buffer) > 0)
  1055. // {
  1056. // char *kv[2];
  1057. // split_string(line_buffer, '=', line_buffer, flen + 1, kv, 2);
  1058. // char *key = trim(kv[0], 0);
  1059. // char *value = trim(kv[1], 0);
  1060. // ABLOG_Printf(Detail, (ABLOG, "[D] %s=%s", key, value));
  1061. // put_string_mapping(ret_map_id, key, value);
  1062. // }
  1063. // line_buffer = newline ? newline + 1 : 0;
  1064. // }
  1065. // FREE(buf);
  1066. // ABLOG_Return_Long(ret_map_id);
  1067. // }
  1068. int write_mapping_file(int fd, long mid)
  1069. {
  1070. ABLOG_Entry(Public, read_mapping_file);
  1071. MapEntry me = items_mapping(mid);
  1072. lseek(fd, 0, SEEK_SET);
  1073. ftruncate(fd, 0);
  1074. while (me)
  1075. {
  1076. write(fd, me->key, strlen(me->key));
  1077. write(fd, "=", 1);
  1078. write(fd, me->value, strlen(me->value));
  1079. write(fd, "\r\n", 2);
  1080. me = me->next;
  1081. }
  1082. ABLOG_Return_Int(lseek(fd, 0, SEEK_END));
  1083. }
  1084. #define DIR_MODE (S_IRWXU | S_IRWXG | S_IRWXO)
  1085. int mk_dir(char *dir)
  1086. {
  1087. DIR *mydir = NULL;
  1088. if ((mydir = opendir(dir)) == NULL) // 判断目录
  1089. {
  1090. int ret = mk_parent_dir(dir);
  1091. if (ret != 0)
  1092. {
  1093. return ret;
  1094. }
  1095. ret = mkdir(dir, DIR_MODE); // 创建目录
  1096. if (ret != 0)
  1097. {
  1098. // printf("%s created failed!\n", dir);
  1099. return ret;
  1100. }
  1101. // printf("%s created sucess!\n", dir);
  1102. }
  1103. // else printf("%s exist!\n", dir);
  1104. return 0;
  1105. }
  1106. int mk_parent_dir(char *filepath)
  1107. {
  1108. char *pIndex = rindex(filepath, '/');
  1109. if (pIndex != NULL && pIndex != filepath)
  1110. {
  1111. char pdir[512] = {0};
  1112. int msg_size = pIndex - filepath;
  1113. memcpy(pdir, filepath, msg_size);
  1114. // printf("%s\n", pdir);
  1115. return mk_dir(pdir);
  1116. }
  1117. return 0;
  1118. }