百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

Skywalking Php代码分析

toyiye 2024-04-07 14:12 19 浏览 0 评论

这篇文章我们来分析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;

        // 拦截 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;
        }
        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;
        }

12

这里只讲一个函数: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) {
            // params
            uint32_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脚本中,在模块加载的时候可能还没加载进来,所以不能静态拦截,只好进行动态拦截,每次执行一个函数时判断是不是我们关心的函数。

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码