ab_code.c 22 KB

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