前面我们介绍了Skywalking php如何安装的,这篇文章我们来分析Skywalking php是如何实现拦截的。

一、OpenTracing
在分析代码之前,我们先了解下OpenTracing规范,OpenTracing规范用来解决分布式追踪规范问题,这样保证不管用什么样的语言开发,只要遵守规范,你写的程序就可以被追踪,这里不准备讲太多这方面的理论,有兴趣的同学可以百度下。
Skywalking Php也是遵守OpenTracking规范实现的,我们贴一个实际的例子:
假如有以下PHP代码
$redis = new Redis();$redis->connect('127.0.0.1', 6379);$redis->get('ok');
产生的追踪数据如下:
{"application_instance": 207,"pid": 1639,"application_id": 4,"version": 6,"uuid": "bc12912e-1791-47b9-abe2-4dabda363d4a","segment": {"traceSegmentId": "3062_15767727610001","isSizeLimited": 0,"spans": [{"spanId": 0,"parentSpanId": -1,"startTime": 1576772761044,"operationName": "cli","peer": "","spanType": 0,"spanLayer": 3,"componentId": 2,"refs": [],"endTime": 1576772761062,"isError": 0}, {"spanId": 1,"parentSpanId": 0,"startTime": 1576772761059,"spanType": 1,"spanLayer": 5,"tags": [{"key": "db.type","value": "Redis"}, {"key": "db.statement","value": ""}],"componentId": 30,"endTime": 1576772761061,"operationName": "connect","peer": "127.0.0.1:6379","isError": 0,"refs": []}, {"spanId": 2,"parentSpanId": 0,"startTime": 1576772761061,"spanType": 1,"spanLayer": 5,"tags": [{"key": "db.type","value": "Redis"}, {"key": "db.statement","value": "get ok"}],"componentId": 30,"endTime": 1576772761061,"operationName": "get","peer": "127.0.0.1:6379","isError": 0,"refs": []}]},"globalTraceIds": ["3062_15767727610001"]}
其中有对Redis的connect和get操作的拦截。
二、关键代码分析
1、初始化
任意一个PHP扩展都有模块启动函数、请求启动/关闭函数,我们可以先从这里分析入手。
先看模块启动函数:
PHP_MINIT_FUNCTION (skywalking) {ZEND_INIT_MODULE_GLOBALS(skywalking, php_skywalking_init_globals, NULL);//data_register_hashtable();REGISTER_INI_ENTRIES();/* If you have INI entries, uncomment these lines*/if (SKYWALKING_G(enable)) {//Cli模式下不做处理if (strcasecmp("cli", sapi_module.name) == 0 && cli_debug == 0) {return SUCCESS;}//拦截用户执行函数ori_execute_ex = zend_execute_ex;zend_execute_ex = sky_execute_ex;//拦截内部执行函数ori_execute_internal = zend_execute_internal;zend_execute_internal = sky_execute_internal;// 拦截 curlzend_function *old_function;if ((old_function = zend_hash_str_find_ptr(CG(function_table), "curl_exec", sizeof("curl_exec") - 1)) != NULL) {orig_curl_exec = old_function->internal_function.handler;old_function->internal_function.handler = sky_curl_exec_handler;}if ((old_function = zend_hash_str_find_ptr(CG(function_table), "curl_setopt", sizeof("curl_setopt")-1)) != NULL) {orig_curl_setopt = old_function->internal_function.handler;old_function->internal_function.handler = sky_curl_setopt_handler;}if ((old_function = zend_hash_str_find_ptr(CG(function_table), "curl_setopt_array", sizeof("curl_setopt_array")-1)) != NULL) {orig_curl_setopt_array = old_function->internal_function.handler;old_function->internal_function.handler = sky_curl_setopt_array_handler;}if ((old_function = zend_hash_str_find_ptr(CG(function_table), "curl_close", sizeof("curl_close")-1)) != NULL) {orig_curl_close = old_function->internal_function.handler;old_function->internal_function.handler = sky_curl_close_handler;}}return SUCCESS;}/* }}} */
模块大概做了2件事:
1)、拦截函数执行
//拦截用户执行函数ori_execute_ex = zend_execute_ex;zend_execute_ex = sky_execute_ex;//拦截内部执行函数ori_execute_internal = zend_execute_internal;zend_execute_internal = sky_execute_internal;
PHP函数分2种,一个是用户态函数,即.php文件中的函数,这些是通过zend_execute_ex来执行;另一种就是内部函数,即PHP扩展编写的函数,这个会通过zend_execute_internal来执行。
而这两个都是函数指针,允许各模块自己去拦截,这样Skywalking就可以拦截所有函数的调用了。
2)、拦截curl的调用
zend_function *old_function;if ((old_function = zend_hash_str_find_ptr(CG(function_table), "curl_exec", sizeof("curl_exec") - 1)) != NULL) {orig_curl_exec = old_function->internal_function.handler;old_function->internal_function.handler = sky_curl_exec_handler;}
这里只讲一个函数:curl_exec,先查找函数表中这函数,将其保存下来,便于做了统计信息后再执行原有逻辑,然后动态的替换成自己的实现。
我们再来看sky_curl_exec_handler的实现逻辑。
这里的代码就比较细了,大概思路是:得到当前执行的一些参数
,然后按格式组装OpenTracing规范数据。
zval function_name,curlInfo;zval params[1];ZVAL_COPY(¶ms[0], zid);ZVAL_STRING(&function_name, "curl_getinfo");call_user_function(CG(function_table), NULL, &function_name, &curlInfo, 1, params);zval_dtor(&function_name);zval_dtor(¶ms[0]);//得到url信息zval *z_url = zend_hash_str_find(Z_ARRVAL(curlInfo), ZEND_STRL("url"));char *url_str = Z_STRVAL_P(z_url);if(strlen(url_str) <= 0) {zval_dtor(&curlInfo);is_send = 0;}php_url *url_info = NULL;if(is_send == 1) {url_info = php_url_parse(url_str);if(url_info->scheme == NULL || url_info->host == NULL) {zval_dtor(&curlInfo);php_url_free(url_info);is_send = 0;}}
接下来是按OpenTraceing规范组装数据:
if(is_send == 1) {array_init(&temp);add_assoc_long(&temp, "spanId", Z_LVAL_P(span_id) + 1);add_assoc_long(&temp, "parentSpanId", 0);l_millisecond = get_millisecond();millisecond = zend_atol(l_millisecond, strlen(l_millisecond));efree(l_millisecond);add_assoc_long(&temp, "startTime", millisecond);add_assoc_long(&temp, "spanType", 1);add_assoc_long(&temp, "spanLayer", 3);add_assoc_long(&temp, "componentId", COMPONENT_HTTPCLIENT);}
然后是执行原来的逻辑:
orig_curl_exec(INTERNAL_FUNCTION_PARAM_PASSTHRU);
2、sky_execute_ex的实现。
先得到类和函数的信息:
zend_function *zf = execute_data->func;const char *class_name = (zf->common.scope != NULL && zf->common.scope->name != NULL) ? ZSTR_VAL(zf->common.scope->name) : NULL;const char *function_name = zf->common.function_name == NULL ? NULL : ZSTR_VAL(zf->common.function_name);`然后是根据不同的类拦截不同的方法了:` if (class_name != NULL) {if (strcmp(class_name, "Predis\\Client") == 0 && strcmp(function_name, "executeCommand") == 0) {// paramsuint32_t arg_count = ZEND_CALL_NUM_ARGS(execute_data);if (arg_count) {zval *p = ZEND_CALL_ARG(execute_data, 1);zval *id = (zval *) emalloc(sizeof(zval));zend_call_method(p, Z_OBJCE_P(p), NULL, ZEND_STRL("getid"), id, 0, NULL, NULL);if (Z_TYPE_P(id) == IS_STRING) {operationName = (char *) emalloc(strlen(class_name) + strlen(Z_STRVAL_P(id)) + 3);componentId = COMPONENT_JEDIS;strcpy(operationName, class_name);strcat(operationName, "->");strcat(operationName, Z_STRVAL_P(id));}efree(id);}……
三、总结
Skywalking Php的模块启动的时候替换了PHP函数执行的几个函数指针,然后判断是否自己关心的几个类,像Predis,如果是就进行拦截;
Skywaling Php还对Curl进行拦截,不过这个是在模块启动的时候就拦截了,后面每个请求进来是不会变化的。
为什么拦截Curl模块只要在模块启动时一次拦截就行,而其它函数需要拦截执行函数这种动态方式?因为其它的一些类是在PHP脚本中,在模块加载的时候可能还没加载进来,所有不能静态拦截,只好进行动态拦截,每次执行一个函数时判断是不是我们关心的函数。
四、动手写代码
官方版本的skywalking是有拦截mysql和redis的功能的,但一些参数没有记录,像get命令执行的时候是获取哪个key,mysql执行哪条语句;
我们在开源的基础上做了一些定制,有兴趣同学可以关注公众号,回复skywalking 就可以下载相应的代码自己调试,redis写了个demo,拦截get的调用,可以记录是哪个key,mysql的拦截会记录执行的是哪条sql。





