如何用Bazel构建uWSGI?关于构建规则选择的疑问
解决方案
因为uWSGI的构建是先通过Python脚本处理配置生成编译所需文件,再编译C代码,所以不能直接用单一的cc_binary或py_binary,需要结合genrule串联配置生成与编译流程,以下是具体实现步骤:
1. 完善WORKSPACE中uWSGI仓库的BUILD定义
补全new_git_repository的build_file_content,暴露uWSGI的源码、配置脚本和默认配置目录:
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") new_git_repository( name = "uwsgi", remote = "git@github.com:unbit/uwsgi.git", commit = "ca8bc6acc98b2c062b5b00668acd851e210fcbca", build_file_content = """ filegroup( name = "sources", srcs = glob(["**/*.c", "**/*.h"]), visibility = ["//visibility:public"], ) py_binary( name = "uwsgiconfig", srcs = ["uwsgiconfig.py"], visibility = ["//visibility:public"], ) filegroup( name = "buildconf", srcs = glob(["buildconf/*.ini"]), visibility = ["//visibility:public"], ) """, )
2. 项目中编写BUILD规则处理自定义配置并构建uWSGI
假设自定义配置myconf.ini放在项目根目录,创建BUILD.bazel文件,按流程实现配置复制、编译文件生成、最终二进制编译:
# 复制自定义配置到uWSGI的buildconf目录(模拟手动复制操作) genrule( name = "prepare_uwsgi_config", srcs = [ "@uwsgi//:buildconf", "myconf.ini", ], outs = ["uwsgi_buildconf/myconf.ini"], cmd = """ mkdir -p $(@D)/uwsgi_buildconf cp $(location myconf.ini) $(@D)/uwsgi_buildconf/ # 按需复制uWSGI默认配置 cp $(locations @uwsgi//:buildconf) $(@D)/uwsgi_buildconf/ """, ) # 执行uwsgiconfig.py生成编译所需的Makefile和头文件 genrule( name = "generate_uwsgi_build_files", srcs = [ "@uwsgi//:sources", "@uwsgi//:uwsgiconfig", ":prepare_uwsgi_config", ], outs = [ "uwsgi_build/uwsgi.h", "uwsgi_build/Makefile", ], cmd = """ mkdir -p $(@D)/uwsgi_build # 切换到uWSGI源码目录执行配置脚本 cd $(@D)/../external/uwsgi PYTHONPATH=. python $(location @uwsgi//:uwsgiconfig) --build myconf \ --confdir $(location :prepare_uwsgi_config)/../uwsgi_buildconf # 将生成的文件复制到Bazel输出目录 cp uwsgi.h $(@D)/uwsgi_build/ cp Makefile $(@D)/uwsgi_build/ cp *.c $(@D)/uwsgi_build/ """, ) # 编译生成最终的uWSGI二进制 cc_binary( name = "uwsgi", srcs = [ "@uwsgi//:sources", ":generate_uwsgi_build_files", ], includes = ["uwsgi_build"], # 根据配置需求添加依赖库链接选项 linkopts = [ "-lpthread", "-lz", "-ldl", ], )
3. 关键说明
genrule用于模拟手动操作流程:第一个负责配置文件复制,第二个调用Python脚本生成编译资源。- 沙盒环境中需用
$(location)获取文件绝对路径,确保脚本能正确找到依赖文件。 - 链接选项需根据你的uWSGI配置调整,比如启用Python支持时需添加Python库链接参数。
内容的提问来源于stack exchange,提问作者legend855
相关产品推荐
相关产品推荐

