ab_code.c 21 KB

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