mysql5.5的audit审计功能是被自动触发的,在文件plugin_audit.h中可以看到比较详细的定义
在audit插件中,可控制的变量包括THD以及事件
其中事件分为两种结构体,可以进行强制转换:
第一种:
48 struct mysql_event_general 49 { 50 unsigned int event_subclass; 51 int general_error_code; 52 unsigned long general_thread_id; 53 const char *general_user; 54 unsigned int general_user_length; 55 const char *general_command; 56 unsigned int general_command_length; 57 const char *general_query; 58 unsigned int general_query_length; 59 struct charset_info_st *general_charset; 60 unsigned long long general_time; 61 unsigned long long general_rows; 62 };触发条件:
#define MYSQL_AUDIT_GENERAL_LOG 0
在提交给general query log之前被触发
#define MYSQL_AUDIT_GENERAL_ERROR 1
在发送给用户错误之前触发
#define MYSQL_AUDIT_GENERAL_RESULT 2
当将结果集合发送给用户后触发
#define MYSQL_AUDIT_GENERAL_STATUS 3
当发送一个结果集或发生错误时被触发
第二种: 79 struct mysql_event_connection 80 { 81 unsigned int event_subclass; 82 int status; 83 unsigned long thread_id; 84 const char *user; 85 unsigned int user_length; 86 const char *priv_user; 87 unsigned int priv_user_length; 88 const char *external_user; 89 unsigned int external_user_length; 90 const char *proxy_user; 91 unsigned int proxy_user_length; 92 const char *host; 93 unsigned int host_length; 94 const char *ip; 95 unsigned int ip_length; 96 const char *database; 97 unsigned int database_length; 98 };
触发条件:
#define MYSQL_AUDIT_CONNECTION_CONNECT 0
完成认证后触发
#define MYSQL_AUDIT_CONNECTION_DISCONNECT 1
连接被中断时触发
#define MYSQL_AUDIT_CONNECTION_CHANGE_USER 2
在执行COM_CHANGE_USER命令后触发
从上面的分析,我们可以看出,在event中存储了相当丰富的信息,将notify函数进行了如下简单的修改:
91 static void audit_null_notify(MYSQL_THD thd __attribute__((unused)), 92 unsigned int event_class, 93 const void *event) 94 { 95 const struct mysql_event_general *pEvent; 96 97 if (log_fp == NULL) 98 log_fp = fopen("/tmp/rec.log", "a"); 99 number_of_calls++; 100 101 if (event_class == MYSQL_AUDIT_GENERAL_CLASS && log_fp != NULL){ 102 pEvent = (const struct mysql_event_general *) event; 103 104 if ( pEvent->event_subclass == MYSQL_AUDIT_GENERAL_RESULT && 105 pEvent->general_query != NULL 106 && *(pEvent->general_query) != '\0') { 107 // fprintf(log_fp, "user:%s,host:%s,command:%s\n",&thd->security_ctx->priv_user[0], 108 // (char *) thd->security_ctx->host_or_ip , 109 // pEvent->general_query); 110 111 time_t cur = time(NULL); 112 113 fprintf(log_fp, "%s %s\n%s\n", ctime(&cur) , pEvent->general_user , pEvent->general_query); 114 fflush(log_fp); 115 } 116 } 117 }