如何为手机号创建UDF实现中间四位*掩码?

解读

国内面试中,手机号脱敏是数据安全合规的硬需求。ClickHouse 原生没有 maskPhone() 函数,因此需要候选人现场给出可编译、可注册、可下推的 UDF 方案。面试官重点考察三点:

  1. 是否熟悉 ClickHouse UDF 的两种形态(SQL lambda 与可执行文件)。
  2. 能否保证分布式环境下每个分片都能调用到同一份逻辑(注册路径、文件同步、HDFS 依赖)。
  3. 性能与安全性:正则回溯、内存拷贝、异常输入(非11位、带86前缀、NULL)是否处理。

知识点

  1. SQL lambda UDF(20.9+):通过 CREATE FUNCTION 语句注册,语法简单,但只能做纯表达式计算,无法做复杂分支。
  2. 可执行文件 UDF(20.3+):用 C++/Rust/Go 写一个小程序,ClickHouse 通过 stdin/stdout 与之交互,支持复杂逻辑,可随配置自动分发到各分片。
  3. 字符编码:中国大陆手机号 11 位,GBK/UTF-8 均按字节截断会踩坑,必须按字符处理。
  4. Nullable 处理:手机号字段可能是 Nullable(String),UDF 入参需声明为 String 并配合 ifNull(),否则内部抛异常会导致整条 SQL 失败。
  5. 分布式一致性:config 里 <user_defined_executable_functions_config> 指向的 XML 必须同步到所有节点;若用 HDFS 存储二进制,需保证 hdfs://user/clickhouse/udfs/mask_phone 权限 755、副本数≥3。
  6. 性能:向量化执行一次调用的批次可达 65536 行,C++ 实现需零拷贝(直接读 stdin 的 buffer,避免逐行 new string)。

答案

给出生产级可执行文件方案,三步落地:

  1. 编写 mask_phone.cc(C++17)
#include <iostream>
#include <string>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    string line;
    while (getline(cin, line)) {
        if (line.size() == 11 && line.find_first_not_of("0123456789") == string::npos)
            cout << line.substr(0,3) + "****" + line.substr(7) << '\n';
        else
            cout << line << '\n';   // 原样返回,避免脏数据抛异常
    }
    return 0;
}

编译:

g++ -O3 -std=c++17 mask_phone.cc -o mask_phone
chmod 755 mask_phone

放到所有分片的同一路径,例如 /opt/clickhouse/udfs/mask_phone。

  1. 创建函数描述文件 /etc/clickhouse-server/mask_phone.xml
<functions>
    <function>
        <type>executable</type>
        <name>mask_phone</name>
        <return_type>String</return_type>
        <argument>
            <type>String</type>
            <name>phone</name>
        </argument>
        <format>tab_separated</format>
        <command>/opt/clickhouse/udfs/mask_phone</command>
        <execute_direct>1</execute_direct>
    </function>
</functions>

在 config.xml 追加:

<user_defined_executable_functions_config>/etc/clickhouse-server/mask_phone.xml</user_defined_executable_functions_config>

滚动重启实例(无需全集群同时停,可逐节点灰度)。

  1. 使用
SELECT mask_phone(phone) AS safe_phone
FROM user_event
WHERE event_date = today();

支持向量化、并行、分布式自动下推,性能与内置函数几乎无差异。

拓展思考

  1. SQL lambda 快速验证:若现场不允许上传二进制,可先用 lambda 兜底:
CREATE FUNCTION mask_phone_lambda ON CLUSTER '{cluster}' AS (phone) ->
    if(length(phone)=11 and match(phone,'^1[3-9]\\d{9}$'),
       concat(substring(phone,1,3),'****',substring(phone,8)),
       phone);

面试官会追问“lambda 的缺点”——无法处理异常编码、无法做指令级优化、在高并发大宽表场景 CPU 比 C++ 版本高 30%+。

  1. 安全加固:

    • 在 UDF 内部再加白名单校验(号段库),防止虚拟运营商新号段误判。
    • 通过 chmod 550 + setfacl 限制只有 clickhouse 用户可执行,防止提权。
  2. 热升级:
    二进制替换后,执行 SYSTEM RELOAD FUNCTIONS; 即可秒级生效,无需重启节点;灰度方案可结合 ZooKeeper 版本号做滚动校验。