12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046 |
- /***************************************************************************
- *
- * 通用代码
- * 常用函数
- * 程序日志输出
- * 读取解析配置文件
- * 代码转换函数
- *
- * Author : Li Bo Feng
- *
- * Update History
- * DATE OWNER DESCRIPTION
- * ----------- ------------ -----------
- * 2010-01-19 Li Bo Feng Generated
- *
- ***************************************************************************/
- #include <stdio.h>
- #include <stdlib.h>
- #include <stddef.h>
- #include <stdarg.h>
- #include <unistd.h>
- #include <string.h>
- #include <ctype.h>
- #include <time.h>
- #include <sys/time.h>
- #include <sys/file.h>
- #include <sys/dir.h>
- #include <sys/stat.h>
- #include <pthread.h>
- #include "ab_map.h"
- #include "ab_code.h"
- #pragma -Wincompatible-pointer-types
- #define MAX_LINE_BUFFER_LENGTH 1024
- static int ablog_level = -1;
- static FILE *ablog_file = NULL;
- static int ablog_stdout = 1;
- static int ablog_keep_hours = 120;
- static struct pattern_instance ablog_filename =
- { "", 0, 0, 0, MAX_FILEPATH_LENGTH, "" };
- void set_log_filename(char* filepath_pattern) {
- strncpy(ablog_filename.pattern, filepath_pattern, MAX_FILEPATH_LENGTH);
- }
- void set_log_keephours(int keep_hours) {
- ablog_keep_hours = keep_hours;
- }
- void set_log_stdout(int yn) {
- ablog_stdout = yn ? 1 : 0;
- }
- static int initialized = 0;
- static time_t vt_offset = 0;
- static int tzone_hours = 0;
- static long code_string_mapping = 0;
- function_on_ablog_reinitialized on_ablog_reinitialized = 0;
- static pthread_mutex_t thread_mut;
- void init_coding()
- {
- if (initialized == 0)
- {
- pthread_mutex_init(&thread_mut, NULL);
- // 虚拟时间偏移
- time_t vt = parse_time(getenv("VIRTUAL_TIME"), NULL);
- vt_offset = vt == 0 ? 0 : vt - time(0);
- // 当前时区偏移
- time_t tzone = 0;
- tzone_hours = localtime(&tzone)->tm_hour;
- // 初始化返回码-字符串映射
- code_string_mapping = new_mapping();
- // 初始化完毕
- initialized = 1;
- }
- }
- static char _code_string[50];
- void set_code_string(int n, char* string)
- {
- sprintf(_code_string, "%d", n);
- put_string_mapping(code_string_mapping, _code_string, string);
- }
- char* code_string(int n)
- {
- sprintf(_code_string, "%d", n);
- char* ret = (char*) get_string_mapping(code_string_mapping, _code_string);
- if (ret)
- {
- return ret;
- }
- sprintf(_code_string, "code %d[0x%08X]", n, n);
- return _code_string;
- }
- void clear_coding()
- {
- clear_mapping();
- }
- /**
- * 虚拟当前时间 virtual_current_time
- * 根据环境变量指定的 VIRTUAL_TIME = `date +"%Y-%m-%d %H:%M:%S"`确定时间偏移
- * 返回计算后的虚拟当前时间
- * 使用此函数前必须在main开始时调用 init_coding();
- */
- time_t vtime()
- {
- return time(0) + vt_offset;
- }
- static time_t t_debug_flag = 0;
- static time_t t_debug_pid_flag = 0;
- static int b_debug_current_process = 0;
- int debug_current_process()
- {
- if (t_debug_flag < time(0))
- {
- t_debug_flag = time(0) + 60;
- if (access("debug.pid", 0) == 0)
- {
- if (t_debug_pid_flag == 0)
- {
- t_debug_pid_flag = 1;
- }
- }
- else
- {
- t_debug_pid_flag = 0;
- b_debug_current_process = 0;
- }
- }
- if (t_debug_pid_flag > 0 && t_debug_pid_flag < time(0))
- {
- t_debug_pid_flag = time(0) + 5;
- char debug_file[50];
- sprintf(debug_file, "debug.%d", getpid());
- if (access(debug_file, 0) == 0)
- {
- b_debug_current_process = 1;
- }
- else
- {
- b_debug_current_process = 0;
- }
- }
- return b_debug_current_process;
- }
- time_t _replace_time_pattern(char *buf, int buf_len, time_t st, char CoS)
- {
- time_t expiration_t = -1;
- struct tm *tms = localtime(&st);
- int n = (replace_string(buf, CoS == 'C' ? "[yyyy]" : "[YYYY]",
- format_int("%04d", (tms->tm_year + 1900)), buf, buf_len));
- n |= (replace_string(buf, CoS == 'C' ? "[mm]" : "[MM]", format_int("%02d", (tms->tm_mon + 1)),
- buf, buf_len));
- n |= (replace_string(buf, CoS == 'C' ? "[dd]" : "[DD]", format_int("%02d", tms->tm_mday), buf,
- buf_len));
- if (n)
- {
- // 每天检查是否需要切换文件
- expiration_t = ((((st / 3600)) + tzone_hours + 24) / 24 * 24 - tzone_hours) * 3600;
- }
- if (replace_string(buf, CoS == 'C' ? "[hh]" : "[HH]", format_int("%02d", tms->tm_hour), buf,
- buf_len))
- {
- // 每小时检查是否需要切换文件
- expiration_t = (st + 3600) / 3600 * 3600;
- }
- if (replace_string(buf, CoS == 'C' ? "[mi]" : "[MI]", format_int("%02d", tms->tm_min), buf,
- buf_len))
- {
- // 每分钟检查是否需要切换文件,主要用于测试
- expiration_t = (st + 60) / 60 * 60;
- }
- return expiration_t;
- }
- int instantiated_pattern(struct pattern_instance *pi)
- {
- time_t vt = vtime();
- time_t ct = time(0);
- if ((pi->expiration_ct >= 0 && ct >= pi->expiration_ct)
- || (pi->expiration_vt >= 0 && vt >= pi->expiration_vt))
- {
- strncpy(pi->instance, pi->pattern, pi->instance_buf_len);
- replace_string(pi->instance, "[PID]", format_int("%d", getpid()), pi->instance,
- pi->instance_buf_len);
- replace_string(pi->instance, "[pid]", format_int("%d", getpid()), pi->instance,
- pi->instance_buf_len);
- pi->expiration_ct = _replace_time_pattern(pi->instance, pi->instance_buf_len, ct, 'C');
- pi->expiration_vt = _replace_time_pattern(pi->instance, pi->instance_buf_len, vt, 'V');
- pi->instantiated_time = time(0);
- return 1;
- }
- return 0;
- }
- int lock_file(char* filename, int wait)
- {
- int lockfd = open(filename, O_RDWR | O_CREAT, 0666);
- if (lockfd)
- {
- int flock_cmd = wait ? F_SETLKW : F_SETLK;
- static struct flock flock_args;
- flock_args.l_type = F_WRLCK;
- flock_args.l_start = 0;
- flock_args.l_whence = SEEK_SET;
- flock_args.l_len = 0;
- flock_args.l_pid = getpid();
- if (fcntl(lockfd, flock_cmd, &flock_args) == 0)
- {
- return lockfd;
- }
- close(lockfd);
- }
- return 0;
- }
- int unlock_file(int lockfd)
- {
- int ret = 0;
- if (lockfd)
- {
- int flock_cmd = F_SETLK;
- static struct flock flock_args;
- flock_args.l_type = F_UNLCK;
- flock_args.l_start = 0;
- flock_args.l_whence = SEEK_SET;
- flock_args.l_len = 0;
- flock_args.l_pid = getpid();
- if (fcntl(lockfd, flock_cmd, &flock_args) == 0)
- {
- ret = 1;
- }
- close(lockfd);
- }
- return ret;
- }
- int _ablog_lock(char *dir)
- {
- int ret = 0;
- char buf[MAX_LINE_BUFFER_LENGTH];
- char lock_filename[MAX_FILEPATH_LENGTH];
- sprintf(lock_filename, "%s%s", dir, ".lock");
- int ablog_lockfd = lock_file(lock_filename, 0);
- if (ablog_lockfd)
- {
- memset(buf, 0, sizeof(buf));
- read(ablog_lockfd, buf, sizeof(buf));
- time_t t = parse_time(buf, NULL);
- if (t < time(0))
- {
- strcpy(buf, time_string(time(0) + 60));
- lseek(ablog_lockfd, 0, SEEK_SET);
- write(ablog_lockfd, buf, strlen(buf));
- ret = 1;
- }
- unlock_file(ablog_lockfd);
- }
- else
- {
- log_println("ABLOG_FILE", __FILE__, __LINE__, "lock file[%s] failed.", lock_filename);
- }
- return ret;
- }
- int _ablog_rm_old_files(char *dir, time_t time_before)
- {
- if (!_ablog_lock(dir))
- {
- return -1;
- }
- DIR *od = opendir(dir);
- if (od == NULL)
- {
- return -1;
- }
- char file[MAX_FILEPATH_LENGTH];
- struct stat file_stat;
- struct dirent *ent;
- int n = 0;
- while ((ent = readdir(od)) != NULL)
- {
- if (ent->d_name[0] != '.')
- {
- sprintf(file, "%s%s", dir, ent->d_name);
- stat(file, &file_stat);
- //printf("%32s %s ", namelist[i]->d_name, time_string(file_stat.st_mtime));
- if (S_ISREG(file_stat.st_mode) && file_stat.st_mtime < time_before)
- {
- remove(file);
- n++;
- log_println("ABLOG_FILE", __FILE__, __LINE__, "remove old log file: %s", file);
- }
- //printf("\n");
- }
- }
- closedir(od);
- log_println("ABLOG_FILE", __FILE__, __LINE__, "%d old log files removed", n);
- return n;
- }
- int remove_old_log_files(time_t time_before)
- {
- char buf[MAX_FILEPATH_LENGTH];
- strcpy(buf, ablog_filename.instance);
- char *c = buf + strlen(buf) - 1;
- while (*c != '/' && c >= buf)
- {
- *c = '\0';
- --c;
- }
- if (buf[0] == 0)
- {
- strcpy(buf, "./");
- }
- return _ablog_rm_old_files(buf, time_before);
- }
- void _ablog_set_log_file()
- {
- if (instantiated_pattern(&ablog_filename))
- {
- if (ablog_file)
- {
- fclose(ablog_file);
- }
- ablog_file = fopen(ablog_filename.instance, "a");
- if (!ablog_file)
- {
- ablog_stdout = 1;
- log_println("ABLOG_FILE", __FILE__, __LINE__, "File append error, '%s'",
- ablog_filename.instance);
- }
- else
- {
- log_println("ABLOG_FILE", __FILE__, __LINE__, "%s", ablog_filename.instance);
- }
- if (on_ablog_reinitialized)
- {
- on_ablog_reinitialized();
- }
- remove_old_log_files(time(0) - ablog_keep_hours * 3600);
- }
- }
- void mc_print_log(long mtc, char *info, char* file, int line)
- {
- log_println("MEMORY_CHECK", file, line, "malloc %ld, %s", mtc, info);
- }
- static int ablog_level_setting = 0;
- #define CHECK_ABLOG_CLASS(N) (strcasecmp(#N,buf)==0)?LPL_##N
- #define SHOW_ABLOG_CLASS(N) (ablog_level & LPL_##N)?#N
- int get_log_print_level()
- {
- if (ablog_level == -1)
- {
- init_coding();
- parse_int(getenv("ABLOG_KEEP_HOURS"), &ablog_keep_hours, ablog_keep_hours);
- parse_int(getenv("ABLOG_STDOUT"), &ablog_stdout, ablog_stdout);
- char* sf = getenv("ABLOG_FILE");
- if (sf)
- {
- strncpy(ablog_filename.pattern, sf, MAX_FILEPATH_LENGTH);
- }
- _ablog_set_log_file();
- // 重定向内存检查输出
- mc_print = mc_print_log;
- char buf[32];
- char* lpls = getenv("ABLOG_CLASS");
- if (lpls)
- {
- ablog_level = 0;
- while (*lpls)
- {
- buf[0] = 0;
- lpls = split_string_next(lpls, ',', buf, sizeof(buf));
- 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;
- if (n != 0)
- {
- log_println("ABLOG_CLASS", __FILE__, __LINE__,
- "configured ablog class #%02X %s", n, buf);
- ablog_level |= n;
- }
- }
- }
- if (vt_offset != 0)
- {
- log_println("VIRTUAL_TIME", __FILE__, __LINE__, "configured virtual time [%s]",
- time_string(vtime()));
- }
- ablog_level_setting = ablog_level;
- }
- return debug_current_process() ? LPL_All : ablog_level_setting;
- }
- /**
- * 输出一行日志信息
- */
- void log_println(const char *func, const char *file, int line, const char *format, ...)
- {
- char sb[MAX_LINE_BUFFER_LENGTH];
- va_list vl;
- va_start(vl, format);
- int cnt = vsnprintf(sb, sizeof(sb), format, vl);
- if (cnt < 0)
- {
- printf("log error!");
- }
- va_end(vl);
- struct timeval tv;
- gettimeofday(&tv, NULL);
- _ablog_set_log_file();
- char buf[MAX_LINE_BUFFER_LENGTH];
- snprintf(buf, MAX_LINE_BUFFER_LENGTH, "%s.%03ld[%s]:%s (%s,%d)\r\n", time_string(tv.tv_sec),
- (tv.tv_usec / 1000l), func, sb, file, line);
- pthread_mutex_lock(&thread_mut);
- if (ablog_file)
- {
- fprintf(ablog_file, "%s", buf);
- fflush(ablog_file);
- }
- if (ablog_stdout)
- {
- printf("%d %s", getpid(), buf);
- fflush(stdout);
- }
- pthread_mutex_unlock(&thread_mut);
- }
- void log_println_vl(const char *func, const char *file, int line, const char *format, va_list vl ) {
- struct timeval tv;
- gettimeofday(&tv, NULL);
- _ablog_set_log_file();
- pthread_mutex_lock(&thread_mut);
- if (ablog_file)
- {
- fprintf(ablog_file, "%s.%03ld[%s]:", time_string(tv.tv_sec), (tv.tv_usec / 1000l), func);
- vfprintf(ablog_file, format, vl);
- fprintf(ablog_file, " (%s,%d)\n", file, line);
- fflush(ablog_file);
- }
- if (ablog_stdout)
- {
- printf("%d %s.%03ld[%s]:", getpid(), time_string(tv.tv_sec), (tv.tv_usec / 1000l), func);
- vfprintf(stdout, format, vl);
- printf(" (%s,%d)\n", file, line);
- fflush(stdout);
- }
- pthread_mutex_unlock(&thread_mut);
- }
- /**
- * 解析十六进制数
- * 解析结果通过输出参数o返回
- * 解析失败返回0,解析成功返回非0
- */
- int parse_hex(char* s, int*o, int default_value)
- {
- int x = 0;
- int i = 0;
- int n = 0;
- int c, t;
- *o = default_value;
- if (s)
- {
- for (; isspace((int) s[i]); i++)
- ;
- if (s[i] == 'h' || s[i] == 'H' || s[i] == 'x' || s[i] == 'X')
- {
- i++;
- }
- else if (s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X'))
- {
- i += 2;
- }
- for (; (c = s[i]) != 0 && !isspace((int) c); i++, n++)
- {
- t = c >= '0' && c <= '9' ? (c - '0') : c >= 'A' && c <= 'F' ? (c - 'A' + 10) :
- c >= 'a' && c <= 'f' ? (c - 'a' + 10) : -1;
- if (t == -1)
- {
- return 0;
- }
- x <<= 4;
- x |= t;
- }
- for (; isspace((int) s[i]); i++)
- ;
- if (s[i] != 0 || n == 0)
- {
- return 0;
- }
- *o = x;
- }
- return n;
- }
- /**
- * 解析十进制数
- * 解析结果通过输出参数o返回
- * 解析失败返回0,解析成功返回非0
- */
- int parse_int(char* s, int*o, int default_value)
- {
- int x = 0;
- int i = 0;
- int n = 0;
- int c, t;
- *o = default_value;
- if (s)
- {
- for (; isspace((int) s[i]); i++)
- ;
- for (; (c = s[i]) != 0; i++, n++)
- {
- t = c >= '0' && c <= '9' ? (c - '0') : -1;
- if (t == -1)
- {
- return 0;
- }
- x = x * 10 + t;
- }
- for (; isspace((int) s[i]); i++)
- ;
- if (s[i] != 0 || n == 0)
- {
- return 0;
- }
- *o = x;
- }
- return n;
- }
- /**
- * 解析十进制数
- * 解析结果通过输出参数o返回
- * 解析失败返回0,解析成功返回非0
- */
- int parse_double(char* s, double*o, double default_value)
- {
- int signal = 1;
- double x = 0;
- double t = 0;
- int i = 0;
- int n = 0;
- int c;
- *o = default_value;
- if (s)
- {
- for (; isspace((int) s[i]); i++)
- ;
- if ((c = s[i]) == '-' || c == '+')
- {
- signal = c == '-' ? -1 : 1;
- i++;
- }
- for (; (c = s[i]) >= '0' && c <= '9'; i++, n++)
- {
- x = x * 10 + (c - '0');
- }
- if ((c = s[i]) == '.')
- {
- i++;
- t = 1;
- for (; (c = s[i]) >= '0' && c <= '9'; i++, n++)
- {
- t /= 10;
- x = x + t * (c - '0');
- }
- }
- for (; isspace((int) s[i]); i++)
- ;
- if (s[i] != 0 || n == 0)
- {
- return 0;
- }
- *o = signal * x;
- }
- return n;
- }
- /**
- * 格式化数字字符串
- */
- static char int_string_buffer[20][100];
- static int int_string_buffer_i = 0;
- char* format_int(char* format, int n)
- {
- int_string_buffer_i++;
- if (int_string_buffer_i >= 20)
- {
- int_string_buffer_i = 0;
- }
- sprintf(int_string_buffer[int_string_buffer_i], format, n);
- return int_string_buffer[int_string_buffer_i];
- }
- char* format_long(char* format, long n)
- {
- int_string_buffer_i++;
- if (int_string_buffer_i >= 20)
- {
- int_string_buffer_i = 0;
- }
- sprintf(int_string_buffer[int_string_buffer_i], format, n);
- return int_string_buffer[int_string_buffer_i];
- }
- char* format_double(char* format, double n)
- {
- int_string_buffer_i++;
- if (int_string_buffer_i >= 20)
- {
- int_string_buffer_i = 0;
- }
- sprintf(int_string_buffer[int_string_buffer_i], format, n);
- return int_string_buffer[int_string_buffer_i];
- }
- char* int_string(int n)
- {
- return format_int("%d", n);
- }
- /**
- * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串
- * 返回标准时间秒数,毫秒值通过输出参数ms返回
- * 解析失败返回 0
- */
- time_t parse_time(char *stime, long *ms)
- {
- if (stime == NULL || stime[0] == 0)
- {
- return 0;
- }
- char *c = stime;
- while ((isspace((int) *c)))
- {
- c++;
- }
- if (*c == 0)
- {
- return 0;
- }
- char timestr[25];
- strncpy(timestr, c, 24);
- struct tm tm;
- memset(&tm, 0, sizeof(tm));
- int rms = 0;
- sscanf(timestr, "%d-%d-%d %d:%d:%d.%d", &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour,
- &tm.tm_min, &tm.tm_sec, &rms);
- if (ms != NULL)
- {
- *ms = rms;
- }
- tm.tm_year -= 1900;
- tm.tm_mon -= 1;
- tm.tm_isdst = 0;
- time_t time_t = mktime(&tm);
- return time_t;
- }
- /**
- * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串
- * 返回timeval形式
- */
- struct timeval parse_time_tv(char *stime)
- {
- struct timeval tv;
- tv.tv_usec = 0;
- tv.tv_sec = parse_time(stime, &(tv.tv_usec));
- tv.tv_usec *= 1000;
- return tv;
- }
- /**
- * 解析格式为 yyyy-MM-dd HH:mm:ss[.SSS] 的时间字符串
- * 返回标准时间毫秒数
- */
- long parse_time_lms(char *stime)
- {
- long ms = 0;
- long lms = 1000L * parse_time(stime, &ms);
- return lms + ms;
- }
- /**
- * 格式化时间字符串
- * 返回格式为 yyyy-MM-dd HH:mm:ss的时间字符串
- */
- static char time_string_buffer[20][25];
- static int time_string_buffer_i = 0;
- char* time_string(time_t seconds)
- {
- time_string_buffer_i++;
- if (time_string_buffer_i >= 20)
- {
- time_string_buffer_i = 0;
- }
- struct tm *tmp = localtime(&seconds);
- tmp->tm_year = tmp->tm_year + 1900;
- tmp->tm_mon = tmp->tm_mon + 1;
- sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d", tmp->tm_year,
- tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec);
- return time_string_buffer[time_string_buffer_i];
- }
- /**
- * 格式化时间字符串
- * 返回格式为 yyyy-MM-dd HH:mm:ss.SSS的时间字符串
- */
- char* time_tv_string(struct timeval tv)
- {
- time_string_buffer_i++;
- if (time_string_buffer_i >= 20)
- {
- time_string_buffer_i = 0;
- }
- time_t seconds = tv.tv_sec;
- int dms = (int) (tv.tv_usec / 1000);
- struct tm *tmp = localtime(&seconds);
- tmp->tm_year = tmp->tm_year + 1900;
- tmp->tm_mon = tmp->tm_mon + 1;
- sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d.%03d",
- tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, dms);
- return time_string_buffer[time_string_buffer_i];
- }
- /**
- * 格式化时间字符串
- * 返回格式为 yyyy-MM-dd HH:mm:ss.SSS的时间字符串
- */
- char* time_lms_string(time_long milliseconds)
- {
- time_string_buffer_i++;
- if (time_string_buffer_i >= 20)
- {
- time_string_buffer_i = 0;
- }
- time_t seconds = milliseconds / 1000;
- int dms = (int) (milliseconds % 1000);
- struct tm *tmp = localtime(&seconds);
- tmp->tm_year = tmp->tm_year + 1900;
- tmp->tm_mon = tmp->tm_mon + 1;
- sprintf(time_string_buffer[time_string_buffer_i], "%4d-%02d-%02d %02d:%02d:%02d.%03d",
- tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, dms);
- return time_string_buffer[time_string_buffer_i];
- }
- /**
- * MUST recv_buf length >= strlen(source) + 1
- */
- char** split_string(char* source, char split_char, char*recv_buf, int recv_buf_bytes,
- char**recv_buf_array, int recv_buf_array_size)
- {
- ABLOG_Entry(Public, split_string);
- int iout = 0;
- int n = 0;
- char *recv;
- char *scur = NULL;
- char *snext = source;
- while (*snext)
- {
- scur = snext;
- recv_buf_array[iout] = recv_buf;
- recv = recv_buf;
- iout++;
- if (iout >= recv_buf_array_size)
- {
- split_char = 0;
- snext += strlen(scur);
- }
- else
- {
- snext = split_string_next(scur, split_char, recv, recv_buf_bytes);
- }
- n = snext - scur;
- recv_buf_bytes -= n;
- if (recv_buf_bytes <= 0)
- {
- ABLOG_(Error, "[W] substring[%d] is too long, length[%d], %s...", iout, n, recv);
- }
- recv_buf += n;
- }
- while (iout < recv_buf_array_size)
- {
- recv_buf_array[iout] = 0;
- iout++;
- }
- ABLOG_Return
- (recv_buf_array);
- }
- /**
- * 分割字符串 source
- * 按指定字符 split_char 分割
- * 通过 recv_buf 接收分割出来的字符串
- * 接收缓冲区长度 recv_buf_len
- * 返回下一分割段的起始位置,没有下一段时*source应该为0;
- */
- char* split_string_next(char* source, char split_char, char* recv_buf, int recv_buf_len)
- {
- char c;
- int n = 0;
- while ((c = *source) && c != split_char)
- {
- if (n < recv_buf_len - 1)
- {
- *recv_buf = c;
- recv_buf++;
- }
- source++;
- n++;
- }
- *recv_buf = 0;
- if (split_char != 0 && c == split_char)
- {
- source++;
- }
- return source;
- }
- int replace_string(char* source, char* find, char* replace, char* recv_buf, int recv_buf_len)
- {
- int n = 0;
- // 原字符串
- char* temp_buf = 0;
- if (source == recv_buf)
- {
- temp_buf = (char*) malloc(strlen(source) + 1);
- strcpy(temp_buf, source);
- source = temp_buf;
- }
- int rbfl = recv_buf_len;
- // 开始替换
- char *found = strstr(source, find);
- if (rbfl > 0 && found)
- {
- int snfl = strlen(find);
- int snrl = strlen(replace);
- do
- {
- int cpyn = (found - source);
- if (cpyn >= 0)
- {
- cpyn = cpyn < rbfl ? cpyn : rbfl;
- memcpy(recv_buf, source, cpyn);
- source = found + snfl;
- recv_buf += cpyn;
- rbfl -= cpyn;
- }
- if (rbfl > 0)
- {
- cpyn = snrl < rbfl ? snrl : rbfl;
- memcpy(recv_buf, replace, cpyn);
- recv_buf += cpyn;
- rbfl -= cpyn;
- }
- found = strstr(source, find);
- n++;
- } while (rbfl > 0 && found);
- }
- if (rbfl > 0)
- {
- strncpy(recv_buf, source, rbfl);
- }
- if (temp_buf)
- {
- free(temp_buf);
- }
- return n;
- }
- char* toUpperCase(const char *str, char *rbuf)
- {
- for (; *str; str++, rbuf++)
- {
- *rbuf = toupper((int)*str);
- }
- *rbuf = 0;
- return rbuf;
- }
- char* trimRight(const char *str, char *rbuf)
- {
- char *c = (char*) str;
- if (rbuf == 0)
- {
- rbuf = c;
- }
- c += strlen(str) - 1;
- while (isspace((int)*c) && c >= str)
- {
- --c;
- }
- if (c < str)
- {
- rbuf[0] = 0;
- }
- else
- {
- memcpy(rbuf, str, c - str + 1);
- rbuf[c - str + 1] = 0;
- }
- return rbuf;
- }
- char* trimLeft(const char *str, char *rbuf)
- {
- char *c = (char*) str;
- if (rbuf == 0)
- {
- rbuf = c;
- }
- while ((isspace((int)*c)) != 0)
- {
- c++;
- }
- strcpy(rbuf, c);
- return rbuf;
- }
- char* trim(const char *str, char *rbuf)
- {
- if (rbuf == 0)
- {
- rbuf = (char*) str;
- }
- trimLeft(str, rbuf);
- trimRight(rbuf, rbuf);
- return rbuf;
- }
- long read_mapping_file(int fd)
- {
- ABLOG_Entry(Public, read_mapping_file);
- long ret_map_id = new_mapping();
- int flen = lseek(fd, 0, SEEK_END);
- char *buf = MALLOC(flen + 1);
- memset(buf, 0, flen + 1);
- lseek(fd, 0, SEEK_SET);
- read(fd, buf, flen);
- char *line_buffer = buf;
- while (line_buffer[0])
- {
- char* newline = strstr(line_buffer, "\n");
- if (newline)
- {
- newline[0] = 0;
- }
- trimLeft(line_buffer, 0);
- if (line_buffer[0] != '#' && strlen(line_buffer) > 0)
- {
- char *kv[2];
- split_string(line_buffer, '=', line_buffer, flen + 1, kv, 2);
- char* key = trim(kv[0], 0);
- char* value = trim(kv[1], 0);
- ABLOG_Printf(Detail, (ABLOG, "[D] %s=%s", key, value));
- put_string_mapping(ret_map_id, key, value);
- }
- line_buffer = newline ? newline + 1 : 0;
- }
- FREE(buf);
- ABLOG_Return_Long(ret_map_id);
- }
- int write_mapping_file(int fd, long mid)
- {
- ABLOG_Entry(Public, read_mapping_file);
- MapEntry me = items_mapping(mid);
- lseek(fd, 0, SEEK_SET);
- ftruncate(fd, 0);
- while (me)
- {
- write(fd, me->key, strlen(me->key));
- write(fd, "=", 1);
- write(fd, me->value, strlen(me->value));
- write(fd, "\r\n", 2);
- me = me->next;
- }
- ABLOG_Return_Int(lseek(fd, 0, SEEK_END));
- }
|