惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
Intezer
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
H
Heimdal Security Blog
I
InfoQ
Blog — PlanetScale
Blog — PlanetScale
Apple Machine Learning Research
Apple Machine Learning Research
Spread Privacy
Spread Privacy
腾讯CDC
大猫的无限游戏
大猫的无限游戏
Recent Announcements
Recent Announcements
V
Vulnerabilities – Threatpost
D
DataBreaches.Net
The GitHub Blog
The GitHub Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
G
Google Developers Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
J
Java Code Geeks
MyScale Blog
MyScale Blog
P
Palo Alto Networks Blog
V
Visual Studio Blog
Microsoft Azure Blog
Microsoft Azure Blog
Google Online Security Blog
Google Online Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
W
WeLiveSecurity
宝玉的分享
宝玉的分享
aimingoo的专栏
aimingoo的专栏
博客园_首页
S
Security @ Cisco Blogs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Recent Commits to openclaw:main
Recent Commits to openclaw:main
P
Privacy International News Feed
H
Hacker News: Front Page
Vercel News
Vercel News
T
Troy Hunt's Blog
Forbes - Security
Forbes - Security
N
News and Events Feed by Topic
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
U
Unit 42
Cloudbric
Cloudbric
MongoDB | Blog
MongoDB | Blog
B
Blog RSS Feed
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
Schneier on Security
Schneier on Security
Last Week in AI
Last Week in AI
H
Help Net Security
M
MIT News - Artificial intelligence
美团技术团队

Yesterday17's Blog

2026 新年解密红包 / Melody Flag | Yesterday17's Blog 谈谈 Iori 的设计思路(二):如何实现一个 Showroom 录制工具? | Yesterday17's Blog 谈谈 Iori 的设计思路(一):从 Nico Timeshift 说起 | Yesterday17's Blog Iori Minyami 0.1.0 发布 | Yesterday17's Blog 2025 新年解密红包 / Melody Flag | Yesterday17's Blog 使用 Cloudflare Warp 解决罗森票务的海外登录问题 | Yesterday17's Blog How To Blog 04: The Astro v5 Era | Yesterday17's Blog 谈谈 tokio::select! 的公平性 | Yesterday17's Blog Learning Pingora 05 - Connect with TLS | Yesterday17's Blog Leaving Bytedance | Yesterday17's Blog 大橋彩香 AsiaTour「Reflection」上海公演 个人向记录 & Repo | Yesterday17's Blog Recoving from burnout - What happened? | Yesterday17 Yubikey 重建手册 | Yesterday17's Blog How To Blog 03: Heimus | Yesterday17's Blog 🪧 Blog Migration Accouncement | Yesterday17's Blog Learn Your IDE - VSCode 是如何仅重启插件的? | Yesterday17's Blog How To Blog 02: Astro❤️Password | Yesterday17's Blog How To Blog 01: Why, How, and the Future | Yesterday17's Blog Learning Pingora 04 - Establish L4 Connection | Yesterday17's Blog Learning Pingora 03 - Upstreams and Peers | Yesterday17's Blog Learning Pingora 02 - A Simple HTTP Server | Yesterday17's Blog 2024 新年解密红包 / Melody Flag | Yesterday17's Blog 向新的一年飞驰——记录 2023 | Yesterday17's Blog 「サクラノ刻」对话选摘(2) | Yesterday17's Blog PGP Key Revocation 注销声明 | Yesterday17's Blog 「サクラノ刻」对话选摘(1) | Yesterday17's Blog 2023 新年解密红包 / Melody Flag | Yesterday17's Blog 『蒼の彼方のフォーリズム』通关感想 | Yesterday17's Blog 单显卡直通教程 | Yesterday17's Blog 对博客与笔记的思考 | Yesterday17's Blog Project Anni 之旅(3)自动化 Flutter 应用 CI/CD 上架流程 | Yesterday17's Blog AsobiStage 直接播放链接 | Yesterday17 如何在后分P时代进行投稿——sswa使用详解 | Yesterday17's Blog JSON RPC 与 LSP 协议基础 | Yesterday17's Blog Grajapa Shueisha / BookEnd 加密方式调查 | Yesterday17's Blog 【2022篇+WriteUp】如何再收一个新年红包? | Yesterday17's Blog 如何将良心云的良心功能清理干净 | Yesterday17's Blog 【油猴脚本】bilibili 投稿页面返回旧版+旧版页面强制允许分P上传 | Yesterday17's Blog Cloudr1v1 授权方式分析 | Yesterday17 Typora 1.0.2 逆向实录 | Yesterday17's Blog Project Anni 之旅(2)ValueAfterTable——toml-rs的实现与限制 | Yesterday17's Blog IPv4透明代理+IPv6 Passthrough——树莓派单臂软路由折腾记 | Yesterday17's Blog Chaos; Child 汉化补丁 神秘编码探索 | Yesterday17's Blog 镣铐与舞蹈——个性与共性之迷思 | Yesterday17's Blog Go 学习笔记 02 - 找准 io 之道 | Yesterday17's Blog NAT Slipstreaming v1 原理浅析 | Yesterday17's Blog 绕过「9-nine-」的 CDKEY 验证——KrkrPlugin 正(?)向实录 | Yesterday17's Blog 静流的青春纪念册——「サクラノ刻 -櫻の森の下を歩む-」体验版感言 | Yesterday17's Blog Project Anni 之旅 01 - 从 clap-builder 到 derive | Yesterday17's Blog [Google CTF 2021] CPP WriteUp | Yesterday17's Blog 获取 アソビステージ 的实际播放链接 | Yesterday17's Blog 90 行 Rust 代码实现 AsyncTeeReader | Yesterday17's Blog 或许还算有价值一读的文章列表 | Yesterday17's Blog 从零开始的 Seedbox 之旅 | Yesterday17's Blog [随笔]技术型博客行文迷思(1) | Yesterday17's Blog 浅谈 git fetch 的工作方式 | Yesterday17's Blog 『ソーサレス*アライヴ! ~the World's End Fallen Star~』通关感想" | Yesterday17's Blog Rust std::fmt 格式语法简述 | Yesterday17's Blog 日亚修改居住国的解决方案 | Yesterday17's Blog [Windows/Linux] GC553 的 Switch 完美采集之路 | Yesterday17's Blog 【翻译】Subtyping and Variance / 子类型与变型 | Yesterday17's Blog Berd's Red Envelope 2021 WriteUp | Yesterday17's Blog 【中英对照】ALSA 音频 API 使用教程/A Tutorial on Using the ALSA Audio API | Yesterday17's Blog 从 cue_scanner.l 看 CUE Sheet 的词法单元 | Yesterday17's Blog Postman 历史记录导出的解决方案 | Yesterday17's Blog 《恋爱绮谭 不存在的夏天》通关感想 | Yesterday17's Blog [微机实验/TD-PITE] 微机接口综合实验 | Yesterday17's Blog [微机实验/TD-PITE] 键盘扫描及数码管显示实验 | Yesterday17's Blog [微机实验/TD-PITE] 数码管显示实验 | Yesterday17's Blog Airsonic Advanced+Google Drive+Caddy 部署纪实 | Yesterday17's Blog X-NUCA 2020 - hellowasm 题解 | Yesterday17's Blog [微机实验/TD-PITE] 8251 串行接口实验 | Yesterday17's Blog Node.js child_process.fork 与 env 污染 RCE | Yesterday17's Blog EP.01 「夜の向日葵」 | Yesterday17's Blog [微机实验/TD-PITE] 8254 定时/计数器实验+选做实验 | Yesterday17's Blog [JLU CTF/2020] babywasm WriteUp | Yesterday17's Blog PHP 反序列化与经典利用 | Yesterday17's Blog WebAssembly 逆向简述 | Yesterday17's Blog 『彼女、お借りします』一期完结点评 | Yesterday17's Blog [微机实验/TD-PITE] D/A 转换实验+选做实验 | Yesterday17's Blog [微机实验/TD-PITE] A/D 转换实验+选做实验 | Yesterday17's Blog 开源项目申请 JetBrains Open Source License 简单流程 | Yesterday17's Blog 微软拼音与 JetBrains 搜索快捷键冲突的解决方案 | Yesterday17's Blog [微机实验/TD-PITE] 8259 中断优先级实验+选做实验 | Yesterday17's Blog IFTTT 测试(续) | Yesterday17 IFTTT 测试 | Yesterday17's Blog [微机实验/TD-PITE] 存储器扩展实验+选做实验 | Yesterday17's Blog 新版 GCC 针对 -fdump-translation-unit 的替代方案 | Yesterday17's Blog 一次 HSTS 策略配置的排错之旅 | Yesterday17's Blog YukiNative 踩坑记——Windows 的消息队列 | Yesterday17's Blog 我是我自己——论获取 HTTPS 证书时的验证步骤 | Yesterday17's Blog 【设计文档】对 PUG 的大规模设计修订(1.1) | Yesterday17's Blog GS65 折腾记(2)加装固态,分区,Grub2 引导 Manjaro LiveCD | Yesterday17's Blog 「さくら、もゆ。」的空白字体列表——一次逆向问题定位过程实录 | Yesterday17's Blog GSuite 探索篇(1)使用 Service Account 向 Google Drive 传输文件 | Yesterday17's Blog 『サクラノ詩 -櫻の森の上を舞う-』通关感想 | Yesterday17's Blog 《ATRI -My Dear Moments-》通关感想 | Yesterday17's Blog [工具][VSCode 扩展] AegiKit——方便 Aegisub 使用的工具箱 | Yesterday17's Blog 贝塞尔曲线、字体矢量化与曲线运算 | Yesterday17's Blog NAT 类型初探 | Yesterday17's Blog
Learning Pingora 01 - Getting Started | Yesterday17's Blog
Yesterday17 · 2024-03-30 · via Yesterday17's Blog

ToC

  • 示例代码
  • Server、Service 与 Http
  • HTTP Proxy Service
  • ServerApp 与 HttpServerApp

示例代码

让我们首先按照 Pingora 的 example 来看吧。首先是建立一个项目:

# 初始化项目

cargo init pingora-learning

cd pingora-learning

# 加入引用

cargo add pingora -F lb

cargo add async-trait

然后是照葫芦画瓢:

use async_trait::async_trait;

use pingora::prelude::*;

use std::sync::Arc;

pub struct LB(Arc<LoadBalancer<RoundRobin>>);

#[async_trait]

impl ProxyHttp for LB {

/// For this small example, we don't need context storage

type CTX = ();

fn new_ctx(&self) -> () {

()

}

async fn upstream_peer(&self, _session: &mut Session, _ctx: &mut ()) -> Result<Box<HttpPeer>> {

let upstream = self

.0

.select(b"", 256) // hash doesn't matter for round robin

.unwrap();

println!("upstream peer is: {upstream:?}");

// Set SNI to one.one.one.one

let peer = Box::new(HttpPeer::new(upstream, true, "one.one.one.one".to_string()));

Ok(peer)

}

async fn upstream_request_filter(

&self,

_session: &mut Session,

upstream_request: &mut RequestHeader,

_ctx: &mut Self::CTX,

) -> Result<()> {

upstream_request

.insert_header("Host", "one.one.one.one")

.unwrap();

Ok(())

}

}

fn main() {

let mut my_server = Server::new(None).unwrap();

my_server.bootstrap();

let upstreams = LoadBalancer::try_from_iter(["1.1.1.1:443", "1.0.0.1:443"]).unwrap();

let mut lb = http_proxy_service(&my_server.configuration, LB(Arc::new(upstreams)));

lb.add_tcp("0.0.0.0:6188");

my_server.add_service(lb);

my_server.run_forever();

}

这个案例足够简单,让我们看看 Pingora 实际是怎么操作的。

Server、Service 与 Http

让我们首先观察一下 fn main() 的实现。

在整个 main 中,贯彻始终的是 Server,也就是上面高亮的 [1][3] 部分。从 bootstrapadd_service,以及最后的 run_forever,它都是最主要的服务组成部分。而 Server 真正需要的内部逻辑,比如 example 中的 Load Balancer,则是通过 Service 的方式向 Server 注册的。

Servicepingora-core 中的定义如下:

/// The service interface

#[async_trait]

pub trait Service: Sync + Send {

/// This function will be called when the server is ready to start the service.

///

/// - `fds`: a collection of listening file descriptors. During zero downtime restart

/// the `fds` would contain the listening sockets passed from the old service, services should

/// take the sockets they need to use then. If the sockets the service looks for don't appear in

/// the collection, the service should create its own listening sockets and then put them into

/// the collection in order for them to be passed to the next server.

/// - `shutdown`: the shutdown signal this server would receive.

async fn start_service(&mut self, fds: Option<ListenFds>, mut shutdown: ShutdownWatch);

/// The name of the service, just for logging and naming the threads assigned to this service

///

/// Note that due to the limit of the underlying system, only the first 16 chars will be used

fn name(&self) -> &str;

/// The preferred number of threads to run this service

///

/// If `None`, the global setting will be used

fn threads(&self) -> Option<usize> {

None

}

}

最核心的就是 start_service 了。Service 需要负责热更新相关的事项,因此 start_service 接收了 fds 作为参数,用于在 server 更新时通过 fd 继承旧服务的 service。此外,shutdown 也可以在停止时监听并作一些移交的事项。

HTTP Proxy Service

在 example 的 47 行,我们调用了 http_proxy_service 作为我们 LB 的 Wrapper。这其实是一个 Service 初始化的快捷手段:

/// Create a [Service] from the user implemented [ProxyHttp].

///

/// The returned [Service] can be hosted by a [pingora_core::server::Server] directly.

pub fn http_proxy_service<SV>(conf: &Arc<ServerConf>, inner: SV) -> Service<HttpProxy<SV>> {

Service::new(

"Pingora HTTP Proxy Service".into(),

HttpProxy::new(inner, conf.clone()),

)

}

在内部,我们实际上是创建了一个 struct Service,并且在这个 Service 里包了一个 HttpProxystruct Service 实现了 trait Service

#[async_trait]

impl<A: ServerApp + Send + Sync + 'static> ServiceTrait for Service<A> {

24 collapsed lines

async fn start_service(&mut self, fds: Option<ListenFds>, shutdown: ShutdownWatch) {

let runtime = current_handle();

let endpoints = self.listeners.build(fds);

let handlers = endpoints.into_iter().map(|endpoint| {

let app_logic = self.app_logic.clone();

let shutdown = shutdown.clone();

runtime.spawn(async move {

Self::run_endpoint(app_logic, endpoint, shutdown).await;

})

});

futures::future::join_all(handlers).await;

self.listeners.cleanup();

self.app_logic.cleanup();

}

fn name(&self) -> &str {

&self.name

}

fn threads(&self) -> Option<usize> {

self.threads

}

}

这使得通过 http_proxy_service 构造的 HttpProxy 能作为 ServiceServer 加载。而 HttpProxy 则实现了 HttpServerApp

#[async_trait]

impl<SV> HttpServerApp for HttpProxy<SV>

where

SV: ProxyHttp + Send + Sync + 'static,

<SV as ProxyHttp>::CTX: Send + Sync,

{

async fn process_new_http(

self: &Arc<Self>,

session: HttpSession,

shutdown: &ShutdownWatch,

) -> Option<Stream> {

18 collapsed lines

let session = Box::new(session);

// TODO: keepalive pool, use stack

let mut session = match self.handle_new_request(session).await {

Some(downstream_session) => Session::new(downstream_session),

None => return None, // bad request

};

if *shutdown.borrow() {

// stop downstream from reusing if this service is shutting down soon

session.set_keepalive(None);

} else {

// default 60s

session.set_keepalive(Some(60));

}

let ctx = self.inner.new_ctx();

self.process_request(session, ctx).await

}

fn http_cleanup(&self) {

4 collapsed lines

// Notify all keepalived request blocking on read_request() to abort

self.shutdown.notify_waiters();

// TODO: impl shutting down flag so that we don't need to read stack.is_shutting_down()

}

// TODO implement h2_options

}

让我们看看 HttpServerApp 是什么。

ServerApp 与 HttpServerApp

提到 HttpServerApp 绕不开的就是 ServerApp。我们先来看一下 ServerApp

#[cfg_attr(not(doc_async_trait), async_trait)]

/// This trait defines the interface of a transport layer (TCP or TLS) application.

pub trait ServerApp {

/// Whenever a new connection is established, this function will be called with the established

/// [`Stream`] object provided.

///

/// The application can do whatever it wants with the `session`.

///

/// After processing the `session`, if the `session`'s connection is reusable, This function

/// can return it to the service by returning `Some(session)`. The returned `session` will be

/// fed to another [`Self::process_new()`] for another round of processing.

/// If not reusable, `None` should be returned.

///

/// The `shutdown` argument will change from `false` to `true` when the server receives a

/// signal to shutdown. This argument allows the application to react accordingly.

async fn process_new(

self: &Arc<Self>,

mut session: Stream,

// TODO: make this ShutdownWatch so that all task can await on this event

shutdown: &ShutdownWatch,

) -> Option<Stream>;

/// This callback will be called once after the service stops listening to its endpoints.

fn cleanup(&self) {}

}

简单易懂。在新的连接进入时,Pingora 会调用 process_new() 进行处理;而当 Service 停止时,则会使用 cleanup() 进行清理。

再看看 HttpServerApp

/// This trait defines the interface of a HTTP application.

#[cfg_attr(not(doc_async_trait), async_trait)]

pub trait HttpServerApp {

/// Similar to the [`ServerApp`], this function is called whenever a new HTTP session is established.

///

/// After successful processing, [`ServerSession::finish()`] can be called to return an optionally reusable

/// connection back to the service. The caller needs to make sure that the connection is in a reusable state

/// i.e., no error or incomplete read or write headers or bodies. Otherwise a `None` should be returned.

async fn process_new_http(

self: &Arc<Self>,

mut session: ServerSession,

// TODO: make this ShutdownWatch so that all task can await on this event

shutdown: &ShutdownWatch,

) -> Option<Stream>;

/// Provide options on how HTTP/2 connection should be established. This function will be called

/// every time a new HTTP/2 **connection** needs to be established.

///

/// A `None` means to use the built-in default options. See [`server::H2Options`] for more details.

fn h2_options(&self) -> Option<server::H2Options> {

None

}

fn http_cleanup(&self) {}

}

首先是 process_new_http。与 process_new 不能说是一致,几乎可以说是完全一样了。唯一的区别是传入的第二个参数 session 的类型从 Stream 变成了 ServerSessionServerSession 是 HTTP 下特有的 context,针对 http1http2 分别存储了不同的内容。

Pingora 为所有 trait HttpServerApp 实现了 trait ServerApp。因此上面实现了 HttpServerAppHttpProxy 也就自动实现了 ServerApp