Week 3
Lab
Step 1 本地部署一个 OpenFaaS
- 选择在裸机环境下安装
faasd
(我没有这么做) Kubernetes
(k8s
)
-
为什么要
k8s
:- 服务发现和负载均衡
- 存储编排
- 自动部署和回滚
- 自动资源调度
- 自我修复容器(重启、替换、杀死容器)
- 密钥与配置管理
- OpenFaaS
# 查看IP
kubectl get nodes -o wide
kubectl get svc gateway -n openfaas
# 设置/更改密码
# 删除旧密码 kubectl -n openfaas delete secret basic-auth
kubectl -n openfaas create secret generic basic-auth \
--from-literal=basic-auth-user=admin \
--from-literal=basic-auth-password=newpassword
kubectl get pods -n openfaas
确保所有 pods
为 STATUS: Running
,而不是 CrashLoopBackOff
(搞这个莫名搞了我半天 :(
- 登进
OpenFaaS
http://<Node-IP>:31112 (可选:修改hosts
文件)
Step 2 编写业务代码
GET /:返回提示信息。
POST /echo:返回请求体内容。
POST /echo/uppercase:返回转为大写的请求体内容。
POST /echo/primes:返回是否为质数。
main.rs:(我这里想实现一个2e7范围内判断质数的 FaaS
,需要手动配置 Tokio
)
fn handler_service(req: Request<Body>) -> BoxFuture<'static, Result<Response<Body>, Infallible>> {
Box::pin(async {
match handler::echo(req).await {
Ok(response) => Ok(response),
Err(e) => {
let error_response = Response::builder()
.status(500)
.body(Body::from(format!("Internal Server Error: {:?}", e)))
.unwrap();
Ok(error_response)
}
}
})
}
fn main() {
// 配置 Tokio 运行时的栈空间大小
let runtime = Builder::new_multi_thread()
.thread_stack_size(160 * 1024 * 1024) // 设置每个线程的栈空间为 160MB
.enable_all() // 启用所有功能(包括 I/O 和时间功能)
.build()
.unwrap();
let addr = ([0, 0, 0, 0], 3000).into();
// 创建服务
let make_svc = make_service_fn(|_conn| async {
Ok::<_, Infallible>(service_fn(handler_service))
});
// 启动服务器
runtime.block_on(async {
let server = Server::bind(&addr).serve(make_svc);
println!("服务器已启动,监听地址: {}", addr);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
});
println!("服务器已退出");
}
当异步函数执行到一个await表达式时,状态机会保存当前状态,并将控制权返回给调用者。
cargo run
测试如下:
Step 3 部署 FaaS
- login
# docker hub
docker login -u <yourname>
# OpenFaaS
cat ~/faas_pass.txt | faas-cli login -u admin --password-stdin --gateway http://172.30.225.124:31112
下面这样就是成功登录了,不要像我一样以为刚需https,捣鼓一晚上 :(
Calling the OpenFaaS server to validate the credentials…
WARNING! You are not using an encrypted connection to the gateway, consider using HTTPS.
credentials saved for admin http://172.30.225.124:31112
- 部署函数:
# 可能需要根据你的情况加上 --gateway http://172.30.225.124:31112
# 构建函数镜像
faas-cli build -f <function-yaml-file>
# 推送函数镜像到仓库
faas-cli push -f <function-yaml-file>
# 部署函数到 OpenFaaS
faas-cli deploy -f <function-yaml-file>
# 查看函数列表
faas-cli list
- 登上
OpenFaaS UI
或者用curl
查看
# 查看密码
PASSWORD=$(kubectl -n openfaas get secret basic-auth -o jsonpath="{.data.basic-auth-password}" | base64 --decode)
echo "OpenFaaS admin password: $PASSWORD"
成果如下:
后记
多路由函数(比如/echo,/echo/others 等等),在 OpenFaaS
上要注意:
http://172.30.225.124:31112/function/echo 的
echo
只是名字,其实是/
根目录