From 308e9bcc5d9bd6823da98da0f584c7c4ca25c0ae Mon Sep 17 00:00:00 2001 From: Samuel Dai Date: Thu, 22 May 2025 21:43:16 +0800 Subject: [PATCH] refactor: project structure and better interfaces (#100) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: basically rewrite all interface * refactor: rename crates to make clear meaning; use tokio runtime and handle shutdown within Provider * remove tracker in main Signed-off-by: sparkzky * feat(provider): enhance Provider trait with list, update, and status methods; refactor existing methods to async * fix(containerd): fetch handle from environment and initialize it. * fix(init): BACKEND init add handle fetching * fix: add test framework * fix: move the snapshot logic into snapshot.rs Signed-off-by: sparkzky * fix: change some spec setting Signed-off-by: sparkzky * feat: add created_at field, add http status code convertion * refactor(spec): use builder to generate spec Signed-off-by: sparkzky * fix: clippy Signed-off-by: sparkzky * manage reference, fix boot issue * fix: ip parsing * feat: add cleanup logic on fail * fix style: clippy for return function * feat: add response message * fix:1.修复proxy和resolve的逻辑 2.spec内netns的路径问题以及传参顺序 * feat:add update list status service implmentation * fix: move some consts into consts.rs Signed-off-by: sparkzky * fix: fmt & clippy Signed-off-by: sparkzky * fix: update dependecy Signed-off-by: sparkzky * feat: add function with_vm_network Signed-off-by: sparkzky * feat: integrate cni into containerd crate * fix:修复proxy的路径正则匹配并添加单元测试 * fix:fix proxy_path and add default namespace for Query::from * fix: integration_test * fix: path dispatch test * fix: more specified url dispatch in proxy handle * feat: add persistent container record for restart service * feat: add task error type * fix: delete error handle logic --------- Signed-off-by: sparkzky Co-authored-by: sparkzky Co-authored-by: dolzhuying <1240800466@qq.com> Co-authored-by: scutKKsix <1129332011@qq.com> --- Cargo.lock | 1022 +++++++---------- crates/app/Cargo.toml | 16 - crates/app/src/main.rs | 60 - crates/app/tests/integration_test.rs | 105 -- crates/cni/Cargo.toml | 16 - crates/cni/src/command.rs | 92 -- crates/cni/src/lib.rs | 91 -- crates/cni/src/netns.rs | 32 - crates/faas-containerd/Cargo.toml | 36 + crates/faas-containerd/src/consts.rs | 15 + .../faas-containerd/src/impls/cni/cni_impl.rs | 148 +++ .../faas-containerd/src/impls/cni/command.rs | 94 ++ crates/faas-containerd/src/impls/cni/mod.rs | 55 + .../src/impls/cni}/util.rs | 28 +- crates/faas-containerd/src/impls/container.rs | 125 ++ crates/faas-containerd/src/impls/error.rs | 17 + crates/faas-containerd/src/impls/function.rs | 97 ++ crates/faas-containerd/src/impls/mod.rs | 30 + .../src/impls/oci_image.rs} | 624 +++++----- crates/faas-containerd/src/impls/snapshot.rs | 131 +++ crates/faas-containerd/src/impls/spec.rs | 329 ++++++ crates/faas-containerd/src/impls/task.rs | 210 ++++ crates/faas-containerd/src/lib.rs | 8 + crates/faas-containerd/src/main.rs | 36 + .../src/provider/function/delete.rs | 35 + .../src/provider/function/deploy.rs | 96 ++ .../src/provider/function/get.rs | 19 + .../src/provider/function/list.rs | 69 ++ .../src/provider/function/mod.rs | 6 + .../src/provider/function/resolve.rs | 65 ++ .../src/provider/function/status.rs | 69 ++ .../src/provider/function/update.rs | 32 + crates/faas-containerd/src/provider/mod.rs | 49 + .../src/systemd.rs | 0 .../faas-containerd/tests/integration_test.rs | 150 +++ crates/{provider => gateway}/Cargo.toml | 22 +- crates/gateway/src/bootstrap/mod.rs | 175 +++ crates/gateway/src/handlers/function.rs | 173 +++ crates/gateway/src/handlers/mod.rs | 34 + crates/gateway/src/handlers/proxy.rs | 67 ++ .../src/handlers/utils.rs | 0 crates/gateway/src/lib.rs | 6 + .../{provider => gateway}/src/metrics/mod.rs | 2 - crates/gateway/src/provider/mod.rs | 45 + .../src/proxy/builder.rs | 12 +- crates/{provider => gateway}/src/proxy/mod.rs | 3 +- crates/gateway/src/proxy/proxy_handler.rs | 28 + crates/gateway/src/proxy/test.rs | 108 ++ .../{provider => gateway}/src/types/config.rs | 0 crates/gateway/src/types/function.rs | 166 +++ crates/gateway/src/types/mod.rs | 2 + crates/my-workspace-hack/Cargo.toml | 14 +- crates/provider/src/bootstrap/mod.rs | 103 -- crates/provider/src/config/mod.rs | 1 - crates/provider/src/consts.rs | 14 - crates/provider/src/handlers/delete.rs | 68 -- crates/provider/src/handlers/deploy.rs | 77 -- crates/provider/src/handlers/function_get.rs | 146 --- crates/provider/src/handlers/function_list.rs | 74 -- .../provider/src/handlers/invoke_resolver.rs | 54 - crates/provider/src/handlers/mod.rs | 111 -- crates/provider/src/httputils/mod.rs | 1 - crates/provider/src/lib.rs | 9 - crates/provider/src/logs/mod.rs | 1 - crates/provider/src/proxy/proxy_handler.rs | 59 - .../provider/src/proxy/proxy_handler_test.rs | 127 -- .../provider/src/types/function_deployment.rs | 71 -- crates/provider/src/types/mod.rs | 2 - crates/service/Cargo.toml | 21 - crates/service/src/containerd_manager.rs | 599 ---------- crates/service/src/lib.rs | 48 - crates/service/src/namespace_manager.rs | 81 -- crates/service/src/spec.rs | 339 ------ docs/openapi.yaml | 2 +- flake.nix | 10 +- 75 files changed, 3451 insertions(+), 3431 deletions(-) delete mode 100644 crates/app/Cargo.toml delete mode 100644 crates/app/src/main.rs delete mode 100644 crates/app/tests/integration_test.rs delete mode 100644 crates/cni/Cargo.toml delete mode 100644 crates/cni/src/command.rs delete mode 100644 crates/cni/src/lib.rs delete mode 100644 crates/cni/src/netns.rs create mode 100644 crates/faas-containerd/Cargo.toml create mode 100644 crates/faas-containerd/src/consts.rs create mode 100644 crates/faas-containerd/src/impls/cni/cni_impl.rs create mode 100644 crates/faas-containerd/src/impls/cni/command.rs create mode 100644 crates/faas-containerd/src/impls/cni/mod.rs rename crates/{cni/src => faas-containerd/src/impls/cni}/util.rs (78%) create mode 100644 crates/faas-containerd/src/impls/container.rs create mode 100644 crates/faas-containerd/src/impls/error.rs create mode 100644 crates/faas-containerd/src/impls/function.rs create mode 100644 crates/faas-containerd/src/impls/mod.rs rename crates/{service/src/image_manager.rs => faas-containerd/src/impls/oci_image.rs} (54%) create mode 100644 crates/faas-containerd/src/impls/snapshot.rs create mode 100644 crates/faas-containerd/src/impls/spec.rs create mode 100644 crates/faas-containerd/src/impls/task.rs create mode 100644 crates/faas-containerd/src/lib.rs create mode 100644 crates/faas-containerd/src/main.rs create mode 100644 crates/faas-containerd/src/provider/function/delete.rs create mode 100644 crates/faas-containerd/src/provider/function/deploy.rs create mode 100644 crates/faas-containerd/src/provider/function/get.rs create mode 100644 crates/faas-containerd/src/provider/function/list.rs create mode 100644 crates/faas-containerd/src/provider/function/mod.rs create mode 100644 crates/faas-containerd/src/provider/function/resolve.rs create mode 100644 crates/faas-containerd/src/provider/function/status.rs create mode 100644 crates/faas-containerd/src/provider/function/update.rs create mode 100644 crates/faas-containerd/src/provider/mod.rs rename crates/{service => faas-containerd}/src/systemd.rs (100%) create mode 100644 crates/faas-containerd/tests/integration_test.rs rename crates/{provider => gateway}/Cargo.toml (58%) create mode 100644 crates/gateway/src/bootstrap/mod.rs create mode 100644 crates/gateway/src/handlers/function.rs create mode 100644 crates/gateway/src/handlers/mod.rs create mode 100644 crates/gateway/src/handlers/proxy.rs rename crates/{provider => gateway}/src/handlers/utils.rs (100%) create mode 100644 crates/gateway/src/lib.rs rename crates/{provider => gateway}/src/metrics/mod.rs (93%) create mode 100644 crates/gateway/src/provider/mod.rs rename crates/{provider => gateway}/src/proxy/builder.rs (70%) rename crates/{provider => gateway}/src/proxy/mod.rs (57%) create mode 100644 crates/gateway/src/proxy/proxy_handler.rs create mode 100644 crates/gateway/src/proxy/test.rs rename crates/{provider => gateway}/src/types/config.rs (100%) create mode 100644 crates/gateway/src/types/function.rs create mode 100644 crates/gateway/src/types/mod.rs delete mode 100644 crates/provider/src/bootstrap/mod.rs delete mode 100644 crates/provider/src/config/mod.rs delete mode 100644 crates/provider/src/consts.rs delete mode 100644 crates/provider/src/handlers/delete.rs delete mode 100644 crates/provider/src/handlers/deploy.rs delete mode 100644 crates/provider/src/handlers/function_get.rs delete mode 100644 crates/provider/src/handlers/function_list.rs delete mode 100644 crates/provider/src/handlers/invoke_resolver.rs delete mode 100644 crates/provider/src/handlers/mod.rs delete mode 100644 crates/provider/src/httputils/mod.rs delete mode 100644 crates/provider/src/lib.rs delete mode 100644 crates/provider/src/logs/mod.rs delete mode 100644 crates/provider/src/proxy/proxy_handler.rs delete mode 100644 crates/provider/src/proxy/proxy_handler_test.rs delete mode 100644 crates/provider/src/types/function_deployment.rs delete mode 100644 crates/provider/src/types/mod.rs delete mode 100644 crates/service/Cargo.toml delete mode 100644 crates/service/src/containerd_manager.rs delete mode 100644 crates/service/src/lib.rs delete mode 100644 crates/service/src/namespace_manager.rs delete mode 100644 crates/service/src/spec.rs diff --git a/Cargo.lock b/Cargo.lock index 17b9c25..b927f23 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -21,23 +21,23 @@ dependencies = [ [[package]] name = "actix-http" -version = "3.9.0" +version = "3.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d48f96fc3003717aeb9856ca3d02a8c7de502667ad76eeacd830b48d2e91fac4" +checksum = "44dfe5c9e0004c623edc65391dfd51daa201e7e30ebd9c9bedf873048ec32bc2" dependencies = [ "actix-codec", "actix-rt", "actix-service", "actix-utils", - "ahash", "base64 0.22.1", "bitflags 2.8.0", "brotli", "bytes", "bytestring", - "derive_more 0.99.18", + "derive_more", "encoding_rs", "flate2", + "foldhash", "futures-core", "h2 0.3.26", "http 0.2.12", @@ -49,7 +49,7 @@ dependencies = [ "mime", "percent-encoding", "pin-project-lite", - "rand 0.8.5", + "rand 0.9.1", "sha1", "smallvec", "tokio", @@ -65,7 +65,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb" dependencies = [ "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -79,7 +79,7 @@ dependencies = [ "http 0.2.12", "regex", "regex-lite", - "serde 1.0.217", + "serde", "tracing", ] @@ -95,9 +95,9 @@ dependencies = [ [[package]] name = "actix-server" -version = "2.5.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ca2549781d8dd6d75c40cf6b6051260a2cc2f3c62343d761a969a0640646894" +checksum = "a65064ea4a457eaf07f2fba30b4c695bf43b721790e9530d26cb6f9019ff7502" dependencies = [ "actix-rt", "actix-service", @@ -152,9 +152,9 @@ dependencies = [ [[package]] name = "actix-web" -version = "4.9.0" +version = "4.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9180d76e5cc7ccbc4d60a506f2c727730b154010262df5b910eb17dbe4b8cb38" +checksum = "a597b77b5c6d6a1e1097fddde329a83665e25c5437c696a3a9a4aa514a614dea" dependencies = [ "actix-codec", "actix-http", @@ -165,13 +165,13 @@ dependencies = [ "actix-service", "actix-utils", "actix-web-codegen", - "ahash", "bytes", "bytestring", "cfg-if", "cookie", - "derive_more 0.99.18", + "derive_more", "encoding_rs", + "foldhash", "futures-core", "futures-util", "impl-more", @@ -183,12 +183,13 @@ dependencies = [ "pin-project-lite", "regex", "regex-lite", - "serde 1.0.217", + "serde", "serde_json", "serde_urlencoded", "smallvec", "socket2", "time", + "tracing", "url", ] @@ -201,7 +202,7 @@ dependencies = [ "actix-router", "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -234,19 +235,6 @@ version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627" -[[package]] -name = "ahash" -version = "0.8.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e89da841a80418a9b391ebaea17f5c112ffaaa96f621d2c285b5174da76b9011" -dependencies = [ - "cfg-if", - "getrandom 0.2.15", - "once_cell", - "version_check", - "zerocopy", -] - [[package]] name = "aho-corasick" version = "1.1.3" @@ -272,53 +260,18 @@ dependencies = [ ] [[package]] -name = "anstream" -version = "0.6.18" +name = "android-tzdata" +version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8acc5369981196006228e28809f761875c0327210a891e941f4c683b3a99529b" -dependencies = [ - "anstyle", - "anstyle-parse", - "anstyle-query", - "anstyle-wincon", - "colorchoice", - "is_terminal_polyfill", - "utf8parse", -] +checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" [[package]] -name = "anstyle" -version = "1.0.10" +name = "android_system_properties" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55cc3b69f167a1ef2e161439aa98aed94e6028e5f9a59be9a6ffb47aef1651f9" - -[[package]] -name = "anstyle-parse" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b2d16507662817a6a20a9ea92df6652ee4f94f914589377d69f3b21bc5798a9" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" dependencies = [ - "utf8parse", -] - -[[package]] -name = "anstyle-query" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79947af37f4177cfead1110013d678905c37501914fba0efea834c3fe9a8d60c" -dependencies = [ - "windows-sys 0.59.0", -] - -[[package]] -name = "anstyle-wincon" -version = "3.0.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca3534e77181a9cc07539ad51f2141fe32f6c3ffd4df76db8ad92346b003ae4e" -dependencies = [ - "anstyle", - "once_cell", - "windows-sys 0.59.0", + "libc", ] [[package]] @@ -328,10 +281,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34ac096ce696dc2fcabef30516bb13c0a68a11d30131d3df6f04711467681b04" [[package]] -name = "arrayvec" -version = "0.5.2" +name = "async-safe-defer" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" +checksum = "c1f4369b3a4ac026c75c6707978bdfe60a4489cd9a6ae75e37f7ccea524f881a" [[package]] name = "async-stream" @@ -352,18 +305,18 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] name = "async-trait" -version = "0.1.85" +version = "0.1.88" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f934833b4b7233644e5848f235df3f57ed8c80f1528a26c3dfa13d2147fa056" +checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -394,7 +347,7 @@ dependencies = [ "bytes", "cfg-if", "cookie", - "derive_more 2.0.1", + "derive_more", "futures-core", "futures-util", "h2 0.3.26", @@ -405,7 +358,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "rand 0.9.1", - "serde 1.0.217", + "serde", "serde_json", "serde_urlencoded", "tokio", @@ -422,7 +375,7 @@ dependencies = [ "bytes", "futures-util", "http 1.3.1", - "http-body 1.0.1", + "http-body", "http-body-util", "itoa", "matchit", @@ -431,7 +384,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "rustversion", - "serde 1.0.217", + "serde", "sync_wrapper", "tower 0.5.2", "tower-layer", @@ -448,7 +401,7 @@ dependencies = [ "bytes", "futures-util", "http 1.3.1", - "http-body 1.0.1", + "http-body", "http-body-util", "mime", "pin-project-lite", @@ -506,49 +459,11 @@ dependencies = [ "generic-array", ] -[[package]] -name = "bollard" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d82e7850583ead5f8bbef247e2a3c37a19bd576e8420cd262a6711921827e1e5" -dependencies = [ - "base64 0.13.1", - "bollard-stubs", - "bytes", - "futures-core", - "futures-util", - "hex", - "http 0.2.12", - "hyper 0.14.32", - "hyperlocal", - "log", - "pin-project-lite", - "serde 1.0.217", - "serde_derive", - "serde_json", - "serde_urlencoded", - "thiserror 1.0.69", - "tokio", - "tokio-util", - "url", - "winapi", -] - -[[package]] -name = "bollard-stubs" -version = "1.42.0-rc.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed59b5c00048f48d7af971b71f800fdf23e858844a6f9e4d32ca72e9399e7864" -dependencies = [ - "serde 1.0.217", - "serde_with", -] - [[package]] name = "brotli" -version = "6.0.0" +version = "8.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74f7971dbd9326d58187408ab83117d8ac1bb9c17b085fdacd1cf2f598719b6b" +checksum = "9991eea70ea4f293524138648e41ee89b0b2b12ddef3b255effa43c8056e0e0d" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", @@ -557,14 +472,20 @@ dependencies = [ [[package]] name = "brotli-decompressor" -version = "4.0.2" +version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74fa05ad7d803d413eb8380983b092cbbaf9a85f151b871360e7b00cd7060b37" +checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03" dependencies = [ "alloc-no-stdlib", "alloc-stdlib", ] +[[package]] +name = "bumpalo" +version = "3.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" + [[package]] name = "byteorder" version = "1.5.0" @@ -604,40 +525,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] -name = "cni" -version = "0.1.0" +name = "chrono" +version = "0.4.41" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c469d952047f47f91b68d1cba3f10d63c11d73e4636f24f08daf0278abf01c4d" dependencies = [ - "defer", - "dotenv", - "env_logger 0.11.8", - "lazy_static", - "log", - "my-workspace-hack", - "netns-rs", - "serde_json", + "android-tzdata", + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", ] [[package]] -name = "colorchoice" -version = "1.0.3" +name = "cidr" +version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b63caa9aa9397e2d9480a9b13673856c78d8ac123288526c37d7839f2a86990" +checksum = "bd1b64030216239a2e7c364b13cd96a2097ebf0dfe5025f2dedee14a23f2ab60" [[package]] -name = "config" -version = "0.11.0" +name = "container_image_dist_ref" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b1b9d958c2b1368a663f05538fc1b5975adce1e19f435acceae987aceeeb369" -dependencies = [ - "lazy_static", - "nom", - "rust-ini", - "serde 1.0.217", - "serde-hjson", - "serde_json", - "toml", - "yaml-rust", -] +checksum = "34d6a36cca589c5ee5b480b147783c2c80752b6d0a9cf5914a2cd7e82a9be8db" [[package]] name = "containerd-client" @@ -655,12 +567,6 @@ dependencies = [ "tower 0.5.2", ] -[[package]] -name = "convert_case" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" - [[package]] name = "convert_case" version = "0.7.1" @@ -681,6 +587,12 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -699,6 +611,21 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "crossbeam-epoch" +version = "0.9.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + [[package]] name = "crypto-common" version = "0.1.6" @@ -709,38 +636,14 @@ dependencies = [ "typenum", ] -[[package]] -name = "darling" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" -dependencies = [ - "darling_core 0.13.4", - "darling_macro 0.13.4", -] - [[package]] name = "darling" version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6f63b86c8a8826a49b8c21f08a2d07338eec8d900540f8630dc76284be802989" dependencies = [ - "darling_core 0.20.10", - "darling_macro 0.20.10", -] - -[[package]] -name = "darling_core" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" -dependencies = [ - "fnv", - "ident_case", - "proc-macro2", - "quote", - "strsim 0.10.0", - "syn 1.0.109", + "darling_core", + "darling_macro", ] [[package]] @@ -753,19 +656,8 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "strsim 0.11.1", - "syn 2.0.100", -] - -[[package]] -name = "darling_macro" -version = "0.13.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" -dependencies = [ - "darling_core 0.13.4", - "quote", - "syn 1.0.109", + "strsim", + "syn", ] [[package]] @@ -774,17 +666,11 @@ version = "0.20.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d336a2a514f6ccccaa3e09b02d41d35330c07ddf03a62165fcec10bb561c7806" dependencies = [ - "darling_core 0.20.10", + "darling_core", "quote", - "syn 2.0.100", + "syn", ] -[[package]] -name = "defer" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "930c7171c8df9fb1782bdf9b918ed9ed2d33d1d22300abb754f9085bc48bf8e8" - [[package]] name = "deranged" version = "0.3.11" @@ -809,10 +695,10 @@ version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" dependencies = [ - "darling 0.20.10", + "darling", "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -822,20 +708,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" dependencies = [ "derive_builder_core", - "syn 2.0.100", -] - -[[package]] -name = "derive_more" -version = "0.99.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f33878137e4dafd7fa914ad4e259e18a4e8e532b9617a2d0150262bf53abfce" -dependencies = [ - "convert_case 0.4.0", - "proc-macro2", - "quote", - "rustc_version", - "syn 2.0.100", + "syn", ] [[package]] @@ -853,10 +726,10 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3" dependencies = [ - "convert_case 0.7.1", + "convert_case", "proc-macro2", "quote", - "syn 2.0.100", + "syn", "unicode-xid", ] @@ -878,7 +751,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -902,16 +775,6 @@ dependencies = [ "cfg-if", ] -[[package]] -name = "env_filter" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "186e05a59d4c50738528153b83b0b0194d3a29507dfec16eccd4b342903397d0" -dependencies = [ - "log", - "regex", -] - [[package]] name = "env_logger" version = "0.10.2" @@ -925,19 +788,6 @@ dependencies = [ "termcolor", ] -[[package]] -name = "env_logger" -version = "0.11.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13c863f0904021b108aa8b2f55046443e6b1ebde8fd4a15c399893aae4fa069f" -dependencies = [ - "anstream", - "anstyle", - "env_filter", - "jiff", - "log", -] - [[package]] name = "equivalent" version = "1.0.1" @@ -955,19 +805,37 @@ dependencies = [ ] [[package]] -name = "faas-rs" +name = "faas-containerd" version = "0.1.0" dependencies = [ + "actix-http", "actix-web", + "async-safe-defer", + "chrono", + "cidr", + "container_image_dist_ref", + "containerd-client", + "derive_more", "dotenv", - "env_logger 0.10.2", + "env_logger", + "futures", + "gateway", + "handlebars", + "hex", "log", "my-workspace-hack", - "provider", - "serde 1.0.217", + "netns-rs", + "oci-spec", + "prost-types", + "scopeguard", + "serde", "serde_json", - "service", + "sha2", + "sled", "tokio", + "tokio-util", + "tonic", + "url", ] [[package]] @@ -998,6 +866,12 @@ version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "form_urlencoded" version = "1.2.1" @@ -1007,6 +881,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "futures" version = "0.3.31" @@ -1063,7 +947,7 @@ checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -1096,6 +980,39 @@ dependencies = [ "slab", ] +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + +[[package]] +name = "gateway" +version = "0.1.0" +dependencies = [ + "actix-http", + "actix-web", + "actix-web-httpauth", + "awc", + "base64 0.13.1", + "chrono", + "derive_more", + "http 1.3.1", + "log", + "my-workspace-hack", + "prometheus", + "serde", + "serde_json", + "thiserror 1.0.69", + "tokio", + "tokio-util", + "tonic", + "url", +] + [[package]] name = "generic-array" version = "0.14.7" @@ -1138,7 +1055,7 @@ dependencies = [ "proc-macro-error2", "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -1194,7 +1111,7 @@ dependencies = [ "log", "pest", "pest_derive", - "serde 1.0.217", + "serde", "serde_json", "thiserror 1.0.69", ] @@ -1251,17 +1168,6 @@ dependencies = [ "itoa", ] -[[package]] -name = "http-body" -version = "0.4.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" -dependencies = [ - "bytes", - "http 0.2.12", - "pin-project-lite", -] - [[package]] name = "http-body" version = "1.0.1" @@ -1281,7 +1187,7 @@ dependencies = [ "bytes", "futures-util", "http 1.3.1", - "http-body 1.0.1", + "http-body", "pin-project-lite", ] @@ -1303,30 +1209,6 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" -[[package]] -name = "hyper" -version = "0.14.32" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" -dependencies = [ - "bytes", - "futures-channel", - "futures-core", - "futures-util", - "h2 0.3.26", - "http 0.2.12", - "http-body 0.4.6", - "httparse", - "httpdate", - "itoa", - "pin-project-lite", - "socket2", - "tokio", - "tower-service", - "tracing", - "want", -] - [[package]] name = "hyper" version = "1.5.2" @@ -1338,7 +1220,7 @@ dependencies = [ "futures-util", "h2 0.4.7", "http 1.3.1", - "http-body 1.0.1", + "http-body", "httparse", "httpdate", "itoa", @@ -1354,7 +1236,7 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0" dependencies = [ - "hyper 1.5.2", + "hyper", "hyper-util", "pin-project-lite", "tokio", @@ -1371,8 +1253,8 @@ dependencies = [ "futures-channel", "futures-util", "http 1.3.1", - "http-body 1.0.1", - "hyper 1.5.2", + "http-body", + "hyper", "pin-project-lite", "socket2", "tokio", @@ -1381,16 +1263,27 @@ dependencies = [ ] [[package]] -name = "hyperlocal" -version = "0.8.0" +name = "iana-time-zone" +version = "0.1.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fafdf7b2b2de7c9784f76e02c0935e65a8117ec3b768644379983ab333ac98c" +checksum = "b0c919e5debc312ad217002b8048a17b7d83f80703865bbfcfebb0458b0b27d8" dependencies = [ - "futures-util", - "hex", - "hyper 0.14.32", - "pin-project", - "tokio", + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", ] [[package]] @@ -1508,7 +1401,7 @@ checksum = "1ec89e9337638ecdc08744df490b221a7399bf8d164eb52a665454e60e075ad6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -1564,6 +1457,15 @@ dependencies = [ "hashbrown 0.15.2", ] +[[package]] +name = "instant" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222" +dependencies = [ + "cfg-if", +] + [[package]] name = "is-terminal" version = "0.4.15" @@ -1575,12 +1477,6 @@ dependencies = [ "windows-sys 0.59.0", ] -[[package]] -name = "is_terminal_polyfill" -version = "1.70.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7943c866cc5cd64cbc25b2e01621d07fa8eb2a1a23160ee81ce38704e97b8ecf" - [[package]] name = "itertools" version = "0.13.0" @@ -1596,30 +1492,6 @@ version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674" -[[package]] -name = "jiff" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5ad87c89110f55e4cd4dc2893a9790820206729eaf221555f742d540b0724a0" -dependencies = [ - "jiff-static", - "log", - "portable-atomic", - "portable-atomic-util", - "serde 1.0.217", -] - -[[package]] -name = "jiff-static" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d076d5b64a7e2fe6f0743f02c43ca4a6725c0f904203bfe276a5b3e793103605" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.100", -] - [[package]] name = "jobserver" version = "0.1.32" @@ -1629,6 +1501,16 @@ dependencies = [ "libc", ] +[[package]] +name = "js-sys" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + [[package]] name = "language-tags" version = "0.3.2" @@ -1641,31 +1523,12 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" -[[package]] -name = "lexical-core" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6607c62aa161d23d17a9072cc5da0be67cdfc89d3afb1e8d9c842bebc2525ffe" -dependencies = [ - "arrayvec", - "bitflags 1.3.2", - "cfg-if", - "ryu", - "static_assertions", -] - [[package]] name = "libc" version = "0.2.169" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" -[[package]] -name = "linked-hash-map" -version = "0.5.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" - [[package]] name = "linux-raw-sys" version = "0.4.15" @@ -1770,7 +1633,10 @@ name = "my-workspace-hack" version = "0.1.0" dependencies = [ "actix-router", + "bitflags 2.8.0", + "byteorder", "bytes", + "chrono", "futures-channel", "futures-task", "futures-util", @@ -1783,12 +1649,12 @@ dependencies = [ "regex", "regex-automata", "regex-syntax", - "serde 1.0.217", + "scopeguard", + "serde", "smallvec", - "syn 2.0.100", + "syn", "tokio", "tokio-util", - "tower 0.4.13", "tracing", "tracing-core", ] @@ -1816,32 +1682,12 @@ dependencies = [ "memoffset", ] -[[package]] -name = "nom" -version = "5.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08959a387a676302eebf4ddbcbc611da04285579f76f88ee0506c63b1a61dd4b" -dependencies = [ - "lexical-core", - "memchr", - "version_check", -] - [[package]] name = "num-conv" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" -[[package]] -name = "num-traits" -version = "0.1.43" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92e5113e9fd4cc14ded8e499429f396a20f98c772a47cc8622a736e1ec843c31" -dependencies = [ - "num-traits 0.2.19", -] - [[package]] name = "num-traits" version = "0.2.19" @@ -1868,7 +1714,7 @@ checksum = "bdf88ddc01cc6bccbe1044adb6a29057333f523deadcb4953c011a73158cfa5e" dependencies = [ "derive_builder", "getset", - "serde 1.0.217", + "serde", "serde_json", "strum", "strum_macros", @@ -1877,9 +1723,20 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.20.2" +version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1261fe7e33c73b354eab43b1273a57c8f967d0391e80353e51f764ac02cf6775" +checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" + +[[package]] +name = "parking_lot" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99" +dependencies = [ + "instant", + "lock_api", + "parking_lot_core 0.8.6", +] [[package]] name = "parking_lot" @@ -1888,7 +1745,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27" dependencies = [ "lock_api", - "parking_lot_core", + "parking_lot_core 0.9.10", +] + +[[package]] +name = "parking_lot_core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc" +dependencies = [ + "cfg-if", + "instant", + "libc", + "redox_syscall 0.2.16", + "smallvec", + "winapi", ] [[package]] @@ -1899,7 +1770,7 @@ checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.8", "smallvec", "windows-targets", ] @@ -1947,7 +1818,7 @@ dependencies = [ "pest_meta", "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -1988,7 +1859,7 @@ checksum = "d56a66c0c55993aa927429d0f8a0abfd74f084e4d9c192cffed01e418d83eefb" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2009,21 +1880,6 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "953ec861398dccce10c670dfeaf3ec4911ca479e9c02154b3a215178c5f566f2" -[[package]] -name = "portable-atomic" -version = "1.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "350e9b48cbc6b0e028b0473b114454c6316e57336ee184ceab6e53f72c178b3e" - -[[package]] -name = "portable-atomic-util" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8a2f0d8d040d7848a709caf78912debcc3f33ee4b3cac47d73d1e1069e83507" -dependencies = [ - "portable-atomic", -] - [[package]] name = "powerfmt" version = "0.2.0" @@ -2046,7 +1902,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6924ced06e1f7dfe3fa48d57b9f74f55d8915f5036121bef647ef4b204895fac" dependencies = [ "proc-macro2", - "syn 2.0.100", + "syn", ] [[package]] @@ -2068,7 +1924,7 @@ dependencies = [ "proc-macro-error-attr2", "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2090,7 +1946,7 @@ dependencies = [ "fnv", "lazy_static", "memchr", - "parking_lot", + "parking_lot 0.12.3", "protobuf", "thiserror 1.0.69", ] @@ -2121,7 +1977,7 @@ dependencies = [ "prost", "prost-types", "regex", - "syn 2.0.100", + "syn", "tempfile", ] @@ -2135,7 +1991,7 @@ dependencies = [ "itertools", "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2153,40 +2009,6 @@ version = "2.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "106dd99e98437432fed6519dedecfade6a06a73bb7b2a1e019fdd2bee5778d94" -[[package]] -name = "provider" -version = "0.1.0" -dependencies = [ - "actix-service", - "actix-web", - "actix-web-httpauth", - "async-trait", - "awc", - "base64 0.13.1", - "bollard", - "cni", - "config", - "derive_more 2.0.1", - "futures", - "futures-util", - "http 1.3.1", - "lazy_static", - "log", - "my-workspace-hack", - "prometheus", - "regex", - "serde 1.0.217", - "serde_json", - "service", - "tempfile", - "thiserror 1.0.69", - "tokio", - "tonic", - "tower 0.4.13", - "url", - "uuid", -] - [[package]] name = "quote" version = "1.0.38" @@ -2255,6 +2077,15 @@ dependencies = [ "getrandom 0.3.1", ] +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags 1.3.2", +] + [[package]] name = "redox_syscall" version = "0.5.8" @@ -2299,27 +2130,12 @@ version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c" -[[package]] -name = "rust-ini" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e52c148ef37f8c375d49d5a73aa70713125b7f19095948a923f80afdeb22ec2" - [[package]] name = "rustc-demangle" version = "0.1.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f" -[[package]] -name = "rustc_version" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" -dependencies = [ - "semver", -] - [[package]] name = "rustix" version = "0.38.44" @@ -2351,18 +2167,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" -[[package]] -name = "semver" -version = "1.0.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f79dfe2d285b0488816f30e700a7438c5a73d816b5b7d3ac72fbc48b0d185e03" - -[[package]] -name = "serde" -version = "0.8.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dad3f759919b92c3068c696c15c3d17238234498bbdcc80f2c469606f948ac8" - [[package]] name = "serde" version = "1.0.217" @@ -2372,18 +2176,6 @@ dependencies = [ "serde_derive", ] -[[package]] -name = "serde-hjson" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6a3a4e0ea8a88553209f6cc6cfe8724ecad22e1acf372793c27d995290fe74f8" -dependencies = [ - "lazy_static", - "num-traits 0.1.43", - "regex", - "serde 0.8.23", -] - [[package]] name = "serde_derive" version = "1.0.217" @@ -2392,7 +2184,7 @@ checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2404,7 +2196,7 @@ dependencies = [ "itoa", "memchr", "ryu", - "serde 1.0.217", + "serde", ] [[package]] @@ -2416,50 +2208,7 @@ dependencies = [ "form_urlencoded", "itoa", "ryu", - "serde 1.0.217", -] - -[[package]] -name = "serde_with" -version = "1.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "678b5a069e50bf00ecd22d0cd8ddf7c236f68581b03db652061ed5eb13a312ff" -dependencies = [ - "serde 1.0.217", - "serde_with_macros", -] - -[[package]] -name = "serde_with_macros" -version = "1.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e182d6ec6f05393cc0e5ed1bf81ad6db3a8feedf8ee515ecdd369809bcce8082" -dependencies = [ - "darling 0.13.4", - "proc-macro2", - "quote", - "syn 1.0.109", -] - -[[package]] -name = "service" -version = "0.1.0" -dependencies = [ - "cni", - "containerd-client", - "env_logger 0.10.2", - "handlebars", - "hex", - "lazy_static", - "log", - "my-workspace-hack", - "oci-spec", - "prost-types", - "serde 1.0.217", - "serde_json", - "sha2", - "tokio", - "tonic", + "serde", ] [[package]] @@ -2508,6 +2257,22 @@ dependencies = [ "autocfg", ] +[[package]] +name = "sled" +version = "0.34.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f96b4737c2ce5987354855aed3797279def4ebf734436c6aa4552cf8e169935" +dependencies = [ + "crc32fast", + "crossbeam-epoch", + "crossbeam-utils", + "fs2", + "fxhash", + "libc", + "log", + "parking_lot 0.11.2", +] + [[package]] name = "smallvec" version = "1.13.2" @@ -2530,18 +2295,6 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" -[[package]] -name = "static_assertions" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" - -[[package]] -name = "strsim" -version = "0.10.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" - [[package]] name = "strsim" version = "0.11.1" @@ -2564,18 +2317,7 @@ dependencies = [ "proc-macro2", "quote", "rustversion", - "syn 2.0.100", -] - -[[package]] -name = "syn" -version = "1.0.109" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" -dependencies = [ - "proc-macro2", - "quote", - "unicode-ident", + "syn", ] [[package]] @@ -2603,7 +2345,7 @@ checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2655,7 +2397,7 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2666,7 +2408,7 @@ checksum = "26afc1baea8a989337eeb52b6e72a039780ce45c3edfcc9c5b9d112feeb173c2" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2679,7 +2421,7 @@ dependencies = [ "itoa", "num-conv", "powerfmt", - "serde 1.0.217", + "serde", "time-core", "time-macros", ] @@ -2712,15 +2454,15 @@ dependencies = [ [[package]] name = "tokio" -version = "1.43.0" +version = "1.45.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d61fa4ffa3de412bfea335c6ecff681de2b609ba3c77ef3e00e521813a9ed9e" +checksum = "2513ca694ef9ede0fb23fe71a4ee4107cb102b9dc1930f6d0fd77aae068ae165" dependencies = [ "backtrace", "bytes", "libc", "mio", - "parking_lot", + "parking_lot 0.12.3", "pin-project-lite", "signal-hook-registry", "socket2", @@ -2736,7 +2478,7 @@ checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2752,26 +2494,21 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.7.13" +version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d7fcaa8d55a2bdd6b83ace262b016eca0d79ee02818c5c1bcdf0305114081078" +checksum = "66a539a9ad6d5d281510d5bd368c973d636c02dbf8a67300bfb6b950696ad7df" dependencies = [ "bytes", "futures-core", + "futures-io", "futures-sink", + "futures-util", + "hashbrown 0.15.2", "pin-project-lite", + "slab", "tokio", ] -[[package]] -name = "toml" -version = "0.5.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234" -dependencies = [ - "serde 1.0.217", -] - [[package]] name = "tonic" version = "0.12.3" @@ -2785,9 +2522,9 @@ dependencies = [ "bytes", "h2 0.4.7", "http 1.3.1", - "http-body 1.0.1", + "http-body", "http-body-util", - "hyper 1.5.2", + "hyper", "hyper-timeout", "hyper-util", "percent-encoding", @@ -2813,7 +2550,7 @@ dependencies = [ "prost-build", "prost-types", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2882,7 +2619,7 @@ checksum = "395ae124c09f9e6918a2310af6038fba074bcf474ac352496d5910dd59a2226d" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -2953,21 +2690,6 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" -[[package]] -name = "utf8parse" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" - -[[package]] -name = "uuid" -version = "1.15.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0f540e3240398cce6128b64ba83fdbdd86129c16a3aa1a3a252efd66eb3d587" -dependencies = [ - "getrandom 0.3.1", -] - [[package]] name = "version_check" version = "0.9.5" @@ -2998,6 +2720,64 @@ dependencies = [ "wit-bindgen-rt", ] +[[package]] +name = "wasm-bindgen" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" +dependencies = [ + "bumpalo", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" +dependencies = [ + "unicode-ident", +] + [[package]] name = "winapi" version = "0.3.9" @@ -3029,6 +2809,65 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" +[[package]] +name = "windows-core" +version = "0.61.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46ec44dc15085cea82cf9c78f85a9114c463a369786585ad2882d1ff0b0acf40" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a47fddd13af08290e67f4acabf4b459f647552718f683a7b415d290ac744a836" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd9211b69f8dcdfa817bfd14bf1c97c9188afa36f4750130fcdf3f400eca9fa8" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-link" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38" + +[[package]] +name = "windows-result" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b895b5356fc36103d0f64dd1e94dfa7ac5633f1c9dd6e80fe9ec4adef69e09d" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a7ab927b2637c19b3dbe0965e75d8f2d30bdd697a1516191cad2ec4df8fb28a" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.52.0" @@ -3132,22 +2971,13 @@ version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e9df38ee2d2c3c5948ea468a8406ff0db0b29ae1ffde1bcf20ef305bcc95c51" -[[package]] -name = "yaml-rust" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85" -dependencies = [ - "linked-hash-map", -] - [[package]] name = "yoke" version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "120e6aef9aa629e3d4f52dc8cc43a015c7724194c97dfaf45180d2daf2b77f40" dependencies = [ - "serde 1.0.217", + "serde", "stable_deref_trait", "yoke-derive", "zerofrom", @@ -3161,7 +2991,7 @@ checksum = "2380878cad4ac9aac1e2435f3eb4020e8374b5f13c296cb75b4620ff8e229154" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", "synstructure", ] @@ -3183,7 +3013,7 @@ checksum = "fa4f8080344d4671fb4e831a13ad1e68092748387dfc4f55e356242fae12ce3e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] @@ -3203,7 +3033,7 @@ checksum = "595eed982f7d355beb85837f651fa22e90b3c044842dc7f2c2842c086f295808" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", "synstructure", ] @@ -3226,7 +3056,7 @@ checksum = "6eafa6dfb17584ea3e2bd6e76e0cc15ad7af12b09abdd1ca55961bed9b1063c6" dependencies = [ "proc-macro2", "quote", - "syn 2.0.100", + "syn", ] [[package]] diff --git a/crates/app/Cargo.toml b/crates/app/Cargo.toml deleted file mode 100644 index c10ac36..0000000 --- a/crates/app/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "faas-rs" -version = "0.1.0" -edition = "2024" - -[dependencies] -actix-web = "4.5.1" -tokio = { version = "1", features = ["full"] } -service = { path = "../service" } -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -my-workspace-hack = { version = "0.1", path = "../my-workspace-hack" } -provider = { path = "../provider" } -dotenv = "0.15" -env_logger = "0.10" -log = "0.4.27" diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs deleted file mode 100644 index cef0385..0000000 --- a/crates/app/src/main.rs +++ /dev/null @@ -1,60 +0,0 @@ -use actix_web::{App, HttpServer, web}; -use provider::{ - handlers::{ - delete::delete_handler, deploy::deploy_handler, function_list::function_list_handler, - }, - proxy::proxy_handler::proxy_handler, - types::config::FaaSConfig, -}; -use service::containerd_manager::ContainerdManager; - -#[actix_web::main] -async fn main() -> std::io::Result<()> { - dotenv::dotenv().ok(); - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - let socket_path = std::env::var("SOCKET_PATH") - .unwrap_or_else(|_| "/run/containerd/containerd.sock".to_string()); - ContainerdManager::init(&socket_path).await; - - let faas_config = FaaSConfig::new(); - - log::info!("I'm running!"); - - let server = HttpServer::new(move || { - App::new() - .app_data(web::Data::new(faas_config.clone())) - .route("/system/functions", web::post().to(deploy_handler)) - .route("/system/functions", web::delete().to(delete_handler)) - .route("/function/{name}{path:/?.*}", web::to(proxy_handler)) - .route( - "/system/functions/{namespace}", - web::get().to(function_list_handler), - ) - // 更多路由配置... - }) - .bind("0.0.0.0:8090")?; - - log::info!("Running on 0.0.0.0:8090..."); - - server.run().await -} - -// 测试env能够正常获取 -#[cfg(test)] -mod tests { - #[test] - fn test_env() { - dotenv::dotenv().ok(); - let result: Vec<(String, String)> = dotenv::vars().collect(); - let bin = std::env::var("CNI_BIN_DIR").unwrap_or_else(|_| "Not set".to_string()); - let conf = std::env::var("CNI_CONF_DIR").unwrap_or_else(|_| "Not set".to_string()); - let tool = std::env::var("CNI_TOOL").unwrap_or_else(|_| "Not set".to_string()); - log::debug!("CNI_BIN_DIR: {bin}"); - log::debug!("CNI_CONF_DIR: {conf}"); - log::debug!("CNI_TOOL: {tool}"); - // for (key, value) in &result { - // println!("{}={}", key, value); - // } - assert!(!result.is_empty()); - } -} diff --git a/crates/app/tests/integration_test.rs b/crates/app/tests/integration_test.rs deleted file mode 100644 index 656e269..0000000 --- a/crates/app/tests/integration_test.rs +++ /dev/null @@ -1,105 +0,0 @@ -use actix_web::{App, web}; -use provider::{ - handlers::{delete::delete_handler, deploy::deploy_handler}, - proxy::proxy_handler::proxy_handler, - types::config::FaaSConfig, -}; -use service::containerd_manager::ContainerdManager; - -mod integration_tests { - use super::*; - use actix_web::http::StatusCode; - use actix_web::test; - use serde_json::json; - use std::thread::sleep; - use std::time::Duration; - - #[actix_web::test] - #[ignore] - async fn test_handlers_in_order() { - dotenv::dotenv().ok(); - env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); - let socket_path = std::env::var("SOCKET_PATH") - .unwrap_or_else(|_| "/run/containerd/containerd.sock".to_string()); - ContainerdManager::init(&socket_path).await; - - let faas_config = FaaSConfig::new(); - - let app = test::init_service( - App::new() - .app_data(web::Data::new(faas_config)) - .route("/system/functions", web::post().to(deploy_handler)) - .route("/system/functions", web::delete().to(delete_handler)) - .route("/function/{name}{path:/?.*}", web::to(proxy_handler)), - ) - .await; - - // test proxy no-found-function in namespace 'default' - let req = test::TestRequest::get() - .uri("/function/test-no-found-function") - .to_request(); - let resp = test::call_service(&app, req).await; - assert_eq!(resp.status(), StatusCode::SERVICE_UNAVAILABLE); - let response_body = test::read_body(resp).await; - let response_str = std::str::from_utf8(&response_body).unwrap(); - assert!(response_str.contains("Failed to get function")); - - // test delete no-found-function in namespace 'default' - let req = test::TestRequest::delete() - .uri("/system/functions") - .set_json(json!({"function_name": "test-no-found-function"})) - .to_request(); - let resp = test::call_service(&app, req).await; - assert_eq!(resp.status(), StatusCode::NOT_FOUND); - let response_body = test::read_body(resp).await; - let response_str = std::str::from_utf8(&response_body).unwrap(); - assert!( - response_str - .contains("Function 'test-no-found-function' not found in namespace 'default'") - ); - - // test deploy in namespace 'default' - let req = test::TestRequest::post() - .uri("/system/functions") - .set_json(json!({ - "function_name": "test-function", - "image": "docker.io/library/nginx:alpine" - })) - .to_request(); - let resp = test::call_service(&app, req).await; - assert_eq!( - resp.status(), - StatusCode::ACCEPTED, - "check whether the container has been existed" - ); - - let response_body = test::read_body(resp).await; - let response_str = std::str::from_utf8(&response_body).unwrap(); - log::info!("{}", response_str); - assert!(response_str.contains("Function test-function deployment initiated successfully.")); - - sleep(Duration::from_secs(2)); - // test proxy in namespace 'default' - let req = test::TestRequest::get() - .uri("/function/test-function") - .to_request(); - let resp = test::call_service(&app, req).await; - assert_eq!(resp.status(), StatusCode::OK); - - let response_body = test::read_body(resp).await; - let response_str = std::str::from_utf8(&response_body).unwrap(); - assert!(response_str.contains("Welcome to nginx!")); - - // test delete in namespace 'default' - let req = test::TestRequest::delete() - .uri("/system/functions") - .set_json(json!({"function_name": "test-function"})) - .to_request(); - let resp = test::call_service(&app, req).await; - assert_eq!(resp.status(), StatusCode::OK); - - let response_body = test::read_body(resp).await; - let response_str = std::str::from_utf8(&response_body).unwrap(); - assert!(response_str.contains("Function test-function deleted successfully.")); - } -} diff --git a/crates/cni/Cargo.toml b/crates/cni/Cargo.toml deleted file mode 100644 index 61ac459..0000000 --- a/crates/cni/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "cni" -version = "0.1.0" -edition = "2024" -# version.workspace = true -# authors.workspace = true - -[dependencies] -serde_json = "1.0" -my-workspace-hack = { version = "0.1", path = "../my-workspace-hack" } -log = "0.4.27" -dotenv = "0.15.0" -netns-rs = "0.1.0" -lazy_static = "1.4.0" -env_logger = "0.11.8" -defer = "0.2.1" diff --git a/crates/cni/src/command.rs b/crates/cni/src/command.rs deleted file mode 100644 index ba84c0c..0000000 --- a/crates/cni/src/command.rs +++ /dev/null @@ -1,92 +0,0 @@ -use std::{ - io::Error, - process::{Command, Output}, -}; - -lazy_static::lazy_static! { - static ref CNI_BIN_DIR: String = - std::env::var("CNI_BIN_DIR").expect("Environment variable CNI_BIN_DIR is not set"); - static ref CNI_TOOL: String = - std::env::var("CNI_TOOL").expect("Environment variable CNI_TOOL is not set"); -} - -#[inline(always)] -fn netns_path(netns: &str) -> String { - "/var/run/netns/".to_string() + netns -} - -pub(super) fn cni_add_bridge(netns: &str, bridge_network_name: &str) -> Result { - Command::new(CNI_TOOL.as_str()) - .arg("add") - .arg(bridge_network_name) - .arg(netns_path(netns)) - .env("CNI_PATH", CNI_BIN_DIR.as_str()) - .output() -} - -pub(super) fn cni_del_bridge(netns: &str, bridge_network_name: &str) -> Result { - Command::new(CNI_TOOL.as_str()) - .arg("del") - .arg(bridge_network_name) - .arg(netns_path(netns)) - .env("CNI_PATH", CNI_BIN_DIR.as_str()) - .output() -} - -/// THESE TESTS SHOULD BE RUN WITH ROOT PRIVILEGES -#[cfg(test)] -mod test { - use crate::{netns, util}; - use std::path::Path; - - use super::*; - - const CNI_DATA_DIR: &str = "/var/run/cni"; - const TEST_CNI_CONF_FILENAME: &str = "11-faasrstest.conflist"; - const TEST_NETWORK_NAME: &str = "faasrstest-cni-bridge"; - const TEST_BRIDGE_NAME: &str = "faasrstest0"; - const TEST_SUBNET: &str = "10.99.0.0/16"; - const CNI_CONF_DIR: &str = "/etc/cni/net.d"; - - fn init_test_net_fs() { - crate::util::init_net_fs( - Path::new(CNI_CONF_DIR), - TEST_CNI_CONF_FILENAME, - TEST_NETWORK_NAME, - TEST_BRIDGE_NAME, - TEST_SUBNET, - CNI_DATA_DIR, - ) - .unwrap() - } - - #[test] - #[ignore] - fn test_cni_resource() { - dotenv::dotenv().unwrap(); - env_logger::init_from_env(env_logger::Env::new().default_filter_or("trace")); - init_test_net_fs(); - let netns = util::netns_from_cid_and_cns("123456", "cns"); - - netns::create(&netns).unwrap(); - defer::defer!({ - let _ = netns::remove(&netns); - }); - - let result = cni_add_bridge(&netns, TEST_NETWORK_NAME); - log::debug!("add CNI result: {:?}", result); - assert!( - result.is_ok_and(|output| output.status.success()), - "Failed to add CNI" - ); - - defer::defer!({ - let result = cni_del_bridge(&netns, TEST_NETWORK_NAME); - log::debug!("del CNI result: {:?}", result); - assert!( - result.is_ok_and(|output| output.status.success()), - "Failed to delete CNI" - ); - }); - } -} diff --git a/crates/cni/src/lib.rs b/crates/cni/src/lib.rs deleted file mode 100644 index 5f1a82e..0000000 --- a/crates/cni/src/lib.rs +++ /dev/null @@ -1,91 +0,0 @@ -type Err = Box; - -use lazy_static::lazy_static; -use serde_json::Value; -use std::{fmt::Error, net::IpAddr, path::Path}; - -mod command; -mod netns; -mod util; -use command as cmd; - -lazy_static! { - static ref CNI_CONF_DIR: String = - std::env::var("CNI_CONF_DIR").expect("Environment variable CNI_CONF_DIR is not set"); -} - -// const NET_NS_PATH_FMT: &str = "/proc/{}/ns/net"; -const CNI_DATA_DIR: &str = "/var/run/cni"; -const DEFAULT_CNI_CONF_FILENAME: &str = "10-faasrs.conflist"; -const DEFAULT_NETWORK_NAME: &str = "faasrs-cni-bridge"; -const DEFAULT_BRIDGE_NAME: &str = "faasrs0"; -const DEFAULT_SUBNET: &str = "10.66.0.0/16"; -// const DEFAULT_IF_PREFIX: &str = "eth"; - -pub fn init_net_work() -> Result<(), Err> { - util::init_net_fs( - Path::new(CNI_CONF_DIR.as_str()), - DEFAULT_CNI_CONF_FILENAME, - DEFAULT_NETWORK_NAME, - DEFAULT_BRIDGE_NAME, - DEFAULT_SUBNET, - CNI_DATA_DIR, - ) -} - -//TODO: 创建网络和删除网络的错误处理 -pub fn create_cni_network(cid: String, ns: String) -> Result { - let netns = util::netns_from_cid_and_cns(&cid, &ns); - let mut ip = String::new(); - - netns::create(&netns)?; - - let output = cmd::cni_add_bridge(netns.as_str(), DEFAULT_NETWORK_NAME); - - match output { - Ok(output) => { - if !output.status.success() { - return Err(Box::new(Error)); - } - let stdout = String::from_utf8_lossy(&output.stdout); - let json: Value = match serde_json::from_str(&stdout) { - Ok(json) => json, - Err(e) => { - return Err(Box::new(e)); - } - }; - if let Some(ips) = json.get("ips").and_then(|ips| ips.as_array()) { - if let Some(first_ip) = ips - .first() - .and_then(|ip| ip.get("address")) - .and_then(|addr| addr.as_str()) - { - ip = first_ip.to_string(); - } - } - } - Err(e) => { - return Err(Box::new(e)); - } - } - - Ok(ip) -} - -pub fn delete_cni_network(ns: &str, cid: &str) { - let netns = util::netns_from_cid_and_cns(cid, ns); - - let _ = cmd::cni_del_bridge(&netns, DEFAULT_NETWORK_NAME); - let _ = netns::remove(&netns); -} - -#[allow(unused)] -fn cni_gateway() -> Result { - let ip: IpAddr = DEFAULT_SUBNET.parse().unwrap(); - if let IpAddr::V4(ip) = ip { - let octets = &mut ip.octets(); - octets[3] = 1; - return Ok(ip.to_string()); - } - Err(Box::new(Error)) -} diff --git a/crates/cni/src/netns.rs b/crates/cni/src/netns.rs deleted file mode 100644 index 766ac35..0000000 --- a/crates/cni/src/netns.rs +++ /dev/null @@ -1,32 +0,0 @@ -use netns_rs::{Error, NetNs}; - -pub(super) fn create(netns: &str) -> Result { - NetNs::new(netns) -} - -pub(super) fn remove(netns: &str) -> Result<(), Error> { - match NetNs::get(netns) { - Ok(ns) => { - ns.remove()?; - Ok(()) - } - Err(e) => { - log::error!("Failed to get netns {}: {}", netns, e); - Err(e) - } - } -} - -/// THESE TESTS SHOULD BE RUN WITH ROOT PRIVILEGES -#[cfg(test)] -mod test { - use super::*; - - #[test] - #[ignore] - fn test_create_and_remove() { - let netns_name = "test_netns"; - create(netns_name).unwrap(); - assert!(remove(netns_name).is_ok()); - } -} diff --git a/crates/faas-containerd/Cargo.toml b/crates/faas-containerd/Cargo.toml new file mode 100644 index 0000000..5b0bf0b --- /dev/null +++ b/crates/faas-containerd/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "faas-containerd" +version = "0.1.0" +edition = "2024" + +[dependencies] +containerd-client = "0.8" +futures = "0.3" +tokio = { version = "1", features = ["full"] } +tonic = "0.12" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +scopeguard = "1.2.0" +log = "0.4" +env_logger = "0.10" +prost-types = "0.13.4" +oci-spec = "0.6" +sha2 = "0.10" +hex = "0.4" +my-workspace-hack = { version = "0.1", path = "../my-workspace-hack" } +gateway = { path = "../gateway" } +handlebars = "4.1.0" +tokio-util = { version = "0.7.15", features = ["full"] } +container_image_dist_ref = "0.3.0" +url = "2.4" +chrono = { version = "0.4", features = ["serde"] } +dotenv = "0.15.0" +derive_more = { version = "2", features = ["full"] } +cidr = "0.3.1" +async-safe-defer = "0.1.2" +actix-http = "*" +netns-rs = "0.1.0" +sled = "0.34.7" + +[dev-dependencies] +actix-web = "4.11.0" diff --git a/crates/faas-containerd/src/consts.rs b/crates/faas-containerd/src/consts.rs new file mode 100644 index 0000000..44e0a65 --- /dev/null +++ b/crates/faas-containerd/src/consts.rs @@ -0,0 +1,15 @@ +#[allow(unused)] +pub const DEFAULT_FUNCTION_NAMESPACE: &str = "faasrs-default"; + +#[allow(unused)] +pub const DEFAULT_SNAPSHOTTER: &str = "overlayfs"; + +pub const DEFAULT_CTRD_SOCK: &str = "/run/containerd/containerd.sock"; + +pub const DEFAULT_FAASDRS_DATA_DIR: &str = "/var/lib/faasdrs"; + +// 定义版本的常量 +pub const VERSION_MAJOR: u32 = 1; +pub const VERSION_MINOR: u32 = 1; +pub const VERSION_PATCH: u32 = 0; +pub const VERSION_DEV: &str = ""; // 对应开发分支 diff --git a/crates/faas-containerd/src/impls/cni/cni_impl.rs b/crates/faas-containerd/src/impls/cni/cni_impl.rs new file mode 100644 index 0000000..7a9d19b --- /dev/null +++ b/crates/faas-containerd/src/impls/cni/cni_impl.rs @@ -0,0 +1,148 @@ +type Err = Box; + +use derive_more::{Display, Error}; +use netns_rs::NetNs; +use scopeguard::{ScopeGuard, guard}; +use serde_json::Value; +use std::{fmt::Error, net::IpAddr, path::Path, sync::LazyLock}; + +use super::{Endpoint, command as cmd, util}; + +static CNI_CONF_DIR: LazyLock = LazyLock::new(|| { + std::env::var("CNI_CONF_DIR").unwrap_or_else(|_| "/etc/cni/net.d".to_string()) +}); + +const CNI_DATA_DIR: &str = "/var/run/cni"; +const DEFAULT_CNI_CONF_FILENAME: &str = "10-faasrs.conflist"; +const DEFAULT_NETWORK_NAME: &str = "faasrs-cni-bridge"; +const DEFAULT_BRIDGE_NAME: &str = "faasrs0"; +const DEFAULT_SUBNET: &str = "10.66.0.0/16"; + +pub fn init_cni_network() -> Result<(), Err> { + util::init_net_fs( + Path::new(CNI_CONF_DIR.as_str()), + DEFAULT_CNI_CONF_FILENAME, + DEFAULT_NETWORK_NAME, + DEFAULT_BRIDGE_NAME, + DEFAULT_SUBNET, + CNI_DATA_DIR, + ) +} + +#[derive(Debug, Display, Error)] +pub struct NetworkError { + pub msg: String, +} + +//TODO: 创建网络和删除网络的错误处理 +pub fn create_cni_network(endpoint: &Endpoint) -> Result<(cidr::IpInet, NetNs), NetworkError> { + let net_ns = guard( + NetNs::new(endpoint.to_string()).map_err(|e| NetworkError { + msg: format!("Failed to create netns: {}", e), + })?, + |ns| ns.remove().unwrap(), + ); + + let output = cmd::cni_add_bridge(net_ns.path(), DEFAULT_NETWORK_NAME); + + match output { + Ok(output) => { + if !output.status.success() { + return Err(NetworkError { + msg: format!( + "Failed to add CNI bridge: {}", + String::from_utf8_lossy(&output.stderr) + ), + }); + } + let stdout = String::from_utf8_lossy(&output.stdout); + let mut json: Value = match serde_json::from_str(&stdout) { + Ok(json) => json, + Err(e) => { + log::error!("Failed to parse JSON: {}", e); + return Err(NetworkError { + msg: format!("Failed to parse JSON: {}", e), + }); + } + }; + log::trace!("CNI add bridge output: {:?}", json); + if let serde_json::Value::Array(ips) = json["ips"].take() { + let mut ip_list = Vec::new(); + for mut ip in ips { + if let serde_json::Value::String(ip_str) = ip["address"].take() { + let ipcidr = ip_str.parse::().map_err(|e| { + log::error!("Failed to parse IP address: {}", e); + NetworkError { msg: e.to_string() } + })?; + ip_list.push(ipcidr); + } + } + if ip_list.is_empty() { + return Err(NetworkError { + msg: "No IP address found in CNI output".to_string(), + }); + } + if ip_list.len() > 1 { + log::warn!("Multiple IP addresses found in CNI output: {:?}", ip_list); + } + log::trace!("CNI network created with IP: {:?}", ip_list[0]); + Ok((ip_list[0], ScopeGuard::into_inner(net_ns))) + } else { + log::error!("Invalid JSON format: {:?}", json); + Err(NetworkError { + msg: "Invalid JSON format".to_string(), + }) + } + } + Err(e) => { + log::error!("Failed to add CNI bridge: {}", e); + Err(NetworkError { + msg: format!("Failed to add CNI bridge: {}", e), + }) + } + } +} + +pub fn delete_cni_network(endpoint: Endpoint) -> Result<(), NetworkError> { + match NetNs::get(endpoint.to_string()) { + Ok(ns) => { + let e1 = cmd::cni_del_bridge(ns.path(), DEFAULT_NETWORK_NAME); + let e2 = ns.remove(); + if e1.is_err() || e2.is_err() { + let err = format!( + "NetNS exists, but failed to delete CNI network, cni bridge: {:?}, netns: {:?}", + e1, e2 + ); + log::error!("{}", err); + return Err(NetworkError { msg: err }); + } + Ok(()) + } + Err(e) => { + let msg = format!("Failed to get netns {}: {}", endpoint, e); + log::warn!("{}", msg); + Err(NetworkError { msg }) + } + } +} + +#[inline] +pub fn check_network_exists(addr: IpAddr) -> bool { + util::CNI_CONFIG_FILE + .get() + .unwrap() + .data_dir + .join(addr.to_string()) + .exists() +} + +#[allow(unused)] +fn cni_gateway() -> Result { + let ip: IpAddr = DEFAULT_SUBNET.parse().unwrap(); + if let IpAddr::V4(ip) = ip { + let octets = &mut ip.octets(); + octets[3] = 1; + return Ok(ip.to_string()); + } + Err(Box::new(Error)) +} diff --git a/crates/faas-containerd/src/impls/cni/command.rs b/crates/faas-containerd/src/impls/cni/command.rs new file mode 100644 index 0000000..f5fe2d6 --- /dev/null +++ b/crates/faas-containerd/src/impls/cni/command.rs @@ -0,0 +1,94 @@ +use std::{ + io::Error, + path::Path, + process::{Command, Output}, + sync::LazyLock, +}; + +static CNI_BIN_DIR: LazyLock = + LazyLock::new(|| std::env::var("CNI_BIN_DIR").unwrap_or_else(|_| "/opt/cni/bin".to_string())); +static CNI_TOOL: LazyLock = + LazyLock::new(|| std::env::var("CNI_TOOL").unwrap_or_else(|_| "cni-tool".to_string())); + +pub(super) fn cni_add_bridge( + netns_path: &Path, + bridge_network_name: &str, +) -> Result { + Command::new(CNI_TOOL.as_str()) + .arg("add") + .arg(bridge_network_name) + .arg(netns_path) + .env("CNI_PATH", CNI_BIN_DIR.as_str()) + .output() +} + +pub(super) fn cni_del_bridge( + netns_path: &Path, + bridge_network_name: &str, +) -> Result { + Command::new(CNI_TOOL.as_str()) + .arg("del") + .arg(bridge_network_name) + .arg(netns_path) + .env("CNI_PATH", CNI_BIN_DIR.as_str()) + .output() +} + +// /// THESE TESTS SHOULD BE RUN WITH ROOT PRIVILEGES +// #[cfg(test)] +// mod test { +// use crate::impls::cni::util; +// use std::path::Path; + +// use super::*; + +// const CNI_DATA_DIR: &str = "/var/run/cni"; +// const TEST_CNI_CONF_FILENAME: &str = "11-faasrstest.conflist"; +// const TEST_NETWORK_NAME: &str = "faasrstest-cni-bridge"; +// const TEST_BRIDGE_NAME: &str = "faasrstest0"; +// const TEST_SUBNET: &str = "10.99.0.0/16"; +// const CNI_CONF_DIR: &str = "/etc/cni/net.d"; + +// fn init_test_net_fs() { +// util::init_net_fs( +// Path::new(CNI_CONF_DIR), +// TEST_CNI_CONF_FILENAME, +// TEST_NETWORK_NAME, +// TEST_BRIDGE_NAME, +// TEST_SUBNET, +// CNI_DATA_DIR, +// ) +// .unwrap() +// } + +// #[test] +// #[ignore] +// fn test_cni_resource() { +// dotenv::dotenv().unwrap(); +// env_logger::init_from_env(env_logger::Env::new().default_filter_or("trace")); +// init_test_net_fs(); +// let netns = util::netns_from_cid_and_cns("123456", "cns"); + +// let net_namespace = netns::create(&netns).unwrap(); +// defer::defer!({ +// let _ = netns::remove(&netns); +// }); +// net_namespace.path() + +// let result = cni_add_bridge(&netns, TEST_NETWORK_NAME); +// log::debug!("add CNI result: {:?}", result); +// assert!( +// result.is_ok_and(|output| output.status.success()), +// "Failed to add CNI" +// ); + +// defer::defer!({ +// let result = cni_del_bridge(&netns, TEST_NETWORK_NAME); +// log::debug!("del CNI result: {:?}", result); +// assert!( +// result.is_ok_and(|output| output.status.success()), +// "Failed to delete CNI" +// ); +// }); +// } +// } diff --git a/crates/faas-containerd/src/impls/cni/mod.rs b/crates/faas-containerd/src/impls/cni/mod.rs new file mode 100644 index 0000000..abf234e --- /dev/null +++ b/crates/faas-containerd/src/impls/cni/mod.rs @@ -0,0 +1,55 @@ +use crate::consts; + +pub mod cni_impl; +mod command; +mod util; + +pub use cni_impl::init_cni_network; +use gateway::types::function::Query; + +#[derive(Debug, Clone, Hash, Eq, PartialEq)] +pub struct Endpoint { + pub service: String, + pub namespace: String, +} + +impl Endpoint { + pub fn new(service: &str, namespace: &str) -> Self { + Self { + service: service.to_string(), + namespace: namespace.to_string(), + } + } +} + +/// format `-` as netns name, also the identifier of each function +impl std::fmt::Display for Endpoint { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}-{}", self.namespace, self.service) + } +} + +impl From for Endpoint { + fn from(query: Query) -> Self { + Self { + service: query.service, + namespace: query + .namespace + .unwrap_or(consts::DEFAULT_FUNCTION_NAMESPACE.to_string()), + } + } +} + +#[cfg(test)] +mod tests { + + #[test] + fn test_ip_parsing() { + let raw_ip = "10.42.0.48/16"; + let ipcidr = raw_ip.parse::().unwrap(); + assert_eq!( + ipcidr.address(), + std::net::IpAddr::V4(std::net::Ipv4Addr::new(10, 42, 0, 48)) + ); + } +} diff --git a/crates/cni/src/util.rs b/crates/faas-containerd/src/impls/cni/util.rs similarity index 78% rename from crates/cni/src/util.rs rename to crates/faas-containerd/src/impls/cni/util.rs index 6dac047..b06165c 100644 --- a/crates/cni/src/util.rs +++ b/crates/faas-containerd/src/impls/cni/util.rs @@ -1,14 +1,15 @@ use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; +use std::sync::OnceLock; -static mut CNI_CONFIG_FILE: Option = None; +pub static CNI_CONFIG_FILE: OnceLock = OnceLock::new(); -/// Generate "cns-cid" -#[inline(always)] -pub fn netns_from_cid_and_cns(cid: &str, cns: &str) -> String { - format!("{}-{}", cns, cid) -} +// /// Generate "cns-cid" +// #[inline(always)] +// pub fn netns_name_from_cid_ns(cid: &str, cns: &str) -> String { +// format!("{}-{}", cns, cid) +// } pub fn init_net_fs( conf_dir: &Path, @@ -19,9 +20,9 @@ pub fn init_net_fs( data_dir: &str, ) -> Result<(), Box> { let conf_file = CniConfFile::new(conf_dir, conf_filename, net_name, bridge, subnet, data_dir)?; - unsafe { - CNI_CONFIG_FILE = Some(conf_file); - } + CNI_CONFIG_FILE + .set(conf_file) + .map_err(|_| "Failed to set CNI_CONFIG_FILE")?; Ok(()) } @@ -56,9 +57,10 @@ fn cni_conf(name: &str, bridge: &str, subnet: &str, data_dir: &str) -> String { ) } -struct CniConfFile { - conf_dir: PathBuf, - conf_filename: String, +pub(super) struct CniConfFile { + pub conf_dir: PathBuf, + pub conf_filename: String, + pub data_dir: PathBuf, } impl CniConfFile { @@ -80,9 +82,11 @@ impl CniConfFile { let net_config = conf_dir.join(conf_filename); File::create(&net_config)? .write_all(cni_conf(net_name, bridge, subnet, data_dir).as_bytes())?; + let data_dir = PathBuf::from(data_dir); Ok(Self { conf_dir: conf_dir.to_path_buf(), conf_filename: conf_filename.to_string(), + data_dir: data_dir.join(net_name), }) } } diff --git a/crates/faas-containerd/src/impls/container.rs b/crates/faas-containerd/src/impls/container.rs new file mode 100644 index 0000000..eaaef45 --- /dev/null +++ b/crates/faas-containerd/src/impls/container.rs @@ -0,0 +1,125 @@ +use containerd_client::{ + services::v1::{Container, DeleteContainerRequest, GetContainerRequest, ListContainersRequest}, + with_namespace, +}; + +use derive_more::Display; + +use containerd_client::services::v1::container::Runtime; + +use super::{ContainerdService, backend, cni::Endpoint, function::ContainerStaticMetadata}; +use tonic::Request; + +#[derive(Debug, Display)] +pub enum ContainerError { + NotFound, + AlreadyExists, + Internal, +} + +impl ContainerdService { + /// 创建容器 + pub async fn create_container( + &self, + metadata: &ContainerStaticMetadata, + ) -> Result { + let container = Container { + id: metadata.endpoint.service.clone(), + image: metadata.image.clone(), + runtime: Some(Runtime { + name: "io.containerd.runc.v2".to_string(), + options: None, + }), + spec: Some(backend().get_spec(metadata).await.map_err(|_| { + log::error!("Failed to get spec"); + ContainerError::Internal + })?), + snapshotter: crate::consts::DEFAULT_SNAPSHOTTER.to_string(), + snapshot_key: metadata.endpoint.service.clone(), + ..Default::default() + }; + + let mut cc = backend().client.containers(); + let req = containerd_client::services::v1::CreateContainerRequest { + container: Some(container), + }; + + let resp = cc + .create(with_namespace!(req, metadata.endpoint.namespace)) + .await + .map_err(|e| { + log::error!("Failed to create container: {}", e); + ContainerError::Internal + })?; + + resp.into_inner().container.ok_or(ContainerError::Internal) + } + + /// 删除容器 + pub async fn delete_container(&self, endpoint: &Endpoint) -> Result<(), ContainerError> { + let Endpoint { + service: cid, + namespace: ns, + } = endpoint; + let mut cc = self.client.containers(); + + let delete_request = DeleteContainerRequest { id: cid.clone() }; + + cc.delete(with_namespace!(delete_request, ns)) + .await + .map_err(|e| { + log::error!("Failed to delete container: {}", e); + ContainerError::Internal + }) + .map(|_| ()) + } + + /// 根据查询条件加载容器参数 + pub async fn load_container(&self, endpoint: &Endpoint) -> Result { + let mut cc = self.client.containers(); + + let request = GetContainerRequest { + id: endpoint.service.clone(), + }; + + let resp = cc + .get(with_namespace!(request, endpoint.namespace)) + .await + .map_err(|e| { + log::error!("Failed to list containers: {}", e); + ContainerError::Internal + })?; + + resp.into_inner().container.ok_or(ContainerError::NotFound) + } + + /// 获取容器列表 + pub async fn list_container(&self, namespace: &str) -> Result, ContainerError> { + let mut cc = self.client.containers(); + + let request = ListContainersRequest { + ..Default::default() + }; + + let resp = cc + .list(with_namespace!(request, namespace)) + .await + .map_err(|e| { + log::error!("Failed to list containers: {}", e); + ContainerError::Internal + })?; + + Ok(resp.into_inner().containers) + } + + /// 不儿,这也要单独一个函数? + #[deprecated] + pub async fn list_container_into_string( + &self, + ns: &str, + ) -> Result, ContainerError> { + self.list_container(ns) + .await + .map(|ctrs| ctrs.into_iter().map(|ctr| ctr.id).collect()) + } +} diff --git a/crates/faas-containerd/src/impls/error.rs b/crates/faas-containerd/src/impls/error.rs new file mode 100644 index 0000000..4532ecd --- /dev/null +++ b/crates/faas-containerd/src/impls/error.rs @@ -0,0 +1,17 @@ +use derive_more::derive::Display; +#[derive(Debug, Display)] +pub enum ContainerdError { + CreateContainerError(String), + CreateSnapshotError(String), + GetParentSnapshotError(String), + GenerateSpecError(String), + DeleteContainerError(String), + GetContainerListError(String), + KillTaskError(String), + DeleteTaskError(String), + WaitTaskError(String), + CreateTaskError(String), + StartTaskError(String), + #[allow(dead_code)] + OtherError, +} diff --git a/crates/faas-containerd/src/impls/function.rs b/crates/faas-containerd/src/impls/function.rs new file mode 100644 index 0000000..9e5da33 --- /dev/null +++ b/crates/faas-containerd/src/impls/function.rs @@ -0,0 +1,97 @@ +use gateway::types::function; + +use crate::consts; + +use super::cni::Endpoint; + +#[derive(Debug, Clone, Hash, Eq, PartialEq)] +pub struct ContainerStaticMetadata { + pub image: String, + pub endpoint: Endpoint, +} + +impl From for ContainerStaticMetadata { + fn from(info: function::Deployment) -> Self { + ContainerStaticMetadata { + image: info.image, + endpoint: Endpoint::new( + &info.service, + &info + .namespace + .unwrap_or(consts::DEFAULT_FUNCTION_NAMESPACE.to_string()), + ), + } + } +} + +// impl From for function::Query { +// fn from(metadata: ContainerStaticMetadata) -> Self { +// function::Query { +// service: metadata.container_id, +// namespace: Some(metadata.namespace), +// } +// } +// } + +// /// A function is a container instance with correct cni connected +// #[derive(Debug)] +// pub struct FunctionInstance { +// container: containerd_client::services::v1::Container, +// namespace: String, +// // ip addr inside cni +// // network: CNIEndpoint, +// // port: Vec, default use 8080 +// // manager: Weak, +// } + +// impl FunctionInstance { +// pub async fn new(metadata: ContainerStaticMetadata) -> Result { + +// Ok(Self { +// container, +// namespace: metadata.namespace, +// // network, +// }) +// } + +// pub async fn delete(&self) -> Result<(), ContainerdError> { +// let container_id = self.container.id.clone(); +// let namespace = self.namespace.clone(); + +// let kill_err = backend() +// .kill_task_with_timeout(&container_id, &namespace) +// .await +// .map_err(|e| { +// log::error!("Failed to kill task: {:?}", e); +// e +// }); + +// let del_ctr_err = backend() +// .delete_container(&container_id, &namespace) +// .await +// .map_err(|e| { +// log::error!("Failed to delete container: {:?}", e); +// e +// }); + +// let rm_snap_err = backend() +// .remove_snapshot(&container_id, &namespace) +// .await +// .map_err(|e| { +// log::error!("Failed to remove snapshot: {:?}", e); +// e +// }); +// if kill_err.is_ok() && del_ctr_err.is_ok() && rm_snap_err.is_ok() { +// Ok(()) +// } else { +// Err(ContainerdError::DeleteContainerError(format!( +// "{:?}, {:?}, {:?}", +// kill_err, del_ctr_err, rm_snap_err +// ))) +// } +// } + +// pub fn address(&self) -> IpAddr { +// self.network.address() +// } +// } diff --git a/crates/faas-containerd/src/impls/mod.rs b/crates/faas-containerd/src/impls/mod.rs new file mode 100644 index 0000000..4ca9b31 --- /dev/null +++ b/crates/faas-containerd/src/impls/mod.rs @@ -0,0 +1,30 @@ +pub mod cni; +pub mod container; +pub mod error; +pub mod function; +pub mod oci_image; +pub mod snapshot; +pub mod spec; +pub mod task; + +use std::sync::OnceLock; + +pub static __BACKEND: OnceLock = OnceLock::new(); + +pub(crate) fn backend() -> &'static ContainerdService { + __BACKEND.get().unwrap() +} + +/// TODO: Panic on failure, should be handled in a better way +pub async fn init_backend() { + let socket = + std::env::var("SOCKET_PATH").unwrap_or(crate::consts::DEFAULT_CTRD_SOCK.to_string()); + let client = containerd_client::Client::from_path(socket).await.unwrap(); + + __BACKEND.set(ContainerdService { client }).ok().unwrap(); + cni::init_cni_network().unwrap(); +} + +pub struct ContainerdService { + pub client: containerd_client::Client, +} diff --git a/crates/service/src/image_manager.rs b/crates/faas-containerd/src/impls/oci_image.rs similarity index 54% rename from crates/service/src/image_manager.rs rename to crates/faas-containerd/src/impls/oci_image.rs index 32c05d5..79665db 100644 --- a/crates/service/src/image_manager.rs +++ b/crates/faas-containerd/src/impls/oci_image.rs @@ -1,10 +1,7 @@ -use std::{ - collections::HashMap, - sync::{Arc, RwLock}, -}; +use super::ContainerdService; +use container_image_dist_ref::ImgRef; use containerd_client::{ - Client, services::v1::{GetImageRequest, ReadContentRequest, TransferOptions, TransferRequest}, to_any, tonic::Request, @@ -16,36 +13,265 @@ use containerd_client::{ }; use oci_spec::image::{Arch, ImageConfiguration, ImageIndex, ImageManifest, MediaType, Os}; -use crate::{containerd_manager::CLIENT, spec::DEFAULT_NAMESPACE}; +impl ContainerdService { + async fn get_image(&self, image_name: &str, ns: &str) -> Result<(), ImageError> { + let mut c = self.client.images(); + let req = GetImageRequest { + name: image_name.to_string(), + }; -type ImagesMap = Arc>>; -lazy_static::lazy_static! { - static ref GLOBAL_IMAGE_MAP: ImagesMap = Arc::new(RwLock::new(HashMap::new())); -} + let resp = match c.get(with_namespace!(req, ns)).await { + Ok(response) => response.into_inner(), + Err(e) => { + return Err(ImageError::ImageNotFound(format!( + "Failed to get image {}: {}", + image_name, e + ))); + } + }; + if resp.image.is_none() { + self.pull_image(image_name, ns).await?; + } + Ok(()) + } -#[derive(Debug, Clone)] -pub struct ImageRuntimeConfig { - pub env: Vec, - pub args: Vec, - pub ports: Vec, - pub cwd: String, -} + pub async fn pull_image(&self, image_name: &str, ns: &str) -> Result<(), ImageError> { + let ns = check_namespace(ns); + let namespace = ns.as_str(); -impl ImageRuntimeConfig { - pub fn new(env: Vec, args: Vec, ports: Vec, cwd: String) -> Self { - ImageRuntimeConfig { - env, - args, - ports, - cwd, + let mut trans_cli = self.client.transfer(); + let source = OciRegistry { + reference: image_name.to_string(), + resolver: Default::default(), + }; + + // 这里先写死linux amd64 + let platform = Platform { + os: "linux".to_string(), + architecture: "amd64".to_string(), + ..Default::default() + }; + + let dest = ImageStore { + name: image_name.to_string(), + platforms: vec![platform.clone()], + unpacks: vec![UnpackConfiguration { + platform: Some(platform), + ..Default::default() + }], + ..Default::default() + }; + + let anys = to_any(&source); + let anyd = to_any(&dest); + + let req = TransferRequest { + source: Some(anys), + destination: Some(anyd), + options: Some(TransferOptions { + ..Default::default() + }), + }; + + trans_cli + .transfer(with_namespace!(req, namespace)) + .await + .map_err(|e| { + log::error!("Failed to pull image: {}", e); + ImageError::ImagePullFailed(format!("Failed to pull image {}: {}", image_name, e)) + }) + .map(|resp| { + log::trace!("Pull image response: {:?}", resp); + }) + } + + pub async fn prepare_image( + &self, + image_name: &str, + ns: &str, + always_pull: bool, + ) -> Result<(), ImageError> { + let _ = ImgRef::new(image_name).map_err(|e| { + ImageError::ImageNotFound(format!("Invalid image name: {:?}", e.kind())) + })?; + if always_pull { + self.pull_image(image_name, ns).await + } else { + let namespace = check_namespace(ns); + let namespace = namespace.as_str(); + + self.get_image(image_name, namespace).await } } -} -impl Drop for ImageManager { - fn drop(&mut self) { - let mut map = GLOBAL_IMAGE_MAP.write().unwrap(); - map.clear(); + pub async fn image_config( + &self, + img_name: &str, + ns: &str, + ) -> Result { + let mut img_cli = self.client.images(); + + let req = GetImageRequest { + name: img_name.to_string(), + }; + let resp = match img_cli.get(with_namespace!(req, ns)).await { + Ok(response) => response.into_inner(), + Err(e) => { + return Err(ImageError::ImageNotFound(format!( + "Failed to get image {}: {}", + img_name, e + ))); + } + }; + + let img_dscr = resp.image.unwrap().target.unwrap(); + let media_type = MediaType::from(img_dscr.media_type.as_str()); + + let req = ReadContentRequest { + digest: img_dscr.digest, + ..Default::default() + }; + + let mut content_cli = self.client.content(); + + let mut inner = match content_cli.read(with_namespace!(req, ns)).await { + Ok(response) => response.into_inner(), + Err(e) => { + return Err(ImageError::ReadContentFailed(format!( + "Failed to read content of image {}: {}", + img_name, e + ))); + } + }; + + let resp = match inner.message().await { + Ok(response) => response.unwrap().data, + Err(e) => { + return Err(ImageError::ReadContentFailed(format!( + "Failed to get the inner content of image {}: {}", + img_name, e + ))); + } + }; + + drop(content_cli); + + match media_type { + MediaType::ImageIndex => self.handle_index(&resp, ns).await, + MediaType::ImageManifest => self.handle_manifest(&resp, ns).await, + MediaType::Other(val) + if val == "application/vnd.docker.distribution.manifest.list.v2+json" => + { + self.handle_index(&resp, ns).await + } + MediaType::Other(val) + if val == "application/vnd.docker.distribution.manifest.v2+json" => + { + self.handle_manifest(&resp, ns).await + } + _ => Err(ImageError::UnexpectedMediaType), + } + } + + async fn handle_index(&self, data: &[u8], ns: &str) -> Result { + let image_index: ImageIndex = ::serde_json::from_slice(data).map_err(|e| { + ImageError::DeserializationFailed(format!("Failed to parse JSON: {}", e)) + })?; + let img_manifest_dscr = image_index + .manifests() + .iter() + .find(|manifest_entry| match manifest_entry.platform() { + Some(p) => { + #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] + { + matches!(p.architecture(), &Arch::Amd64) && matches!(p.os(), &Os::Linux) + } + #[cfg(target_arch = "aarch64")] + { + matches!(p.architecture(), &Arch::ARM64) && matches!(p.os(), Os::Linux) + //&& matches!(p.variant().as_ref().map(|s| s.as_str()), Some("v8")) + } + } + None => false, + }) + .unwrap(); + + let req = ReadContentRequest { + digest: img_manifest_dscr.digest().to_owned(), + offset: 0, + size: 0, + }; + + let mut c = self.client.content(); + let mut inner = match c.read(with_namespace!(req, ns)).await { + Ok(response) => response.into_inner(), + Err(e) => { + return Err(ImageError::ReadContentFailed(format!( + "Failed to handler index : {}", + e + ))); + } + }; + + let resp = match inner.message().await { + Ok(response) => response.unwrap().data, + Err(e) => { + return Err(ImageError::ReadContentFailed(format!( + "Failed to handle index inner : {}", + e + ))); + } + }; + drop(c); + + self.handle_manifest(&resp, ns).await + } + + async fn handle_manifest( + &self, + data: &[u8], + ns: &str, + ) -> Result { + let img_manifest: ImageManifest = match serde_json::from_slice(data) { + Ok(manifest) => manifest, + Err(e) => { + return Err(ImageError::DeserializationFailed(format!( + "Failed to deserialize image manifest: {}", + e + ))); + } + }; + let img_manifest_dscr = img_manifest.config(); + + let req = ReadContentRequest { + digest: img_manifest_dscr.digest().to_owned(), + offset: 0, + size: 0, + }; + let mut c = self.client.content(); + + let mut inner = match c.read(with_namespace!(req, ns)).await { + Ok(response) => response.into_inner(), + Err(e) => { + return Err(ImageError::ReadContentFailed(format!( + "Failed to handler index : {}", + e + ))); + } + }; + + let resp = match inner.message().await { + Ok(response) => response.unwrap().data, + Err(e) => { + return Err(ImageError::ReadContentFailed(format!( + "Failed to handle index inner : {}", + e + ))); + } + }; + + serde_json::from_slice(&resp) + .map_err(|e| ImageError::DeserializationFailed(format!("Failed to parse JSON: {}", e))) } } @@ -81,346 +307,14 @@ impl std::fmt::Display for ImageError { } } -impl std::error::Error for ImageError {} - -#[derive(Debug)] -pub struct ImageManager; - -impl ImageManager { - async fn get_client() -> Arc { - CLIENT - .get() - .unwrap_or_else(|| panic!("Client not initialized, Please run init first")) - .clone() - } - - pub async fn prepare_image( - image_name: &str, - ns: &str, - always_pull: bool, - ) -> Result<(), ImageError> { - if always_pull { - Self::pull_image(image_name, ns).await?; - } else { - let namespace = check_namespace(ns); - let namespace = namespace.as_str(); - - Self::get_image(image_name, namespace).await?; - } - Self::save_img_config(image_name, ns).await - } - - async fn get_image(image_name: &str, ns: &str) -> Result<(), ImageError> { - let mut c = Self::get_client().await.images(); - let req = GetImageRequest { - name: image_name.to_string(), - }; - - let resp = match c.get(with_namespace!(req, ns)).await { - Ok(response) => response.into_inner(), - Err(e) => { - return Err(ImageError::ImageNotFound(format!( - "Failed to get image {}: {}", - image_name, e - ))); - } - }; - if resp.image.is_none() { - Self::pull_image(image_name, ns).await?; - } - Ok(()) - } - - pub async fn pull_image(image_name: &str, ns: &str) -> Result<(), ImageError> { - let client = Self::get_client().await; - let ns = check_namespace(ns); - let namespace = ns.as_str(); - - let mut c: containerd_client::services::v1::transfer_client::TransferClient< - tonic::transport::Channel, - > = client.transfer(); - let source = OciRegistry { - reference: image_name.to_string(), - resolver: Default::default(), - }; - - // 这里先写死linux amd64 - let platform = Platform { - os: "linux".to_string(), - architecture: "amd64".to_string(), - ..Default::default() - }; - - let dest = ImageStore { - name: image_name.to_string(), - platforms: vec![platform.clone()], - unpacks: vec![UnpackConfiguration { - platform: Some(platform), - ..Default::default() - }], - ..Default::default() - }; - - let anys = to_any(&source); - let anyd = to_any(&dest); - - let req = TransferRequest { - source: Some(anys), - destination: Some(anyd), - options: Some(TransferOptions { - ..Default::default() - }), - }; - - if let Err(e) = c.transfer(with_namespace!(req, namespace)).await { - return Err(ImageError::ImagePullFailed(format!( - "Failed to pull image {}: {}", - image_name, e - ))); - } - - Ok(()) - // Self::save_img_config(client, image_name, ns.as_str()).await - } - - pub async fn save_img_config(img_name: &str, ns: &str) -> Result<(), ImageError> { - let client = Self::get_client().await; - let mut c = client.images(); - - let req = GetImageRequest { - name: img_name.to_string(), - }; - let resp = match c.get(with_namespace!(req, ns)).await { - Ok(response) => response.into_inner(), - Err(e) => { - return Err(ImageError::ImageNotFound(format!( - "Failed to get image {}: {}", - img_name, e - ))); - } - }; - - let img_dscr = resp.image.unwrap().target.unwrap(); - let media_type = MediaType::from(img_dscr.media_type.as_str()); - - let req = ReadContentRequest { - digest: img_dscr.digest, - ..Default::default() - }; - - let mut c = client.content(); - - let mut inner = match c.read(with_namespace!(req, ns)).await { - Ok(response) => response.into_inner(), - Err(e) => { - return Err(ImageError::ReadContentFailed(format!( - "Failed to read content of image {}: {}", - img_name, e - ))); - } - }; - - let resp = match inner.message().await { - Ok(response) => response.unwrap().data, - Err(e) => { - return Err(ImageError::ReadContentFailed(format!( - "Failed to get the inner content of image {}: {}", - img_name, e - ))); - } - }; - - drop(c); - - let img_config = match media_type { - MediaType::ImageIndex => Self::handle_index(&resp, ns).await.unwrap(), - MediaType::ImageManifest => Self::handle_manifest(&resp, ns).await.unwrap(), - MediaType::Other(media_type) => match media_type.as_str() { - "application/vnd.docker.distribution.manifest.list.v2+json" => { - Self::handle_index(&resp, ns).await.unwrap() - } - "application/vnd.docker.distribution.manifest.v2+json" => { - Self::handle_manifest(&resp, ns).await.unwrap() - } - _ => { - return Err(ImageError::UnexpectedMediaType); - } - }, - _ => { - return Err(ImageError::UnexpectedMediaType); - } - }; - if img_config.is_none() { - return Err(ImageError::ImageConfigurationNotFound(format!( - "save_img_config: Image configuration not found for image {}", - img_name - ))); - } - let img_config = img_config.unwrap(); - Self::insert_image_config(img_name, img_config) - } - - async fn handle_index(data: &[u8], ns: &str) -> Result, ImageError> { - let image_index: ImageIndex = ::serde_json::from_slice(data).map_err(|e| { - ImageError::DeserializationFailed(format!("Failed to parse JSON: {}", e)) - })?; - let img_manifest_dscr = image_index - .manifests() - .iter() - .find(|manifest_entry| match manifest_entry.platform() { - Some(p) => { - #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] - { - matches!(p.architecture(), &Arch::Amd64) && matches!(p.os(), &Os::Linux) - } - #[cfg(target_arch = "aarch64")] - { - matches!(p.architecture(), &Arch::ARM64) && matches!(p.os(), Os::Linux) - //&& matches!(p.variant().as_ref().map(|s| s.as_str()), Some("v8")) - } - } - None => false, - }) - .unwrap(); - - let req = ReadContentRequest { - digest: img_manifest_dscr.digest().to_owned(), - offset: 0, - size: 0, - }; - - let mut c = Self::get_client().await.content(); - let mut inner = match c.read(with_namespace!(req, ns)).await { - Ok(response) => response.into_inner(), - Err(e) => { - return Err(ImageError::ReadContentFailed(format!( - "Failed to handler index : {}", - e - ))); - } - }; - - let resp = match inner.message().await { - Ok(response) => response.unwrap().data, - Err(e) => { - return Err(ImageError::ReadContentFailed(format!( - "Failed to handle index inner : {}", - e - ))); - } - }; - drop(c); - - Self::handle_manifest(&resp, ns).await - } - - async fn handle_manifest( - data: &[u8], - ns: &str, - ) -> Result, ImageError> { - let img_manifest: ImageManifest = match ::serde_json::from_slice(data) { - Ok(manifest) => manifest, - Err(e) => { - return Err(ImageError::DeserializationFailed(format!( - "Failed to deserialize image manifest: {}", - e - ))); - } - }; - let img_manifest_dscr = img_manifest.config(); - - let req = ReadContentRequest { - digest: img_manifest_dscr.digest().to_owned(), - offset: 0, - size: 0, - }; - let mut c = Self::get_client().await.content(); - - let mut inner = match c.read(with_namespace!(req, ns)).await { - Ok(response) => response.into_inner(), - Err(e) => { - return Err(ImageError::ReadContentFailed(format!( - "Failed to handler index : {}", - e - ))); - } - }; - - let resp = match inner.message().await { - Ok(response) => response.unwrap().data, - Err(e) => { - return Err(ImageError::ReadContentFailed(format!( - "Failed to handle index inner : {}", - e - ))); - } - }; - - Ok(::serde_json::from_slice(&resp).unwrap()) - } - - fn insert_image_config(image_name: &str, config: ImageConfiguration) -> Result<(), ImageError> { - let mut map = GLOBAL_IMAGE_MAP.write().unwrap(); - map.insert(image_name.to_string(), config); - Ok(()) - } - - pub fn get_image_config(image_name: &str) -> Result { - let map = GLOBAL_IMAGE_MAP.read().unwrap(); - if let Some(config) = map.get(image_name) { - Ok(config.clone()) - } else { - Err(ImageError::ImageConfigurationNotFound(format!( - "get_image_config: Image configuration not found for image {}", - image_name - ))) - } - } - - pub fn get_runtime_config(image_name: &str) -> Result { - let map = GLOBAL_IMAGE_MAP.read().unwrap(); - if let Some(config) = map.get(image_name) { - if let Some(config) = config.config() { - let env = config - .env() - .clone() - .expect("Failed to get environment variables"); - let args = config - .cmd() - .clone() - .expect("Failed to get command arguments"); - let ports = config.exposed_ports().clone().unwrap_or_else(|| { - log::warn!("Exposed ports not found, using default port 8080/tcp"); - vec!["8080/tcp".to_string()] - }); - let cwd = config.working_dir().clone().unwrap_or_else(|| { - log::warn!("Working directory not found, using default /"); - "/".to_string() - }); - Ok(ImageRuntimeConfig::new(env, args, ports, cwd)) - } else { - Err(ImageError::ImageConfigurationNotFound(format!( - "Image configuration is empty for image {}", - image_name - ))) - } - } else { - Err(ImageError::ImageConfigurationNotFound(format!( - "get_runtime_config: Image configuration not found for image {}", - image_name - ))) - } - } - - // 不用这个也能拉取镜像? - pub fn get_resolver() { - todo!() - } +// 不用这个也能拉取镜像? +pub fn get_resolver() { + todo!() } fn check_namespace(ns: &str) -> String { match ns { - "" => DEFAULT_NAMESPACE.to_string(), + "" => crate::consts::DEFAULT_FUNCTION_NAMESPACE.to_string(), _ => ns.to_string(), } } diff --git a/crates/faas-containerd/src/impls/snapshot.rs b/crates/faas-containerd/src/impls/snapshot.rs new file mode 100644 index 0000000..7526e46 --- /dev/null +++ b/crates/faas-containerd/src/impls/snapshot.rs @@ -0,0 +1,131 @@ +use containerd_client::{ + services::v1::snapshots::{MountsRequest, PrepareSnapshotRequest, RemoveSnapshotRequest}, + types::Mount, + with_namespace, +}; +use tonic::Request; + +use crate::impls::error::ContainerdError; + +use super::{ContainerdService, cni::Endpoint, function::ContainerStaticMetadata}; + +impl ContainerdService { + #[allow(unused)] + pub(super) async fn get_mounts( + &self, + cid: &str, + ns: &str, + ) -> Result, ContainerdError> { + let mut sc = self.client.snapshots(); + let req = MountsRequest { + snapshotter: crate::consts::DEFAULT_SNAPSHOTTER.to_string(), + key: cid.to_string(), + }; + let mounts = sc + .mounts(with_namespace!(req, ns)) + .await + .map_err(|e| { + log::error!("Failed to get mounts: {}", e); + ContainerdError::CreateTaskError(e.to_string()) + })? + .into_inner() + .mounts; + + Ok(mounts) + } + + pub async fn prepare_snapshot( + &self, + container: &ContainerStaticMetadata, + ) -> Result, ContainerdError> { + let parent_snapshot = self + .get_parent_snapshot(&container.image, &container.endpoint.namespace) + .await?; + self.do_prepare_snapshot( + &container.endpoint.service, + &container.endpoint.namespace, + parent_snapshot, + ) + .await + } + + async fn do_prepare_snapshot( + &self, + cid: &str, + ns: &str, + parent_snapshot: String, + ) -> Result, ContainerdError> { + let req = PrepareSnapshotRequest { + snapshotter: crate::consts::DEFAULT_SNAPSHOTTER.to_string(), + key: cid.to_string(), + parent: parent_snapshot, + ..Default::default() + }; + let mut client = self.client.snapshots(); + let resp = client + .prepare(with_namespace!(req, ns)) + .await + .map_err(|e| { + log::error!("Failed to prepare snapshot: {}", e); + ContainerdError::CreateSnapshotError(e.to_string()) + })?; + + log::trace!("Prepare snapshot response: {:?}", resp); + + Ok(resp.into_inner().mounts) + } + + async fn get_parent_snapshot( + &self, + image_name: &str, + namespace: &str, + ) -> Result { + use sha2::Digest; + let config = self + .image_config(image_name, namespace) + .await + .map_err(|e| { + log::error!("Failed to get image config: {}", e); + ContainerdError::GetParentSnapshotError(e.to_string()) + })?; + + if config.rootfs().diff_ids().is_empty() { + log::error!("Image config has no diff_ids for image: {}", image_name); + return Err(ContainerdError::GetParentSnapshotError( + "No diff_ids found in image config".to_string(), + )); + } + + let mut iter = config.rootfs().diff_ids().iter(); + let mut ret = iter + .next() + .map_or_else(String::new, |layer_digest| layer_digest.clone()); + + for layer_digest in iter { + let mut hasher = sha2::Sha256::new(); + hasher.update(ret.as_bytes()); + ret.push_str(&format!(",{}", layer_digest)); + hasher.update(" "); + hasher.update(layer_digest); + let digest = ::hex::encode(hasher.finalize()); + ret = format!("sha256:{digest}"); + } + Ok(ret) + } + + pub async fn remove_snapshot(&self, endpoint: &Endpoint) -> Result<(), ContainerdError> { + let mut sc = self.client.snapshots(); + let req = RemoveSnapshotRequest { + snapshotter: crate::consts::DEFAULT_SNAPSHOTTER.to_string(), + key: endpoint.service.clone(), + }; + sc.remove(with_namespace!(req, endpoint.namespace)) + .await + .map_err(|e| { + log::error!("Failed to delete snapshot: {}", e); + ContainerdError::DeleteContainerError(e.to_string()) + })?; + + Ok(()) + } +} diff --git a/crates/faas-containerd/src/impls/spec.rs b/crates/faas-containerd/src/impls/spec.rs new file mode 100644 index 0000000..9de071c --- /dev/null +++ b/crates/faas-containerd/src/impls/spec.rs @@ -0,0 +1,329 @@ +use super::{ + ContainerdService, cni::Endpoint, error::ContainerdError, function::ContainerStaticMetadata, +}; +use crate::consts::{VERSION_DEV, VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH}; +use oci_spec::{ + image::ImageConfiguration, + runtime::{ + Capability, LinuxBuilder, LinuxCapabilitiesBuilder, LinuxDeviceCgroupBuilder, + LinuxNamespaceBuilder, LinuxNamespaceType, LinuxResourcesBuilder, MountBuilder, + PosixRlimitBuilder, PosixRlimitType, ProcessBuilder, RootBuilder, Spec, SpecBuilder, + UserBuilder, + }, +}; +use std::path::Path; + +fn oci_version() -> String { + format!( + "{}.{}.{}{}", + VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_DEV + ) +} + +pub(super) fn generate_default_unix_spec( + ns: &str, + cid: &str, + runtime_config: &RuntimeConfig, +) -> Result { + let caps = [ + Capability::Chown, + Capability::DacOverride, + Capability::Fsetid, + Capability::Fowner, + Capability::Mknod, + Capability::NetRaw, + Capability::Setgid, + Capability::Setuid, + Capability::Setfcap, + Capability::Setpcap, + Capability::NetBindService, + Capability::SysChroot, + Capability::Kill, + Capability::AuditWrite, + ]; + let spec = SpecBuilder::default() + .version(oci_version()) + .root( + RootBuilder::default() + .path("rootfs") + .readonly(true) + .build() + .unwrap(), + ) + .process( + ProcessBuilder::default() + .cwd(runtime_config.cwd.clone()) + .no_new_privileges(true) + .user(UserBuilder::default().uid(0u32).gid(0u32).build().unwrap()) + .capabilities( + LinuxCapabilitiesBuilder::default() + .bounding(caps) + .permitted(caps) + .effective(caps) + .build() + .unwrap(), + ) + .rlimits([PosixRlimitBuilder::default() + .typ(PosixRlimitType::RlimitNofile) + .hard(1024u64) + .soft(1024u64) + .build() + .unwrap()]) + .args(runtime_config.args.clone()) + .env(runtime_config.env.clone()) + .build() + .unwrap(), + ) + .linux( + LinuxBuilder::default() + .masked_paths([ + "/proc/acpi".into(), + "/proc/asound".into(), + "/proc/kcore".into(), + "/proc/keys".into(), + "/proc/latency_stats".into(), + "/proc/timer_list".into(), + "/proc/timer_stats".into(), + "/proc/sched_debug".into(), + "/sys/firmware".into(), + "/proc/scsi".into(), + "/sys/devices/virtual/powercap".into(), + ]) + .readonly_paths([ + "/proc/bus".into(), + "/proc/fs".into(), + "/proc/irq".into(), + "/proc/sys".into(), + "/proc/sysrq-trigger".into(), + ]) + .cgroups_path(Path::new("/").join(ns).join(cid)) + .resources( + LinuxResourcesBuilder::default() + .devices([LinuxDeviceCgroupBuilder::default() + .allow(false) + .access("rwm") + .build() + .unwrap()]) + .build() + .unwrap(), + ) + .namespaces([ + LinuxNamespaceBuilder::default() + .typ(LinuxNamespaceType::Pid) + .build() + .unwrap(), + LinuxNamespaceBuilder::default() + .typ(LinuxNamespaceType::Ipc) + .build() + .unwrap(), + LinuxNamespaceBuilder::default() + .typ(LinuxNamespaceType::Uts) + .build() + .unwrap(), + LinuxNamespaceBuilder::default() + .typ(LinuxNamespaceType::Mount) + .build() + .unwrap(), + LinuxNamespaceBuilder::default() + .typ(LinuxNamespaceType::Network) + .path(format!("/var/run/netns/{}", Endpoint::new(cid, ns))) + .build() + .unwrap(), + ]) + .build() + .unwrap(), + ) + .mounts([ + MountBuilder::default() + .destination("/proc") + .typ("proc") + .source("proc") + .options(["nosuid".into(), "noexec".into(), "nodev".into()]) + .build() + .unwrap(), + MountBuilder::default() + .destination("/dev") + .typ("tmpfs") + .source("tmpfs") + .options([ + "nosuid".into(), + "strictatime".into(), + "mode=755".into(), + "size=65536k".into(), + ]) + .build() + .unwrap(), + MountBuilder::default() + .destination("/dev/pts") + .typ("devpts") + .source("devpts") + .options([ + "nosuid".into(), + "noexec".into(), + "newinstance".into(), + "ptmxmode=0666".into(), + "mode=0620".into(), + "gid=5".into(), + ]) + .build() + .unwrap(), + MountBuilder::default() + .destination("/dev/shm") + .typ("tmpfs") + .source("shm") + .options([ + "nosuid".into(), + "noexec".into(), + "nodev".into(), + "mode=1777".into(), + "size=65536k".into(), + ]) + .build() + .unwrap(), + MountBuilder::default() + .destination("/dev/mqueue") + .typ("mqueue") + .source("mqueue") + .options(["nosuid".into(), "noexec".into(), "nodev".into()]) + .build() + .unwrap(), + MountBuilder::default() + .destination("/sys") + .typ("sysfs") + .source("sysfs") + .options([ + "nosuid".into(), + "noexec".into(), + "nodev".into(), + "ro".into(), + ]) + .build() + .unwrap(), + MountBuilder::default() + .destination("/run") + .typ("tmpfs") + .source("tmpfs") + .options([ + "nosuid".into(), + "strictatime".into(), + "mode=755".into(), + "size=65536k".into(), + ]) + .build() + .unwrap(), + ]) + .build() + .map_err(|e| { + log::error!("Failed to generate spec: {}", e); + ContainerdError::GenerateSpecError(e.to_string()) + })?; + + Ok(spec) +} + +#[allow(unused)] +pub(super) fn with_vm_network(spec: &mut Spec) -> Result<(), ContainerdError> { + let mounts = spec + .mounts() + .as_ref() + .expect("Spec's 'Mounts' field should not be None"); + let mut new_mounts = mounts.clone(); + new_mounts.extend([ + MountBuilder::default() + .destination("/etc/resolv.conf") + .typ("bind") + .source("/etc/resolv.conf") + .options(["rbind".into(), "ro".into()]) + .build() + .map_err(|e| { + log::error!("Failed to build OCI (resolv.conf) Mount: {}", e); + ContainerdError::GenerateSpecError(e.to_string()) + })?, + MountBuilder::default() + .destination("/etc/hosts") + .typ("bind") + .source("/etc/hosts") + .options(["rbind".into(), "ro".into()]) + .build() + .map_err(|e| { + log::error!("Failed to build OCI (hosts) Mount: {}", e); + ContainerdError::GenerateSpecError(e.to_string()) + })?, + ]); + let _ = spec.set_mounts(Some(new_mounts)); + + Ok(()) +} + +#[derive(Debug, Clone)] +pub struct RuntimeConfig { + pub env: Vec, + pub args: Vec, + pub ports: Vec, + pub cwd: String, +} + +impl TryFrom for RuntimeConfig { + type Error = ContainerdError; + + fn try_from(value: ImageConfiguration) -> Result { + let conf_ref = value.config().as_ref(); + let config = conf_ref.ok_or(ContainerdError::GenerateSpecError( + "Image configuration not found".to_string(), + ))?; + + let env = config.env().clone().ok_or_else(|| { + ContainerdError::GenerateSpecError("Environment variables not found".to_string()) + })?; + let args = config.cmd().clone().ok_or_else(|| { + ContainerdError::GenerateSpecError("Command arguments not found".to_string()) + })?; + let ports = config.exposed_ports().clone().unwrap_or_else(|| { + log::warn!("Exposed ports not found, using default port 8080/tcp"); + vec!["8080/tcp".to_string()] + }); + let cwd = config.working_dir().clone().unwrap_or_else(|| { + log::warn!("Working directory not found, using default /"); + "/".to_string() + }); + Ok(RuntimeConfig { + env, + args, + ports, + cwd, + }) + } +} + +impl ContainerdService { + pub async fn get_spec( + &self, + metadata: &ContainerStaticMetadata, + ) -> Result { + let image_conf = self + .image_config(&metadata.image, &metadata.endpoint.namespace) + .await + .map_err(|e| { + log::error!("Failed to get image config: {}", e); + ContainerdError::GenerateSpecError(e.to_string()) + })?; + + let rt_conf = RuntimeConfig::try_from(image_conf)?; + + let spec = generate_default_unix_spec( + &metadata.endpoint.namespace, + &metadata.endpoint.service, + &rt_conf, + )?; + let spec_json = serde_json::to_string(&spec).map_err(|e| { + log::error!("Failed to serialize spec to JSON: {}", e); + ContainerdError::GenerateSpecError(e.to_string()) + })?; + let any_spec = prost_types::Any { + type_url: "types.containerd.io/opencontainers/runtime-spec/1/Spec".to_string(), + value: spec_json.into_bytes(), + }; + + Ok(any_spec) + } +} diff --git a/crates/faas-containerd/src/impls/task.rs b/crates/faas-containerd/src/impls/task.rs new file mode 100644 index 0000000..128fee1 --- /dev/null +++ b/crates/faas-containerd/src/impls/task.rs @@ -0,0 +1,210 @@ +use std::time::Duration; + +use containerd_client::{ + services::v1::{ + CreateTaskRequest, DeleteTaskRequest, GetRequest, KillRequest, ListTasksRequest, + ListTasksResponse, StartRequest, WaitRequest, WaitResponse, + }, + types::{Mount, v1::Process}, + with_namespace, +}; +use derive_more::Display; +use gateway::handlers::function::{DeleteError, DeployError}; +use tonic::Request; + +use super::{ContainerdService, cni::Endpoint}; + +#[derive(Debug, Clone, Hash, Eq, PartialEq, Display)] +pub enum TaskError { + NotFound, + AlreadyExists, + InvalidArgument, + // PermissionDenied, + Internal(String), +} + +impl From for TaskError { + fn from(status: tonic::Status) -> Self { + use tonic::Code::*; + match status.code() { + NotFound => TaskError::NotFound, + AlreadyExists => TaskError::AlreadyExists, + InvalidArgument => TaskError::InvalidArgument, + // PermissionDenied => TaskError::PermissionDenied, + _ => TaskError::Internal(status.message().to_string()), + } + } +} + +impl From for DeployError { + fn from(e: TaskError) -> DeployError { + match e { + TaskError::InvalidArgument => DeployError::Invalid(e.to_string()), + _ => DeployError::InternalError(e.to_string()), + } + } +} + +impl From for DeleteError { + fn from(e: TaskError) -> DeleteError { + log::trace!("DeleteTaskError: {:?}", e); + match e { + TaskError::NotFound => DeleteError::NotFound(e.to_string()), + TaskError::InvalidArgument => DeleteError::Invalid(e.to_string()), + _ => DeleteError::Internal(e.to_string()), + } + } +} + +impl ContainerdService { + /// 创建并启动任务 + pub async fn new_task(&self, mounts: Vec, endpoint: &Endpoint) -> Result<(), TaskError> { + let Endpoint { + service: cid, + namespace: ns, + } = endpoint; + // let mounts = self.get_mounts(cid, ns).await?; + self.do_create_task(cid, ns, mounts).await?; + self.do_start_task(cid, ns).await?; + Ok(()) + } + + async fn do_start_task(&self, cid: &str, ns: &str) -> Result<(), TaskError> { + let mut c: containerd_client::services::v1::tasks_client::TasksClient< + tonic::transport::Channel, + > = self.client.tasks(); + let req = StartRequest { + container_id: cid.to_string(), + ..Default::default() + }; + let resp = c.start(with_namespace!(req, ns)).await?; + log::debug!("Task: {:?} started", cid); + log::trace!("Task start response: {:?}", resp); + + Ok(()) + } + + async fn do_create_task( + &self, + cid: &str, + ns: &str, + rootfs: Vec, + ) -> Result<(), TaskError> { + let mut tc = self.client.tasks(); + let create_request = CreateTaskRequest { + container_id: cid.to_string(), + rootfs, + ..Default::default() + }; + let _resp = tc.create(with_namespace!(create_request, ns)).await?; + + Ok(()) + } + + pub async fn get_task(&self, endpoint: &Endpoint) -> Result { + let Endpoint { + service: cid, + namespace: ns, + } = endpoint; + let mut tc = self.client.tasks(); + + let req = GetRequest { + container_id: cid.clone(), + ..Default::default() + }; + + let resp = tc.get(with_namespace!(req, ns)).await?; + + let task = resp.into_inner().process.ok_or(TaskError::NotFound)?; + + Ok(task) + } + + #[allow(dead_code)] + async fn list_task_by_cid(&self, cid: &str, ns: &str) -> Result { + let mut c = self.client.tasks(); + let request = ListTasksRequest { + filter: format!("container=={}", cid), + }; + let response = c.list(with_namespace!(request, ns)).await?.into_inner(); + Ok(response) + } + + async fn do_kill_task(&self, cid: &str, ns: &str) -> Result<(), TaskError> { + let mut c = self.client.tasks(); + let kill_request = KillRequest { + container_id: cid.to_string(), + signal: 15, + all: true, + ..Default::default() + }; + c.kill(with_namespace!(kill_request, ns)).await?; + Ok(()) + } + + async fn do_kill_task_force(&self, cid: &str, ns: &str) -> Result<(), TaskError> { + let mut c = self.client.tasks(); + let kill_request = KillRequest { + container_id: cid.to_string(), + signal: 9, + all: true, + ..Default::default() + }; + c.kill(with_namespace!(kill_request, ns)).await?; + Ok(()) + } + + async fn do_delete_task(&self, cid: &str, ns: &str) -> Result<(), TaskError> { + let mut c = self.client.tasks(); + let delete_request = DeleteTaskRequest { + container_id: cid.to_string(), + }; + c.delete(with_namespace!(delete_request, ns)).await?; + Ok(()) + } + + async fn do_wait_task(&self, cid: &str, ns: &str) -> Result { + let mut c = self.client.tasks(); + let wait_request = WaitRequest { + container_id: cid.to_string(), + ..Default::default() + }; + let resp = c + .wait(with_namespace!(wait_request, ns)) + .await? + .into_inner(); + Ok(resp) + } + + /// 杀死并删除任务 + pub async fn kill_task_with_timeout(&self, endpoint: &Endpoint) -> Result<(), TaskError> { + let Endpoint { + service: cid, + namespace: ns, + } = endpoint; + let kill_timeout = Duration::from_secs(5); + let wait_future = self.do_wait_task(cid, ns); + self.do_kill_task(cid, ns).await?; + match tokio::time::timeout(kill_timeout, wait_future).await { + Ok(Ok(_)) => { + // 正常退出,尝试删除任务 + self.do_delete_task(cid, ns).await?; + } + Ok(Err(e)) => { + // wait 报错 + log::error!("Error while waiting for task {}: {:?}", cid, e); + return Err(e); + } + Err(_) => { + // 超时,强制 kill + log::warn!("Task {} did not exit in time, sending SIGKILL", cid); + self.do_kill_task_force(cid, ns).await?; + // 尝试删除任务 + if let Err(e) = self.do_delete_task(cid, ns).await { + log::error!("Failed to delete task {} after SIGKILL: {:?}", cid, e); + } + } + } + Ok(()) + } +} diff --git a/crates/faas-containerd/src/lib.rs b/crates/faas-containerd/src/lib.rs new file mode 100644 index 0000000..bf1184c --- /dev/null +++ b/crates/faas-containerd/src/lib.rs @@ -0,0 +1,8 @@ +#![feature(ip_from)] +#![feature(slice_as_array)] +pub mod consts; +pub mod impls; +pub mod provider; +pub mod systemd; + +pub use impls::init_backend; diff --git a/crates/faas-containerd/src/main.rs b/crates/faas-containerd/src/main.rs new file mode 100644 index 0000000..3aca650 --- /dev/null +++ b/crates/faas-containerd/src/main.rs @@ -0,0 +1,36 @@ +use faas_containerd::consts::DEFAULT_FAASDRS_DATA_DIR; +use tokio::signal::unix::{SignalKind, signal}; + +#[tokio::main] +async fn main() -> std::io::Result<()> { + dotenv::dotenv().ok(); + env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); + faas_containerd::init_backend().await; + let provider = faas_containerd::provider::ContainerdProvider::new(DEFAULT_FAASDRS_DATA_DIR); + + // leave for shutdown containers (stop tasks) + let _handle = provider.clone(); + + tokio::spawn(async move { + log::info!("Setting up signal handlers for graceful shutdown"); + let mut sigint = signal(SignalKind::interrupt()).unwrap(); + let mut sigterm = signal(SignalKind::terminate()).unwrap(); + let mut sigquit = signal(SignalKind::quit()).unwrap(); + tokio::select! { + _ = sigint.recv() => log::info!("SIGINT received, starting graceful shutdown..."), + _ = sigterm.recv() => log::info!("SIGTERM received, starting graceful shutdown..."), + _ = sigquit.recv() => log::info!("SIGQUIT received, starting graceful shutdown..."), + } + // for (_q, ctr) in handle.ctr_instance_map.lock().await.drain() { + // let _ = ctr.delete().await; + // } + log::info!("Successfully shutdown all containers"); + }); + + gateway::bootstrap::serve(provider) + .unwrap_or_else(|e| { + log::error!("Failed to start server: {}", e); + std::process::exit(1); + }) + .await +} diff --git a/crates/faas-containerd/src/provider/function/delete.rs b/crates/faas-containerd/src/provider/function/delete.rs new file mode 100644 index 0000000..6a9585d --- /dev/null +++ b/crates/faas-containerd/src/provider/function/delete.rs @@ -0,0 +1,35 @@ +use crate::impls::cni::Endpoint; +use crate::impls::{backend, cni}; +use crate::provider::ContainerdProvider; +use gateway::handlers::function::DeleteError; +use gateway::types::function::Query; + +impl ContainerdProvider { + pub(crate) async fn _delete(&self, function: Query) -> Result<(), DeleteError> { + let endpoint: Endpoint = function.into(); + log::trace!("Deleting function: {:?}", endpoint); + + backend().kill_task_with_timeout(&endpoint).await?; + + let del_ctr_err = backend().delete_container(&endpoint).await.map_err(|e| { + log::error!("Failed to delete container: {:?}", e); + e + }); + + let rm_snap_err = backend().remove_snapshot(&endpoint).await.map_err(|e| { + log::error!("Failed to remove snapshot: {:?}", e); + e + }); + + let del_net_err = cni::cni_impl::delete_cni_network(endpoint); + + if del_ctr_err.is_ok() && rm_snap_err.is_ok() && del_net_err.is_ok() { + Ok(()) + } else { + Err(DeleteError::Internal(format!( + "{:?}, {:?}, {:?}", + del_ctr_err, rm_snap_err, del_net_err + ))) + } + } +} diff --git a/crates/faas-containerd/src/provider/function/deploy.rs b/crates/faas-containerd/src/provider/function/deploy.rs new file mode 100644 index 0000000..2d8344a --- /dev/null +++ b/crates/faas-containerd/src/provider/function/deploy.rs @@ -0,0 +1,96 @@ +use crate::impls::cni; +use crate::impls::{self, backend, function::ContainerStaticMetadata}; +use crate::provider::ContainerdProvider; +use gateway::handlers::function::DeployError; +use gateway::types::function::Deployment; +use scopeguard::{ScopeGuard, guard}; + +impl ContainerdProvider { + pub(crate) async fn _deploy(&self, config: Deployment) -> Result<(), DeployError> { + let metadata = ContainerStaticMetadata::from(config); + log::trace!("Deploying function: {:?}", metadata); + + // not going to check the conflict of namespace, should be handled by containerd backend + backend() + .prepare_image(&metadata.image, &metadata.endpoint.namespace, true) + .await + .map_err(|img_err| { + use impls::oci_image::ImageError; + log::error!("Image '{}' fetch failed: {}", &metadata.image, img_err); + match img_err { + ImageError::ImageNotFound(e) => DeployError::Invalid(e.to_string()), + _ => DeployError::InternalError(img_err.to_string()), + } + })?; + log::trace!("Image '{}' fetch ok", &metadata.image); + + let mounts = backend().prepare_snapshot(&metadata).await.map_err(|e| { + log::error!("Failed to prepare snapshot: {:?}", e); + DeployError::InternalError(e.to_string()) + })?; + + let snapshot_defer = scopeguard::guard((), |()| { + log::trace!("Cleaning up snapshot"); + let endpoint = metadata.endpoint.clone(); + tokio::spawn(async move { backend().remove_snapshot(&endpoint).await }); + }); + + // let network = CNIEndpoint::new(&metadata.container_id, &metadata.namespace)?; + let (ip, netns) = cni::cni_impl::create_cni_network(&metadata.endpoint).map_err(|e| { + log::error!("Failed to create CNI network: {}", e); + DeployError::InternalError(e.to_string()) + })?; + + let netns_defer = guard(netns, |ns| ns.remove().unwrap()); + + let _ = backend().create_container(&metadata).await.map_err(|e| { + log::error!("Failed to create container: {:?}", e); + DeployError::InternalError(e.to_string()) + })?; + + let container_defer = scopeguard::guard((), |()| { + let endpoint = metadata.endpoint.clone(); + tokio::spawn(async move { backend().delete_container(&endpoint).await }); + }); + + // TODO: Use ostree-ext + // let img_conf = BACKEND.get().unwrap().get_runtime_config(&metadata.image).unwrap(); + + backend().new_task(mounts, &metadata.endpoint).await?; + + let task_defer = scopeguard::guard((), |()| { + let endpoint = metadata.endpoint.clone(); + tokio::spawn(async move { backend().kill_task_with_timeout(&endpoint).await }); + }); + + use std::net::IpAddr::*; + + match ip.address() { + V4(addr) => { + if let Err(err) = self + .database + .insert(metadata.endpoint.to_string(), &addr.octets()) + { + log::error!("Failed to insert into database: {:?}", err); + return Err(DeployError::InternalError(err.to_string())); + } + } + V6(addr) => { + if let Err(err) = self + .database + .insert(metadata.endpoint.to_string(), &addr.octets()) + { + log::error!("Failed to insert into database: {:?}", err); + return Err(DeployError::InternalError(err.to_string())); + } + } + } + + log::info!("container was created successfully: {}", metadata.endpoint); + ScopeGuard::into_inner(snapshot_defer); + ScopeGuard::into_inner(netns_defer); + ScopeGuard::into_inner(container_defer); + ScopeGuard::into_inner(task_defer); + Ok(()) + } +} diff --git a/crates/faas-containerd/src/provider/function/get.rs b/crates/faas-containerd/src/provider/function/get.rs new file mode 100644 index 0000000..2bc51fa --- /dev/null +++ b/crates/faas-containerd/src/provider/function/get.rs @@ -0,0 +1,19 @@ +use crate::provider::ContainerdProvider; + +pub enum GetError { + NotFound, + InternalError, +} + +impl ContainerdProvider { + // pub async fn getfn( + // &self, + // query: function::Query, + // ) -> Option { + // let instance = self.ctr_instance_map + // .lock() + // .await + // .get(&query) + // .cloned(); + // } +} diff --git a/crates/faas-containerd/src/provider/function/list.rs b/crates/faas-containerd/src/provider/function/list.rs new file mode 100644 index 0000000..d5f104e --- /dev/null +++ b/crates/faas-containerd/src/provider/function/list.rs @@ -0,0 +1,69 @@ +use gateway::{handlers::function::ListError, types::function::Status}; + +use crate::{ + impls::{backend, cni::Endpoint, task::TaskError}, + provider::ContainerdProvider, +}; + +impl ContainerdProvider { + pub(crate) async fn _list(&self, namespace: String) -> Result, ListError> { + let containers = backend().list_container(&namespace).await.map_err(|e| { + log::error!( + "failed to get container list for namespace {} because {:?}", + namespace, + e + ); + ListError::Internal(e.to_string()) + })?; + let mut statuses: Vec = Vec::new(); + for container in containers { + let endpoint = Endpoint { + service: container.id.clone(), + namespace: namespace.clone(), + }; + let created_at = container.created_at.unwrap().to_string(); + let mut replicas = 0; + + match backend().get_task(&endpoint).await { + Ok(task) => { + let status = task.status; + if status == 2 || status == 3 { + replicas = 1; + } + } + Err(TaskError::NotFound) => continue, + Err(e) => { + log::warn!( + "failed to get task for function {:?} because {:?}", + &endpoint, + e + ); + } + } + + // 大部分字段并未实现,使用None填充 + let status = Status { + name: endpoint.service, + namespace: Some(endpoint.namespace), + image: container.image, + env_process: None, + env_vars: None, + constraints: None, + secrets: None, + labels: None, + annotations: None, + limits: None, + requests: None, + read_only_root_filesystem: false, + invocation_count: None, + replicas: Some(replicas), + available_replicas: Some(replicas), + created_at: Some(created_at), + usage: None, + }; + statuses.push(status); + } + + Ok(statuses) + } +} diff --git a/crates/faas-containerd/src/provider/function/mod.rs b/crates/faas-containerd/src/provider/function/mod.rs new file mode 100644 index 0000000..88b78b9 --- /dev/null +++ b/crates/faas-containerd/src/provider/function/mod.rs @@ -0,0 +1,6 @@ +pub mod delete; +pub mod deploy; +pub mod list; +pub mod resolve; +pub mod status; +pub mod update; diff --git a/crates/faas-containerd/src/provider/function/resolve.rs b/crates/faas-containerd/src/provider/function/resolve.rs new file mode 100644 index 0000000..98925bb --- /dev/null +++ b/crates/faas-containerd/src/provider/function/resolve.rs @@ -0,0 +1,65 @@ +use std::net::{IpAddr, Ipv4Addr}; + +use actix_http::uri::Builder; +use gateway::handlers::function::ResolveError; +use gateway::types::function::Query; + +use crate::impls::cni::{self, Endpoint}; +use crate::provider::ContainerdProvider; + +fn upstream(addr: IpAddr) -> Builder { + actix_http::Uri::builder() + .scheme("http") + .authority(format!("{}:{}", addr, 8080)) +} + +impl ContainerdProvider { + pub(crate) async fn _resolve( + &self, + query: Query, + ) -> Result { + let endpoint = Endpoint::from(query); + log::trace!("Resolving function: {:?}", endpoint); + let addr_oct = self + .database + .get(endpoint.to_string()) + .map_err(|e| { + log::error!("Failed to get container address: {:?}", e); + ResolveError::Internal(e.to_string()) + })? + .ok_or(ResolveError::NotFound("container not found".to_string()))?; + + log::trace!("Container address: {:?}", addr_oct.as_array::<4>()); + + // We force the address to be IPv4 here + let addr = IpAddr::V4(Ipv4Addr::from_octets(*addr_oct.as_array::<4>().unwrap())); + + // Check if the coresponding netns is still alive + // We can achieve this by checking the /run/cni/faasrs-cni-bridge, + // if the ip filename is still there + + if cni::cni_impl::check_network_exists(addr) { + log::trace!("CNI network exists for {}", addr); + Ok(upstream(addr)) + } else { + log::error!("CNI network not exists for {}", addr); + let _ = self.database.remove(endpoint.to_string()); + Err(ResolveError::Internal("CNI network not exists".to_string())) + } + } +} + +#[cfg(test)] +mod tests { + use std::net::{IpAddr, Ipv4Addr}; + + #[test] + fn test_uri() { + let addr = IpAddr::V4(Ipv4Addr::new(10, 42, 2, 48)); + let uri = super::upstream(addr).path_and_query("").build().unwrap(); + assert_eq!(uri.scheme_str(), Some("http")); + assert_eq!(uri.authority().unwrap().host(), addr.to_string()); + assert_eq!(uri.authority().unwrap().port_u16(), Some(8080)); + assert_eq!(uri.to_string(), format!("http://{}:8080/", addr)); + } +} diff --git a/crates/faas-containerd/src/provider/function/status.rs b/crates/faas-containerd/src/provider/function/status.rs new file mode 100644 index 0000000..b04bc43 --- /dev/null +++ b/crates/faas-containerd/src/provider/function/status.rs @@ -0,0 +1,69 @@ +use gateway::{ + handlers::function::ResolveError, + types::function::{Query, Status}, +}; + +use crate::{ + impls::{backend, cni::Endpoint, container::ContainerError}, + provider::ContainerdProvider, +}; + +impl ContainerdProvider { + pub(crate) async fn _status(&self, function: Query) -> Result { + let endpoint: Endpoint = function.into(); + let container = backend().load_container(&endpoint).await.map_err(|e| { + log::error!( + "failed to load container for function {:?} because {:?}", + endpoint, + e + ); + match e { + ContainerError::NotFound => ResolveError::NotFound(e.to_string()), + ContainerError::Internal => ResolveError::Internal(e.to_string()), + _ => ResolveError::Invalid(e.to_string()), + } + })?; + + let created_at = container.created_at.unwrap().to_string(); + let mut replicas = 0; + + match backend().get_task(&endpoint).await { + Ok(task) => { + let status = task.status; + if status == 2 || status == 3 { + replicas = 1; + } + } + Err(e) => { + log::warn!( + "failed to get task for function {:?} because {:?}", + &endpoint, + e + ); + } + } + + // 大部分字段并未实现,使用None填充 + let status = Status { + name: container.id, + namespace: Some(endpoint.namespace), + image: container.image, + env_process: None, + env_vars: None, + constraints: None, + secrets: None, + labels: None, + annotations: None, + limits: None, + requests: None, + read_only_root_filesystem: false, + invocation_count: None, + replicas: Some(replicas), + available_replicas: Some(replicas), + created_at: Some(created_at), + usage: None, + }; + + Ok(status) + } +} diff --git a/crates/faas-containerd/src/provider/function/update.rs b/crates/faas-containerd/src/provider/function/update.rs new file mode 100644 index 0000000..92a49a9 --- /dev/null +++ b/crates/faas-containerd/src/provider/function/update.rs @@ -0,0 +1,32 @@ +use gateway::{ + handlers::function::{DeleteError, DeployError, UpdateError}, + types::function::{Deployment, Query}, +}; + +use crate::provider::ContainerdProvider; + +impl ContainerdProvider { + pub(crate) async fn _update(&self, param: Deployment) -> Result<(), UpdateError> { + let function = Query { + service: param.service.clone(), + namespace: param.namespace.clone(), + }; + self._delete(function).await.map_err(|e| { + log::error!("failed to delete function when update because {:?}", e); + match e { + DeleteError::NotFound(e) => UpdateError::NotFound(e.to_string()), + DeleteError::Internal(e) => UpdateError::Internal(e.to_string()), + _ => UpdateError::Internal(e.to_string()), + } + })?; + self._deploy(param).await.map_err(|e| { + log::error!("failed to deploy function when update because {:?}", e); + match e { + DeployError::Invalid(e) => UpdateError::Invalid(e.to_string()), + DeployError::InternalError(e) => UpdateError::Internal(e.to_string()), + } + })?; + + Ok(()) + } +} diff --git a/crates/faas-containerd/src/provider/mod.rs b/crates/faas-containerd/src/provider/mod.rs new file mode 100644 index 0000000..b8769fd --- /dev/null +++ b/crates/faas-containerd/src/provider/mod.rs @@ -0,0 +1,49 @@ +pub mod function; + +use std::{path::Path, sync::Arc}; + +use gateway::{ + handlers::function::{DeleteError, DeployError, ListError, ResolveError, UpdateError}, + provider::Provider, + types::function::{Deployment, Query, Status}, +}; + +pub struct ContainerdProvider { + // pub ctr_instance_map: tokio::sync::Mutex>, + database: sled::Db, +} + +impl ContainerdProvider { + pub fn new>(path: P) -> Arc { + Arc::new(ContainerdProvider { + // ctr_instance_map: tokio::sync::Mutex::new(HashMap::new()), + database: sled::open(path).unwrap(), + }) + } +} + +impl Provider for ContainerdProvider { + async fn resolve(&self, function: Query) -> Result { + self._resolve(function).await + } + + async fn deploy(&self, param: Deployment) -> Result<(), DeployError> { + self._deploy(param).await + } + + async fn delete(&self, function: Query) -> Result<(), DeleteError> { + self._delete(function).await + } + + async fn list(&self, namespace: String) -> Result, ListError> { + self._list(namespace).await + } + + async fn update(&self, param: Deployment) -> Result<(), UpdateError> { + self._update(param).await + } + + async fn status(&self, function: Query) -> Result { + self._status(function).await + } +} diff --git a/crates/service/src/systemd.rs b/crates/faas-containerd/src/systemd.rs similarity index 100% rename from crates/service/src/systemd.rs rename to crates/faas-containerd/src/systemd.rs diff --git a/crates/faas-containerd/tests/integration_test.rs b/crates/faas-containerd/tests/integration_test.rs new file mode 100644 index 0000000..e311454 --- /dev/null +++ b/crates/faas-containerd/tests/integration_test.rs @@ -0,0 +1,150 @@ +use actix_web::App; +use actix_web::http::StatusCode; +use actix_web::test; +use faas_containerd::consts::DEFAULT_FAASDRS_DATA_DIR; +use gateway::bootstrap::config_app; +use serde_json::json; + +#[actix_web::test] +#[ignore] +async fn test_handlers_in_order() { + dotenv::dotenv().ok(); + faas_containerd::init_backend().await; + let provider = faas_containerd::provider::ContainerdProvider::new(DEFAULT_FAASDRS_DATA_DIR); + let app = test::init_service(App::new().configure(config_app(provider))).await; + + // test proxy no-found-function in namespace 'faasrs-test-namespace' + let req = test::TestRequest::get() + .uri("/function/test-no-found-function") + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); + let response_body = test::read_body(resp).await; + let response_str = std::str::from_utf8(&response_body).unwrap(); + assert!(response_str.contains("Invalid function name")); + + // test update no-found-function in namespace 'faasrs-test-namespace' + let req = test::TestRequest::put() + .uri("/system/functions") + .set_json(json!({ + "service": "test-no-found-function", + "image": "hub.scutosc.cn/dolzhuying/echo:latest", + "namespace": "faasrs-test-namespace" + })) + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), StatusCode::NOT_FOUND); + let response_body = test::read_body(resp).await; + let response_str = std::str::from_utf8(&response_body).unwrap(); + assert!(response_str.contains("NotFound: container not found")); + + // test delete no-found-function in namespace 'faasrs-test-namespace' + let req = test::TestRequest::delete() + .uri("/system/functions") + .set_json(json!({ + "functionName": "test-no-found-function", + "namespace": "faasrs-test-namespace" + })) + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), StatusCode::NOT_FOUND); + + // test deploy test-function in namespace 'faasrs-test-namespace' + let req = test::TestRequest::post() + .uri("/system/functions") + .set_json(json!({ + "service": "test-function", + "image": "hub.scutosc.cn/dolzhuying/echo:latest", + "namespace": "faasrs-test-namespace" + })) + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!( + resp.status(), + StatusCode::ACCEPTED, + "error: {:?}", + resp.response() + ); + + // test update test-function in namespace 'faasrs-test-namespace' + let req = test::TestRequest::put() + .uri("/system/functions") + .set_json(json!({ + "service": "test-function", + "image": "hub.scutosc.cn/dolzhuying/echo:latest", + "namespace": "faasrs-test-namespace" + })) + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), StatusCode::ACCEPTED); + let response_body = test::read_body(resp).await; + let response_str = std::str::from_utf8(&response_body).unwrap(); + assert!(response_str.contains("function test-function was updated successfully")); + + // test list + let req = test::TestRequest::get() + .uri("/system/functions?namespace=faasrs-test-namespace") + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), StatusCode::OK); + let response_body = test::read_body(resp).await; + let response_str = std::str::from_utf8(&response_body).unwrap(); + let response_json: serde_json::Value = serde_json::from_str(response_str).unwrap(); + if let Some(arr) = response_json.as_array() { + for item in arr { + assert_eq!( + item["name"], + serde_json::Value::String("test-function".to_string()) + ); + assert_eq!( + item["image"], + serde_json::Value::String("hub.scutosc.cn/dolzhuying/echo:latest".to_string()) + ); + assert_eq!( + item["namespace"], + serde_json::Value::String("faasrs-test-namespace".to_string()) + ); + } + } + + // test status test-function in namespace 'faasrs-test-namespace' + let req = test::TestRequest::get() + .uri("/system/function/test-function?namespace=faasrs-test-namespace") + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), StatusCode::OK); + let response_body = test::read_body(resp).await; + let response_str = std::str::from_utf8(&response_body).unwrap(); + let response_json: serde_json::Value = serde_json::from_str(response_str).unwrap(); + if let Some(arr) = response_json.as_array() { + for item in arr { + assert_eq!(item["name"], "test-function"); + assert_eq!(item["image"], "hub.scutosc.cn/dolzhuying/echo:latest"); + assert_eq!(item["namespace"], "faasrs-test-namespace"); + } + } + + // test proxy test-function in namespace 'faasrs-test-namespace' + let req = test::TestRequest::get() + .uri("/function/test-function.faasrs-test-namespace") + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), StatusCode::OK); + let response_body = test::read_body(resp).await; + let response_str = std::str::from_utf8(&response_body).unwrap(); + assert!(response_str.contains("Hello world!")); + + // test delete test-function in namespace 'faasrs-test-namespace' + let req = test::TestRequest::delete() + .uri("/system/functions") + .set_json(json!({ + "functionName": "test-function", + "namespace": "faasrs-test-namespace" + })) + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), StatusCode::OK); + let response_body = test::read_body(resp).await; + let response_str = std::str::from_utf8(&response_body).unwrap(); + assert!(response_str.contains("function test-function was deleted successfully")); +} diff --git a/crates/provider/Cargo.toml b/crates/gateway/Cargo.toml similarity index 58% rename from crates/provider/Cargo.toml rename to crates/gateway/Cargo.toml index fc6b54d..54d0bd8 100644 --- a/crates/provider/Cargo.toml +++ b/crates/gateway/Cargo.toml @@ -1,35 +1,25 @@ [package] -name = "provider" +name = "gateway" edition = "2024" version.workspace = true authors.workspace = true [dependencies] -actix-web = "4.5.1" +actix-web = "4.11.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tokio = { version = "1.37.0", features = ["full"] } -bollard = "0.13.0" -uuid = { version = "1.8.0", features = ["v4"] } actix-web-httpauth = "0.6" -config = "0.11" thiserror = "1.0" awc = "3.6.0" prometheus = "0.13" -tempfile = "3.2" -tower = "0.4" -regex = "1" -futures = "0.3" -actix-service = "2" base64 = "0.13" -futures-util = "0.3" -service = { path = "../service" } -cni = { path = "../cni" } -async-trait = "0.1" -lazy_static = "1.4.0" log = "0.4.27" my-workspace-hack = { version = "0.1", path = "../my-workspace-hack" } url = "2.4" derive_more = { version = "2", features = ["full"] } tonic = "0.12" -http = "1.3.1" +tokio-util = "*" +http = "*" +actix-http = "*" +chrono = "0.4.41" diff --git a/crates/gateway/src/bootstrap/mod.rs b/crates/gateway/src/bootstrap/mod.rs new file mode 100644 index 0000000..83a0ea1 --- /dev/null +++ b/crates/gateway/src/bootstrap/mod.rs @@ -0,0 +1,175 @@ +use actix_web::{ + App, HttpServer, + dev::Server, + web::{self, ServiceConfig}, +}; + +use std::{collections::HashMap, sync::Arc}; + +use crate::{ + handlers::{self, proxy::PROXY_DISPATCH_PATH}, + // metrics::HttpMetrics, + provider::Provider, + types::config::FaaSConfig, +}; + +pub fn config_app(provider: Arc

) -> impl FnOnce(&mut ServiceConfig) { + // let _registry = Registry::new(); + + let provider = web::Data::from(provider); + let app_state = web::Data::new(AppState { + // metrics: HttpMetrics::new(), + credentials: None, + }); + move |cfg: &mut ServiceConfig| { + cfg.app_data(app_state) + .app_data(provider) + .service( + web::scope("/system") + .service( + web::resource("/functions") + .route(web::get().to(handlers::function::list::

)) + .route(web::put().to(handlers::function::update::

)) + .route(web::post().to(handlers::function::deploy::

)) + .route(web::delete().to(handlers::function::delete::

)), + ) + .service( + web::resource("/function/{functionName}") + .route(web::get().to(handlers::function::status::

)), + ), // .service( + // web::resource("/scale-function/{name}") + // .route(web::post().to(handlers::scale_function)), + // ) + // .service(web::resource("/info").route(web::get().to(handlers::info))) + // .service( + // web::resource("/secrets") + // .route(web::get().to(handlers::secrets)) + // .route(web::post().to(handlers::secrets)) + // .route(web::put().to(handlers::secrets)) + // .route(web::delete().to(handlers::secrets)), + // ) + // .service(web::resource("/logs").route(web::get().to(handlers::logs))) + // .service( + // web::resource("/namespaces") + // .route(web::get().to(handlers::list_namespaces)) + // .route(web::post().to(handlers::mutate_namespace)), + // ), + // ) + ) + .service(web::scope("/function").service( + web::resource(PROXY_DISPATCH_PATH).route(web::to(handlers::proxy::proxy::

)), + )); + // .route("/metrics", web::get().to(handlers::telemetry)) + // .route("/healthz", web::get().to(handlers::health)); + } +} + +//应用程序状态,存储共享的数据,如配置、指标、认证信息等,为业务函数提供支持 +#[derive(Clone)] +#[allow(dead_code)] +struct AppState { + // config: FaaSConfig, //应用程序的配置,用于识别是否开启Basic Auth等 + // metrics: HttpMetrics, //用于监视http请求的持续时间和总数 + // metrics: HttpMetrics, //用于监视http请求的持续时间和总数 + credentials: Option>, //当有认证信息的时候,获取认证信息 +} + +// this is a blocking serve function +pub fn serve(provider: Arc

) -> std::io::Result { + log::info!("Checking config file"); + let config = FaaSConfig::new(); + let port = config.tcp_port.unwrap_or(8080); + + // 如果启用了Basic Auth,从指定路径读取认证凭证并存储在应用程序状态中 + // TODO: Authentication Logic + + let server = HttpServer::new(move || App::new().configure(config_app(provider.clone()))) + .bind(("0.0.0.0", port))? + .run(); + + Ok(server) +} + +#[cfg(test)] +mod tests { + use std::str::FromStr; + + use crate::handlers::proxy::{PROXY_DISPATCH_PATH, ProxyQuery}; + + use actix_web::{App, HttpResponse, Responder, test, web}; + + async fn dispatcher(any: web::Path) -> impl Responder { + let meta = ProxyQuery::from_str(&any).unwrap(); + HttpResponse::Ok().body(format!( + "{}|{}|{}", + meta.query.service, + meta.query.namespace.unwrap_or_default(), + meta.path + )) + } + + #[actix_web::test] + async fn test_proxy() { + let app = test::init_service( + App::new().service(web::resource(PROXY_DISPATCH_PATH).route(web::get().to(dispatcher))), + ) + .await; + + let (unslash, slash, resp0, a0) = ( + "/service.namespace/path", + "/service.namespace/path/", + "service|namespace|/path", + "service|namespace|/path/", + ); + let (unslash1, slash1, resp1, a1) = ( + "/service/path", + "/service/path/", + "service||/path", + "service||/path/", + ); + let (unslash2, slash2, resp2, a2) = ( + "/service.namespace", + "/service.namespace/", + "service|namespace|", + "service|namespace|/", + ); + let (unslash3, slash3, resp3, a3) = ("/service", "/service/", "service||", "service||/"); + + let req = test::TestRequest::get().uri(unslash).to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert_eq!(resp, resp0); + + let req = test::TestRequest::get().uri(slash).to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert_eq!(resp, a0); + + let req = test::TestRequest::get().uri(unslash1).to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert_eq!(resp, resp1); + + let req = test::TestRequest::get().uri(slash1).to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert_eq!(resp, a1); + + let req = test::TestRequest::get().uri(unslash2).to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert_eq!(resp, resp2); + + let req = test::TestRequest::get().uri(slash2).to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert_eq!(resp, a2); + + let req = test::TestRequest::get().uri(unslash3).to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert_eq!(resp, resp3); + + let req = test::TestRequest::get().uri(slash3).to_request(); + let resp = test::call_and_read_body(&app, req).await; + assert_eq!(resp, a3); + + // test with empty path + let req = test::TestRequest::get().uri("/").to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), 404); + } +} diff --git a/crates/gateway/src/handlers/function.rs b/crates/gateway/src/handlers/function.rs new file mode 100644 index 0000000..21ee01f --- /dev/null +++ b/crates/gateway/src/handlers/function.rs @@ -0,0 +1,173 @@ +use crate::provider::Provider; +use crate::types::function::{Delete, Deployment, Query}; +use actix_http::StatusCode; +use actix_web::ResponseError; +use actix_web::{HttpResponse, web}; +use derive_more::derive::Display; +use serde::Deserialize; + +// 参考响应状态 https://github.com/openfaas/faas/blob/7803ea1861f2a22adcbcfa8c79ed539bc6506d5b/api-docs/spec.openapi.yml#L121C1-L140C45 +// 请求体反序列化失败,自动返回400错误 +pub async fn deploy( + provider: web::Data

, + info: web::Json, +) -> Result { + let service = info.0.service.clone(); + (*provider).deploy(info.0).await.map(|()| { + HttpResponse::Accepted().body(format!("function {} was created successfully", service)) + }) +} + +pub async fn update( + provider: web::Data

, + info: web::Json, +) -> Result { + let service = info.0.service.clone(); + (*provider).update(info.0).await.map(|()| { + HttpResponse::Accepted().body(format!("function {} was updated successfully", service)) + }) +} + +pub async fn delete( + provider: web::Data

, + info: web::Json, +) -> Result { + let service = info.0.function_name.clone(); + let query = Query { + service: service.clone(), + namespace: Some(info.0.namespace), + }; + (*provider) + .delete(query) + .await + .map(|()| HttpResponse::Ok().body(format!("function {} was deleted successfully", service))) +} + +#[derive(Debug, Deserialize)] +pub struct ListParam { + namespace: String, +} + +pub async fn list( + provider: web::Data

, + info: web::Query, +) -> Result { + (*provider) + .list(info.namespace.clone()) + .await + .map(|functions| HttpResponse::Ok().json(functions)) +} + +#[derive(Debug, Deserialize)] +pub struct StatusParam { + namespace: Option, +} + +pub async fn status( + provider: web::Data

, + name: web::Path, + info: web::Query, +) -> Result { + let query = Query { + service: name.into_inner(), + namespace: info.namespace.clone(), + }; + let status = (*provider).status(query).await?; + Ok(HttpResponse::Ok().json(status)) +} + +// TODO: 为 Errors 添加错误信息 + +#[derive(Debug, Display)] +pub enum DeployError { + #[display("Invalid: {}", _0)] + Invalid(String), + #[display("Internal: {}", _0)] + InternalError(String), +} + +#[derive(Debug, Display)] +pub enum DeleteError { + #[display("Invalid: {}", _0)] + Invalid(String), + #[display("NotFound: {}", _0)] + NotFound(String), + #[display("Internal: {}", _0)] + Internal(String), +} + +#[derive(Debug, Display)] +pub enum ResolveError { + #[display("NotFound: {}", _0)] + NotFound(String), + #[display("Invalid: {}", _0)] + Invalid(String), + #[display("Internal: {}", _0)] + Internal(String), +} + +#[derive(Debug, Display)] +pub enum ListError { + #[display("Internal: {}", _0)] + Internal(String), + #[display("NotFound: {}", _0)] + NotFound(String), +} + +#[derive(Debug, Display)] +pub enum UpdateError { + #[display("Invalid: {}", _0)] + Invalid(String), + #[display("Internal: {}", _0)] + Internal(String), + #[display("NotFound: {}", _0)] + NotFound(String), +} + +impl ResponseError for DeployError { + fn status_code(&self) -> StatusCode { + match self { + DeployError::Invalid(_) => StatusCode::BAD_REQUEST, + DeployError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR, + } + } +} + +impl ResponseError for DeleteError { + fn status_code(&self) -> StatusCode { + match self { + DeleteError::Invalid(_) => StatusCode::BAD_REQUEST, + DeleteError::NotFound(_) => StatusCode::NOT_FOUND, + DeleteError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, + } + } +} + +impl ResponseError for ResolveError { + fn status_code(&self) -> StatusCode { + match self { + ResolveError::NotFound(_) => StatusCode::NOT_FOUND, + ResolveError::Invalid(_) => StatusCode::BAD_REQUEST, + ResolveError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, + } + } +} + +impl ResponseError for ListError { + fn status_code(&self) -> StatusCode { + match self { + ListError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, + ListError::NotFound(_) => StatusCode::NOT_FOUND, + } + } +} + +impl ResponseError for UpdateError { + fn status_code(&self) -> StatusCode { + match self { + UpdateError::Invalid(_) => StatusCode::BAD_REQUEST, + UpdateError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, + UpdateError::NotFound(_) => StatusCode::NOT_FOUND, + } + } +} diff --git a/crates/gateway/src/handlers/mod.rs b/crates/gateway/src/handlers/mod.rs new file mode 100644 index 0000000..e042611 --- /dev/null +++ b/crates/gateway/src/handlers/mod.rs @@ -0,0 +1,34 @@ +pub mod function; +pub mod proxy; + +#[derive(Debug, thiserror::Error)] +pub struct FaasError { + message: String, + error_type: FaasErrorType, + #[source] + source: Option>, +} + +#[derive(Debug)] +pub enum FaasErrorType { + ContainerFailure, + Timeout, + InternalError, +} + +impl std::fmt::Display for FaasError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "[{:?}] {}", self.error_type, self.message) + } +} + +// 实现从常见错误类型转换 +impl From for FaasError { + fn from(err: std::io::Error) -> Self { + FaasError { + message: format!("IO error: {}", err), + error_type: FaasErrorType::InternalError, + source: Some(Box::new(err)), + } + } +} diff --git a/crates/gateway/src/handlers/proxy.rs b/crates/gateway/src/handlers/proxy.rs new file mode 100644 index 0000000..80120dd --- /dev/null +++ b/crates/gateway/src/handlers/proxy.rs @@ -0,0 +1,67 @@ +use std::str::FromStr; + +use actix_http::Method; +use actix_web::{HttpRequest, HttpResponse, error::ErrorMethodNotAllowed, web}; + +use crate::{provider::Provider, proxy::proxy_handler::proxy_request, types::function::Query}; + +pub const PROXY_DISPATCH_PATH: &str = "/{any:.+}"; + +pub struct ProxyQuery { + pub query: Query, + pub path: String, +} + +impl FromStr for ProxyQuery { + type Err = (); + fn from_str(path: &str) -> Result { + let (identifier, rest_path) = if let Some((identifier, rest_path)) = path.split_once('/') { + match rest_path { + "" => (identifier, "/".to_owned()), + _ => (identifier, "/".to_owned() + rest_path), + } + } else { + (path, "".to_owned()) + }; + let (service, namespace) = identifier + .rsplit_once('.') + .map(|(s, n)| (s.to_string(), Some(n.to_string()))) + .unwrap_or((identifier.to_string(), None)); + Ok(ProxyQuery { + query: Query { service, namespace }, + path: rest_path, + }) + } +} + +// 主要参考源码的响应设置 +pub async fn proxy( + req: HttpRequest, + payload: web::Payload, + provider: web::Data

, + any: web::Path, +) -> actix_web::Result { + let meta = ProxyQuery::from_str(&any).map_err(|_| { + log::error!("Failed to parse path: {}", any); + ErrorMethodNotAllowed("Invalid path") + })?; + let function = meta.query; + log::trace!("proxy query: {:?}", function); + match *req.method() { + Method::POST + | Method::PUT + | Method::DELETE + | Method::GET + | Method::PATCH + | Method::HEAD + | Method::OPTIONS => { + let upstream = provider + .resolve(function) + .await + .map_err(|e| ErrorMethodNotAllowed(format!("Invalid function name {e}")))?; + log::trace!("upstream: {:?}", upstream); + proxy_request(&req, payload, upstream, &meta.path).await + } + _ => Err(ErrorMethodNotAllowed("Method not allowed")), + } +} diff --git a/crates/provider/src/handlers/utils.rs b/crates/gateway/src/handlers/utils.rs similarity index 100% rename from crates/provider/src/handlers/utils.rs rename to crates/gateway/src/handlers/utils.rs diff --git a/crates/gateway/src/lib.rs b/crates/gateway/src/lib.rs new file mode 100644 index 0000000..0857b4c --- /dev/null +++ b/crates/gateway/src/lib.rs @@ -0,0 +1,6 @@ +pub mod bootstrap; +pub mod handlers; +// pub mod metrics; +pub mod provider; +pub mod proxy; +pub mod types; diff --git a/crates/provider/src/metrics/mod.rs b/crates/gateway/src/metrics/mod.rs similarity index 93% rename from crates/provider/src/metrics/mod.rs rename to crates/gateway/src/metrics/mod.rs index bb4ebbd..248bd2d 100644 --- a/crates/provider/src/metrics/mod.rs +++ b/crates/gateway/src/metrics/mod.rs @@ -35,5 +35,3 @@ impl HttpMetrics { } } } - -pub const TEXT_CONTENT_TYPE: &str = "text/plain; version=0.0.4"; diff --git a/crates/gateway/src/provider/mod.rs b/crates/gateway/src/provider/mod.rs new file mode 100644 index 0000000..5260878 --- /dev/null +++ b/crates/gateway/src/provider/mod.rs @@ -0,0 +1,45 @@ +use crate::{ + handlers::function::{DeleteError, DeployError, ListError, ResolveError, UpdateError}, + types::function::{Deployment, Query, Status}, +}; + +pub trait Provider: Send + Sync + 'static { + /// Should return a valid upstream url + fn resolve( + &self, + function: Query, + ) -> impl std::future::Future> + Send; + + // `/system/functions` endpoint + + /// Get a list of deployed functions + fn list( + &self, + namespace: String, + ) -> impl std::future::Future, ListError>> + Send; + + /// Deploy a new function + fn deploy( + &self, + param: Deployment, + ) -> impl std::future::Future> + Send; + + /// Update a function spec + fn update( + &self, + param: Deployment, + ) -> impl std::future::Future> + Send; + + /// Delete a function + fn delete( + &self, + function: Query, + ) -> impl std::future::Future> + Send; + + // `/system/function/{functionName}` endpoint + /// Get the status of a function by name + fn status( + &self, + function: Query, + ) -> impl std::future::Future> + Send; +} diff --git a/crates/provider/src/proxy/builder.rs b/crates/gateway/src/proxy/builder.rs similarity index 70% rename from crates/provider/src/proxy/builder.rs rename to crates/gateway/src/proxy/builder.rs index b471894..ddc48b0 100644 --- a/crates/provider/src/proxy/builder.rs +++ b/crates/gateway/src/proxy/builder.rs @@ -1,22 +1,14 @@ -use actix_web::{HttpRequest, web}; +use actix_web::{HttpRequest, http::Uri, web}; -use awc::http::Uri; -use url::Url; //根据URL和原始请求来构建转发请求,并对请求头进行处理 pub fn create_proxy_request( req: &HttpRequest, - base_url: &Url, + uri: Uri, payload: web::Payload, ) -> awc::SendClientRequest { let proxy_client = awc::Client::builder() .timeout(std::time::Duration::from_secs(10)) .finish(); - let origin_url = base_url.join(req.uri().path()).unwrap(); - let remaining_segments = origin_url.path_segments().unwrap().skip(2); - let rest_path = remaining_segments.collect::>().join("/"); - let url = base_url.join(&rest_path).unwrap(); - - let uri = url.as_str().parse::().unwrap(); let mut proxy_req = proxy_client.request(req.method().clone(), uri); diff --git a/crates/provider/src/proxy/mod.rs b/crates/gateway/src/proxy/mod.rs similarity index 57% rename from crates/provider/src/proxy/mod.rs rename to crates/gateway/src/proxy/mod.rs index 5d765ee..cb15bb5 100644 --- a/crates/provider/src/proxy/mod.rs +++ b/crates/gateway/src/proxy/mod.rs @@ -1,3 +1,4 @@ pub mod builder; pub mod proxy_handler; -mod proxy_handler_test; +// #[cfg(test)] +// mod test; diff --git a/crates/gateway/src/proxy/proxy_handler.rs b/crates/gateway/src/proxy/proxy_handler.rs new file mode 100644 index 0000000..3214d90 --- /dev/null +++ b/crates/gateway/src/proxy/proxy_handler.rs @@ -0,0 +1,28 @@ +// use crate::handlers::invoke_resolver::InvokeResolver; +use crate::proxy::builder::create_proxy_request; + +use actix_web::{HttpRequest, HttpResponse, error::ErrorInternalServerError, web}; + +pub async fn proxy_request( + req: &HttpRequest, + payload: web::Payload, + upstream: actix_http::uri::Builder, + path: &str, +) -> actix_web::Result { + let uri = upstream.path_and_query(path).build().map_err(|e| { + log::error!("Failed to build URI: {}", e); + ErrorInternalServerError("Failed to build URI") + })?; + log::trace!("Proxying request to: {}", uri); + // Handle the error conversion explicitly + let proxy_resp = create_proxy_request(req, uri, payload).await.map_err(|e| { + log::error!("Failed to create proxy request: {}", e); + ErrorInternalServerError("Failed to create proxy request") + })?; + + // Now create an HttpResponse from the proxy response + let mut client_resp = HttpResponse::build(proxy_resp.status()); + + // Stream the response body + Ok(client_resp.streaming(proxy_resp)) +} diff --git a/crates/gateway/src/proxy/test.rs b/crates/gateway/src/proxy/test.rs new file mode 100644 index 0000000..8ae5373 --- /dev/null +++ b/crates/gateway/src/proxy/test.rs @@ -0,0 +1,108 @@ +use crate::handlers::proxy::proxy; +use actix_web::{ + App, HttpRequest, HttpResponse, Responder, http, + test::{self}, + web::{self, Bytes}, +}; + +#[actix_web::test] +#[ignore] +async fn test_proxy_handler_success() { + todo!() +} + +#[actix_web::test] +async fn test_path_parsing() { + let test_cases = vec![ + ("simple_name_match", "/function/echo", "echo", "", 200), + ( + "simple_name_match", + "/function/echo.faasd-in-rs-fn", + "echo.faasd-in-rs-fn", + "", + 200, + ), + ( + "simple_name_match_with_trailing_slash", + "/function/echo/", + "echo", + "", + 200, + ), + ( + "name_match_with_additional_path_values", + "/function/echo/subPath/extras", + "echo", + "subPath/extras", + 200, + ), + ( + "name_match_with_additional_path_values_and_querystring", + "/function/echo/subPath/extras?query=true", + "echo", + "subPath/extras", + 200, + ), + ("not_found_if_no_name", "/function/", "", "", 404), + ]; + + let app = test::init_service( + App::new() + .route("/function/{name}", web::get().to(var_handler)) + .route("/function/{name}/", web::get().to(var_handler)) + .route("/function/{name}/{params:.*}", web::get().to(var_handler)), + ) + .await; + + for (name, path, function_name, extra_path, status_code) in test_cases { + let req = test::TestRequest::get().uri(path).to_request(); + let resp = test::call_service(&app, req).await; + + assert_eq!(resp.status().as_u16(), status_code, "Test case: {}", name); + + if status_code == 200 { + let body = test::read_body(resp).await; + let expected_body = format!("name: {} params: {}", function_name, extra_path); + assert_eq!(body, expected_body.as_bytes(), "Test case: {}", name); + } + } +} + +#[actix_web::test] +async fn test_invalid_method() { + let app = test::init_service( + App::new().route("/function/{name}{path:/?.*}", web::to(proxy)), + ) + .await; + + let req = test::TestRequest::with_uri("/function/test-service/path") + .method(http::Method::from_bytes(b"INVALID").unwrap()) + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), http::StatusCode::METHOD_NOT_ALLOWED); +} + +#[actix_web::test] +async fn test_empty_func_name() { + let app = test::init_service( + App::new().route("/function{name:/?}{path:/?.*}", web::to(proxy)), + ) + .await; + + let req = test::TestRequest::post() + .uri("/function") + .insert_header((http::header::CONTENT_TYPE, "application/json")) + .set_payload(Bytes::from_static(b"{\"key\":\"value\"}")) + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST); +} + +async fn var_handler(req: HttpRequest) -> impl Responder { + let vars = req.match_info(); + HttpResponse::Ok().body(format!( + "name: {} params: {}", + vars.get("name").unwrap_or(""), + vars.get("params").unwrap_or("") + )) +} diff --git a/crates/provider/src/types/config.rs b/crates/gateway/src/types/config.rs similarity index 100% rename from crates/provider/src/types/config.rs rename to crates/gateway/src/types/config.rs diff --git a/crates/gateway/src/types/function.rs b/crates/gateway/src/types/function.rs new file mode 100644 index 0000000..67de4e9 --- /dev/null +++ b/crates/gateway/src/types/function.rs @@ -0,0 +1,166 @@ +// https://github.com/openfaas/faas/blob/7803ea1861f2a22adcbcfa8c79ed539bc6506d5b/api-docs/spec.openapi.yml + +use std::{collections::HashMap, str::FromStr}; + +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Deployment { + /// Service is the name of the function deployment + pub service: String, + + /// Image is a fully-qualified container image + pub image: String, + + /// Namespace for the function, if supported by the faas-provider + pub namespace: Option, + + /// EnvProcess overrides the fprocess environment variable and can be used + /// with the watchdog + pub env_process: Option, + + /// EnvVars can be provided to set environment variables for the function runtime. + pub env_vars: Option>, + + /// Constraints are specific to the faas-provider. + pub constraints: Option>, + + /// Secrets list of secrets to be made available to function + pub secrets: Option>, + + /// Labels are metadata for functions which may be used by the + /// faas-provider or the gateway + pub labels: Option>, + + /// Annotations are metadata for functions which may be used by the + /// faas-provider or the gateway + pub annotations: Option>, + + /// Limits for function + pub limits: Option, + + /// Requests of resources requested by function + pub requests: Option, + + /// ReadOnlyRootFilesystem removes write-access from the root filesystem + /// mount-point. + #[serde(default = "default_read_only_root_filesystem")] + pub read_only_root_filesystem: bool, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Resources { + /// The amount of memory that is allocated for the function + pub memory: Option, + + /// The amount of CPU that is allocated for the function + pub cpu: Option, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Usage { + /// CPU usage increase since the last measurement, equivalent to Kubernetes' concept of millicores + pub cpu: Option, + + /// Total memory usage in bytes + pub total_memory_bytes: Option, +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Status { + /// The name of the function + pub name: String, + + /// The fully qualified docker image name of the function + pub image: String, + + /// The namespace of the function + pub namespace: Option, + + /// Process for watchdog to fork + pub env_process: Option, + + /// Environment variables for the function runtime + pub env_vars: Option>, + + /// Constraints are specific to OpenFaaS Provider + pub constraints: Option>, + + /// An array of names of secrets that are made available to the function + pub secrets: Option>, + + /// A map of labels for making scheduling or routing decisions + pub labels: Option>, + + /// A map of annotations for management, orchestration, events, and build tasks + pub annotations: Option>, + + /// Limits for function resources + pub limits: Option, + + /// Requests for function resources + pub requests: Option, + + /// Removes write-access from the root filesystem mount-point + #[serde(default = "default_read_only_root_filesystem")] + pub read_only_root_filesystem: bool, + + /// The amount of invocations for the specified function + pub invocation_count: Option, + + /// Desired amount of replicas + pub replicas: Option, + + /// The current available amount of replicas + pub available_replicas: Option, + + /// The time read back from the faas backend's data store for when the function or its container was created + pub created_at: Option, + + /// Usage statistics for the function + pub usage: Option, +} + +#[derive(Eq, Hash, PartialEq, Clone, Debug)] +pub struct Query { + /// Name of deployed function + pub service: String, + + /// Namespace of deployed function + pub namespace: Option, +} + +/// TODO: 其实应该是 try from, 排除非法的函数名 +impl FromStr for Query { + type Err = (); + + fn from_str(function_name: &str) -> Result { + Ok(if let Some(index) = function_name.rfind('.') { + Self { + service: function_name[..index].to_string(), + namespace: Some(function_name[index + 1..].to_string()), + } + } else { + Self { + service: function_name.to_string(), + namespace: Some("default".to_string()), + } + }) + } +} + +#[derive(Serialize, Deserialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Delete { + /// Name of deployed function + pub function_name: String, + pub namespace: String, +} + +const fn default_read_only_root_filesystem() -> bool { + false +} diff --git a/crates/gateway/src/types/mod.rs b/crates/gateway/src/types/mod.rs new file mode 100644 index 0000000..30a6de0 --- /dev/null +++ b/crates/gateway/src/types/mod.rs @@ -0,0 +1,2 @@ +pub mod config; +pub mod function; diff --git a/crates/my-workspace-hack/Cargo.toml b/crates/my-workspace-hack/Cargo.toml index 1af1674..44e6ad7 100644 --- a/crates/my-workspace-hack/Cargo.toml +++ b/crates/my-workspace-hack/Cargo.toml @@ -16,22 +16,24 @@ publish = false ### BEGIN HAKARI SECTION [dependencies] actix-router = { version = "0.5", default-features = false, features = ["http", "unicode"] } +byteorder = { version = "1" } bytes = { version = "1" } +chrono = { version = "0.4", features = ["serde"] } futures-channel = { version = "0.3", features = ["sink"] } futures-task = { version = "0.3", default-features = false, features = ["std"] } futures-util = { version = "0.3", features = ["channel", "io", "sink"] } log = { version = "0.4", default-features = false, features = ["std"] } -memchr = { version = "2", features = ["use_std"] } +memchr = { version = "2" } mio = { version = "1", features = ["net", "os-ext"] } prost = { version = "0.13", features = ["prost-derive"] } regex = { version = "1" } regex-automata = { version = "0.4", default-features = false, features = ["dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "unicode"] } regex-syntax = { version = "0.8" } +scopeguard = { version = "1" } serde = { version = "1", features = ["derive"] } smallvec = { version = "1", default-features = false, features = ["const_new"] } tokio = { version = "1", features = ["full"] } -tokio-util = { version = "0.7", features = ["codec", "io"] } -tower = { version = "0.4", features = ["balance", "buffer", "limit", "util"] } +tokio-util = { version = "0.7", features = ["full"] } tracing = { version = "0.1", features = ["log"] } tracing-core = { version = "0.1", default-features = false, features = ["std"] } @@ -39,7 +41,7 @@ tracing-core = { version = "0.1", default-features = false, features = ["std"] } actix-router = { version = "0.5", default-features = false, features = ["http", "unicode"] } bytes = { version = "1" } log = { version = "0.4", default-features = false, features = ["std"] } -memchr = { version = "2", features = ["use_std"] } +memchr = { version = "2" } prost = { version = "0.13", features = ["prost-derive"] } regex = { version = "1" } regex-automata = { version = "0.4", default-features = false, features = ["dfa-onepass", "hybrid", "meta", "nfa-backtrack", "perf-inline", "perf-literal", "unicode"] } @@ -50,18 +52,22 @@ tracing = { version = "0.1", features = ["log"] } tracing-core = { version = "0.1", default-features = false, features = ["std"] } [target.x86_64-unknown-linux-gnu.dependencies] +bitflags = { version = "2", default-features = false, features = ["std"] } getrandom = { version = "0.2", default-features = false, features = ["std"] } libc = { version = "0.2", features = ["extra_traits"] } [target.x86_64-unknown-linux-gnu.build-dependencies] +bitflags = { version = "2", default-features = false, features = ["std"] } getrandom = { version = "0.2", default-features = false, features = ["std"] } libc = { version = "0.2", features = ["extra_traits"] } [target.aarch64-unknown-linux-gnu.dependencies] +bitflags = { version = "2", default-features = false, features = ["std"] } getrandom = { version = "0.2", default-features = false, features = ["std"] } libc = { version = "0.2", features = ["extra_traits"] } [target.aarch64-unknown-linux-gnu.build-dependencies] +bitflags = { version = "2", default-features = false, features = ["std"] } getrandom = { version = "0.2", default-features = false, features = ["std"] } libc = { version = "0.2", features = ["extra_traits"] } diff --git a/crates/provider/src/bootstrap/mod.rs b/crates/provider/src/bootstrap/mod.rs deleted file mode 100644 index 2ff380a..0000000 --- a/crates/provider/src/bootstrap/mod.rs +++ /dev/null @@ -1,103 +0,0 @@ -use actix_web::{App, HttpServer, middleware, web}; -use prometheus::Registry; -use std::collections::HashMap; - -use crate::{ - handlers, - metrics::{self, HttpMetrics}, - //httputil, - //proxy, - types::config::FaaSConfig, -}; - -//用于函数/服务名称的表达式 -#[allow(dead_code)] -const NAME_EXPRESSION: &str = r"-a-zA-Z_0-9\."; - -//应用程序状态,存储共享的数据,如配置、指标、认证信息等,为业务函数提供支持 -#[derive(Clone)] -#[allow(dead_code)] -struct AppState { - config: FaaSConfig, //应用程序的配置,用于识别是否开启Basic Auth等 - metrics: HttpMetrics, //用于监视http请求的持续时间和总数 - credentials: Option>, //当有认证信息的时候,获取认证信息 -} - -//serve 把处理程序headlers load到正确路由规范。这个函数是阻塞的。 -#[allow(dead_code)] -async fn serve() -> std::io::Result<()> { - let config = FaaSConfig::new(); //加载配置,用于识别是否开启Basic Auth等 - let _registry = Registry::new(); - let metrics = metrics::HttpMetrics::new(); //metrics监视http请求的持续时间和总数 - - // 用于存储应用程序状态的结构体 - let app_state = AppState { - config: config.clone(), - metrics: metrics.clone(), - credentials: None, - }; - - // 如果启用了Basic Auth,从指定路径读取认证凭证并存储在应用程序状态中 - if config.enable_basic_auth { - todo!("implement authentication"); - } - - HttpServer::new(move || { - App::new() - .app_data(web::Data::new(app_state.clone())) // 将app_state存储在web::Data中,以便在处理程序中访问 - .wrap(middleware::Logger::default()) // 记录请求日志 - .service( - web::scope("/system") - .service( - web::resource("/functions") - .route(web::get().to(handlers::function_lister)) - .route(web::post().to(handlers::deploy_function)) - .route(web::delete().to(handlers::delete_function)) - .route(web::put().to(handlers::update_function)), - ) - .service( - web::resource("/function/{name}") - .route(web::get().to(handlers::function_status)), - ) - .service( - web::resource("/scale-function/{name}") - .route(web::post().to(handlers::scale_function)), - ) - .service(web::resource("/info").route(web::get().to(handlers::info))) - .service( - web::resource("/secrets") - .route(web::get().to(handlers::secrets)) - .route(web::post().to(handlers::secrets)) - .route(web::put().to(handlers::secrets)) - .route(web::delete().to(handlers::secrets)), - ) - .service(web::resource("/logs").route(web::get().to(handlers::logs))) - .service( - web::resource("/namespaces") - .route(web::get().to(handlers::list_namespaces)) - .route(web::post().to(handlers::mutate_namespace)), - ), - ) - .service( - web::scope("/function") - .service( - web::resource("/{name}") - .route(web::get().to(handlers::function_proxy)) - .route(web::post().to(handlers::function_proxy)), - ) - .service( - web::resource("/{name}/{params:.*}") - .route(web::get().to(handlers::function_proxy)) - .route(web::post().to(handlers::function_proxy)), - ), - ) - .route("/metrics", web::get().to(handlers::telemetry)) - .route("/healthz", web::get().to(handlers::health)) - }) - .bind(("0.0.0.0", config.tcp_port.unwrap_or(8080)))? - .run() - .await -} - -//当上下文完成的时候关闭服务器 -//无法关闭时候写进log,并且返回错误 diff --git a/crates/provider/src/config/mod.rs b/crates/provider/src/config/mod.rs deleted file mode 100644 index 8b13789..0000000 --- a/crates/provider/src/config/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/provider/src/consts.rs b/crates/provider/src/consts.rs deleted file mode 100644 index 6158c0a..0000000 --- a/crates/provider/src/consts.rs +++ /dev/null @@ -1,14 +0,0 @@ -#[allow(unused)] -pub const DEFAULT_FUNCTION_NAMESPACE: &str = "default"; - -#[allow(unused)] -pub const NAMESPACE_LABEL: &str = "faasrs"; - -#[allow(unused)] -pub const FAASRS_NAMESPACE: &str = "faasrs"; - -#[allow(unused)] -pub const FAASRS_SERVICE_PULL_ALWAYS: bool = false; - -#[allow(unused)] -pub const DEFAULT_SNAPSHOTTER: &str = "overlayfs"; diff --git a/crates/provider/src/handlers/delete.rs b/crates/provider/src/handlers/delete.rs deleted file mode 100644 index 413d9f6..0000000 --- a/crates/provider/src/handlers/delete.rs +++ /dev/null @@ -1,68 +0,0 @@ -use crate::{ - consts, - handlers::{function_get::get_function, utils::CustomError}, -}; -use actix_web::{HttpResponse, Responder, web}; -use serde::{Deserialize, Serialize}; -use service::containerd_manager::ContainerdManager; - -use super::function_list::Function; - -// 参考响应状态:https://github.com/openfaas/faas/blob/7803ea1861f2a22adcbcfa8c79ed539bc6506d5b/api-docs/spec.openapi.yml#L141C2-L162C45 -// 请求体反序列化失败,自动返回400错误 -pub async fn delete_handler(info: web::Json) -> impl Responder { - let function_name = info.function_name.clone(); - let namespace = info - .namespace - .clone() - .unwrap_or_else(|| consts::DEFAULT_FUNCTION_NAMESPACE.to_string()); - - let namespaces = ContainerdManager::list_namespaces().await.unwrap(); - if !namespaces.contains(&namespace.to_string()) { - return HttpResponse::NotFound().body(format!("Namespace '{}' does not exist", namespace)); - } - - let function = match get_function(&function_name, &namespace).await { - Ok(function) => function, - Err(e) => { - log::error!("Failed to get function: {}", e); - return HttpResponse::NotFound().body(format!( - "Function '{}' not found in namespace '{}'", - function_name, namespace - )); - } - }; - - match delete(&function, &namespace).await { - Ok(()) => { - HttpResponse::Ok().body(format!("Function {} deleted successfully.", function_name)) - } - Err(e) => { - HttpResponse::InternalServerError().body(format!("Failed to delete function: {}", e)) - } - } -} - -async fn delete(function: &Function, namespace: &str) -> Result<(), CustomError> { - let function_name = function.name.clone(); - if function.replicas != 0 { - log::info!("function.replicas: {:?}", function.replicas); - cni::delete_cni_network(namespace, &function_name); - log::info!("delete_cni_network ok"); - } else { - log::info!("function.replicas: {:?}", function.replicas); - } - ContainerdManager::delete_container(&function_name, namespace) - .await - .map_err(|e| { - log::error!("Failed to delete container: {}", e); - CustomError::OtherError(format!("Failed to delete container: {}", e)) - })?; - Ok(()) -} - -#[derive(Serialize, Deserialize)] -pub struct DeleteContainerInfo { - pub function_name: String, - pub namespace: Option, -} diff --git a/crates/provider/src/handlers/deploy.rs b/crates/provider/src/handlers/deploy.rs deleted file mode 100644 index bd7c687..0000000 --- a/crates/provider/src/handlers/deploy.rs +++ /dev/null @@ -1,77 +0,0 @@ -use crate::{consts, handlers::utils::CustomError, types::function_deployment::DeployFunctionInfo}; -use actix_web::{HttpResponse, Responder, web}; - -use service::{containerd_manager::ContainerdManager, image_manager::ImageManager}; - -// 参考响应状态 https://github.com/openfaas/faas/blob/7803ea1861f2a22adcbcfa8c79ed539bc6506d5b/api-docs/spec.openapi.yml#L121C1-L140C45 -// 请求体反序列化失败,自动返回400错误 -pub async fn deploy_handler(info: web::Json) -> impl Responder { - let image = info.image.clone(); - let function_name = info.function_name.clone(); - let namespace = info - .namespace - .clone() - .unwrap_or(consts::DEFAULT_FUNCTION_NAMESPACE.to_string()); - - log::info!("Namespace '{}' validated.", &namespace); - - let container_list = match ContainerdManager::list_container_into_string(&namespace).await { - Ok(container_list) => container_list, - Err(e) => { - log::error!("Failed to list container: {}", e); - return HttpResponse::InternalServerError() - .body(format!("Failed to list container: {}", e)); - } - }; - - if container_list.contains(&function_name) { - return HttpResponse::BadRequest().body(format!( - "Function '{}' already exists in namespace '{}'", - function_name, namespace - )); - } - - match deploy(&function_name, &image, &namespace).await { - Ok(()) => HttpResponse::Accepted().body(format!( - "Function {} deployment initiated successfully.", - function_name - )), - Err(e) => HttpResponse::BadRequest().body(format!( - "failed to deploy function {}, because {}", - function_name, e - )), - } -} - -async fn deploy(function_name: &str, image: &str, namespace: &str) -> Result<(), CustomError> { - ImageManager::prepare_image(image, namespace, true) - .await - .map_err(CustomError::from)?; - log::info!("Image '{}' validated ,", image); - - ContainerdManager::create_container(image, function_name, namespace) - .await - .map_err(|e| CustomError::OtherError(format!("failed to create container:{}", e)))?; - - log::info!( - "Container {} created using image {} in namespace {}", - function_name, - image, - namespace - ); - - ContainerdManager::new_task(function_name, namespace) - .await - .map_err(|e| { - CustomError::OtherError(format!( - "failed to start task for container {},{}", - function_name, e - )) - })?; - log::info!( - "Task for container {} was created successfully", - function_name - ); - - Ok(()) -} diff --git a/crates/provider/src/handlers/function_get.rs b/crates/provider/src/handlers/function_get.rs deleted file mode 100644 index 4cc8e54..0000000 --- a/crates/provider/src/handlers/function_get.rs +++ /dev/null @@ -1,146 +0,0 @@ -use crate::handlers::function_list::Function; -// use service::spec::{ Mount, Spec}; -use actix_web::cookie::time::Duration; -use service::{FunctionScope, containerd_manager::ContainerdManager, image_manager::ImageManager}; -use std::{collections::HashMap, time::UNIX_EPOCH}; -use thiserror::Error; - -const ANNOTATION_LABEL_PREFIX: &str = "com.openfaas.annotations."; - -#[derive(Error, Debug)] -pub enum FunctionError { - #[error("Function not found: {0}")] - FunctionNotFound(String), - #[error("Runtime Config not found: {0}")] - RuntimeConfigNotFound(String), -} - -impl From> for FunctionError { - fn from(error: Box) -> Self { - FunctionError::FunctionNotFound(error.to_string()) - } -} - -pub async fn get_function(function_name: &str, namespace: &str) -> Result { - let cid = function_name; - let function = FunctionScope { - function_name: cid.to_string(), - namespace: namespace.to_string(), - }; - let address = ContainerdManager::get_address(&function); - - let container = ContainerdManager::load_container(cid, namespace) - .await - .map_err(|e| FunctionError::FunctionNotFound(e.to_string()))? - .unwrap_or_default(); - - let container_name = container.id.to_string(); - let image = container.image.clone(); - let mut pid = 0; - let mut replicas = 0; - - let all_labels = container.labels; - let (labels, _) = build_labels_and_annotations(all_labels); - - let env = ImageManager::get_runtime_config(&image) - .map_err(|e| FunctionError::RuntimeConfigNotFound(e.to_string()))? - .env; - let (env_vars, env_process) = read_env_from_process_env(env); - // let secrets = read_secrets_from_mounts(&spec.mounts); - // let memory_limit = read_memory_limit_from_spec(&spec); - let timestamp = container.created_at.unwrap_or_default(); - let created_at = UNIX_EPOCH + Duration::new(timestamp.seconds, timestamp.nanos); - - let task = ContainerdManager::get_task(cid, namespace) - .await - .map_err(|e| FunctionError::FunctionNotFound(e.to_string())); - match task { - Ok(task) => { - let status = task.status; - if status == 2 || status == 3 { - pid = task.pid; - replicas = 1; - } - } - Err(e) => { - log::error!("Failed to get task: {}", e); - replicas = 0; - } - } - - Ok(Function { - name: container_name, - namespace: namespace.to_string(), - image, - pid, - replicas, - address, - labels, - env_vars, - env_process, - created_at, - }) -} - -fn build_labels_and_annotations( - ctr_labels: HashMap, -) -> (HashMap, HashMap) { - let mut labels = HashMap::new(); - let mut annotations = HashMap::new(); - - for (k, v) in ctr_labels { - if k.starts_with(ANNOTATION_LABEL_PREFIX) { - annotations.insert(k.trim_start_matches(ANNOTATION_LABEL_PREFIX).to_string(), v); - } else { - labels.insert(k, v); - } - } - - (labels, annotations) -} - -fn read_env_from_process_env(env: Vec) -> (HashMap, String) { - let mut found_env = HashMap::new(); - let mut fprocess = String::new(); - - for e in env { - let kv: Vec<&str> = e.splitn(2, '=').collect(); - if kv.len() == 1 { - continue; - } - if kv[0] == "PATH" { - continue; - } - if kv[0] == "fprocess" { - fprocess = kv[1].to_string(); - continue; - } - found_env.insert(kv[0].to_string(), kv[1].to_string()); - } - - (found_env, fprocess) -} - -// fn read_secrets_from_mounts(mounts: &[Mount]) -> Vec { -// let mut secrets = Vec::new(); -// for mnt in mounts { -// let parts: Vec<&str> = mnt.destination.split("/var/openfaas/secrets/").collect(); -// if parts.len() > 1 { -// secrets.push(parts[1].to_string()); -// } -// } -// secrets -// } - -// fn read_memory_limit_from_spec(spec: &Spec) -> i64 { -// match &spec.linux { -// linux => match &linux.resources { -// resources => match &resources.memory { -// Some(memory) => memory.limit.unwrap_or(0), -// None => 0, -// }, -// _ => 0, -// }, -// _ => 0, -// } -// } diff --git a/crates/provider/src/handlers/function_list.rs b/crates/provider/src/handlers/function_list.rs deleted file mode 100644 index 54f53d6..0000000 --- a/crates/provider/src/handlers/function_list.rs +++ /dev/null @@ -1,74 +0,0 @@ -use std::{collections::HashMap, time::SystemTime}; - -use actix_web::{HttpRequest, HttpResponse, Responder}; -use serde::{Deserialize, Serialize}; -use service::containerd_manager::ContainerdManager; - -use super::{function_get::get_function, utils::CustomError}; - -#[derive(Debug, Serialize, Deserialize)] -pub struct Function { - pub name: String, - pub namespace: String, - pub image: String, - pub pid: u32, - pub replicas: i32, - pub address: String, - pub labels: HashMap, - // pub annotations: HashMap, - // pub secrets: Vec, - pub env_vars: HashMap, - pub env_process: String, - // pub memory_limit: i64, - pub created_at: SystemTime, -} - -// openfaas API文档和faasd源码的响应不能完全对齐,这里参考源码的响应码设置 -// 考虑到部分操作可能返回500错误,但是faasd并没有做internal server error的处理(可能上层有中间件捕获),这里应该需要做500的处理 -pub async fn function_list_handler(req: HttpRequest) -> impl Responder { - let namespace = req.match_info().get("namespace").unwrap_or(""); - if namespace.is_empty() { - return HttpResponse::BadRequest().body("provide namespace in path"); - } - let namespaces = match ContainerdManager::list_namespaces().await { - Ok(namespace) => namespace, - Err(e) => { - return HttpResponse::InternalServerError() - .body(format!("Failed to list namespaces:{}", e)); - } - }; - if !namespaces.contains(&namespace.to_string()) { - return HttpResponse::BadRequest() - .body(format!("Namespace '{}' does not exist", namespace)); - } - - let container_list = match ContainerdManager::list_container_into_string(namespace).await { - Ok(container_list) => container_list, - Err(e) => { - return HttpResponse::InternalServerError() - .body(format!("Failed to list container:{}", e)); - } - }; - log::info!("container_list: {:?}", container_list); - - match get_function_list(container_list, namespace).await { - Ok(functions) => HttpResponse::Ok().body(serde_json::to_string(&functions).unwrap()), - Err(e) => HttpResponse::BadRequest().body(format!("Failed to get function list: {}", e)), - } -} - -async fn get_function_list( - container_list: Vec, - namespace: &str, -) -> Result, CustomError> { - let mut functions: Vec = Vec::new(); - for cid in container_list { - log::info!("cid: {}", cid); - let function = match get_function(&cid, namespace).await { - Ok(function) => function, - Err(e) => return Err(CustomError::FunctionError(e)), - }; - functions.push(function); - } - Ok(functions) -} diff --git a/crates/provider/src/handlers/invoke_resolver.rs b/crates/provider/src/handlers/invoke_resolver.rs deleted file mode 100644 index bef03fd..0000000 --- a/crates/provider/src/handlers/invoke_resolver.rs +++ /dev/null @@ -1,54 +0,0 @@ -use crate::consts::DEFAULT_FUNCTION_NAMESPACE; -use crate::handlers::function_get::get_function; -use actix_web::{Error, error::ErrorInternalServerError, error::ErrorServiceUnavailable}; -use log; -use url::Url; - -#[derive(Clone)] -pub struct InvokeResolver; - -impl InvokeResolver { - pub async fn resolve_function_url(function_name: &str) -> Result { - //根据函数名和containerd获取函数ip, - //从函数名称中提取命名空间。如果函数名称中包含 .,则将其后的部分作为命名空间;否则使用默认命名空间 - - let mut actual_function_name = function_name; - let namespace = - extract_namespace_from_function_or_default(function_name, DEFAULT_FUNCTION_NAMESPACE); - if function_name.contains('.') { - actual_function_name = function_name.trim_end_matches(&format!(".{}", namespace)); - } - - let function = match get_function(actual_function_name, &namespace).await { - Ok(function) => function, - Err(e) => { - log::error!("Failed to get function:{}", e); - return Err(ErrorServiceUnavailable("Failed to get function")); - } - }; - log::info!("Function:{:?}", function); - - let address = function.address.clone(); - let urlstr = format!("http://{}", address); - match Url::parse(&urlstr) { - Ok(url) => Ok(url), - Err(e) => { - log::error!("Failed to resolve url:{}", e); - Err(ErrorInternalServerError("Failed to resolve URL")) - } - } - } -} - -fn extract_namespace_from_function_or_default( - function_name: &str, - default_namespace: &str, -) -> String { - let mut namespace = default_namespace.to_string(); - if function_name.contains('.') { - if let Some(index) = function_name.rfind('.') { - namespace = function_name[index + 1..].to_string(); - } - } - namespace -} diff --git a/crates/provider/src/handlers/mod.rs b/crates/provider/src/handlers/mod.rs deleted file mode 100644 index 54f986e..0000000 --- a/crates/provider/src/handlers/mod.rs +++ /dev/null @@ -1,111 +0,0 @@ -pub mod delete; -pub mod deploy; -pub mod function_get; -pub mod function_list; -pub mod invoke_resolver; -pub mod utils; - -use actix_web::{HttpRequest, HttpResponse, Responder}; - -pub async fn function_lister(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("函数列表") -} - -pub async fn deploy_function(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("部署函数") -} - -pub async fn delete_function(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("删除函数") -} - -pub async fn update_function(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("更新函数") -} - -pub async fn function_status(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("函数状态") -} - -pub async fn scale_function(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("扩展函数") -} - -pub async fn info(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("信息") -} - -pub async fn secrets(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("秘密") -} - -pub async fn logs(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("日志") -} - -pub async fn list_namespaces(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("命名空间列表") -} - -pub async fn mutate_namespace(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("变更命名空间") -} - -pub async fn function_proxy(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("函数代理") -} - -pub async fn telemetry(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("遥测") -} - -pub async fn health(_req: HttpRequest) -> impl Responder { - HttpResponse::Ok().body("健康检查") -} - -// lazy_static! { -// pub static ref HANDLERS: HashMap> = { -// let mut map = HashMap::new(); -// map.insert( -// "function_list".to_string(), -// Box::new(function_list::FunctionLister), -// ); -// map.insert( -// "namespace_list".to_string(), -// Box::new(namespace_list::NamespaceLister), -// ); -// map -// }; -// } - -#[derive(Debug, thiserror::Error)] -pub struct FaasError { - message: String, - error_type: FaasErrorType, - #[source] - source: Option>, -} - -#[derive(Debug)] -pub enum FaasErrorType { - ContainerFailure, - Timeout, - InternalError, -} - -impl std::fmt::Display for FaasError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "[{:?}] {}", self.error_type, self.message) - } -} - -// 实现从常见错误类型转换 -impl From for FaasError { - fn from(err: std::io::Error) -> Self { - FaasError { - message: format!("IO error: {}", err), - error_type: FaasErrorType::InternalError, - source: Some(Box::new(err)), - } - } -} diff --git a/crates/provider/src/httputils/mod.rs b/crates/provider/src/httputils/mod.rs deleted file mode 100644 index 8b13789..0000000 --- a/crates/provider/src/httputils/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/provider/src/lib.rs b/crates/provider/src/lib.rs deleted file mode 100644 index 437d4a0..0000000 --- a/crates/provider/src/lib.rs +++ /dev/null @@ -1,9 +0,0 @@ -pub mod bootstrap; -pub mod config; -pub mod consts; -pub mod handlers; -pub mod httputils; -pub mod logs; -pub mod metrics; -pub mod proxy; -pub mod types; diff --git a/crates/provider/src/logs/mod.rs b/crates/provider/src/logs/mod.rs deleted file mode 100644 index 8b13789..0000000 --- a/crates/provider/src/logs/mod.rs +++ /dev/null @@ -1 +0,0 @@ - diff --git a/crates/provider/src/proxy/proxy_handler.rs b/crates/provider/src/proxy/proxy_handler.rs deleted file mode 100644 index 69147af..0000000 --- a/crates/provider/src/proxy/proxy_handler.rs +++ /dev/null @@ -1,59 +0,0 @@ -use crate::handlers::invoke_resolver::InvokeResolver; -use crate::proxy::builder::create_proxy_request; - -use actix_web::{ - HttpRequest, HttpResponse, - error::{ErrorBadRequest, ErrorInternalServerError, ErrorMethodNotAllowed}, - http::Method, - web, -}; - -// 主要参考源码的响应设置 -pub async fn proxy_handler( - req: HttpRequest, - payload: web::Payload, -) -> actix_web::Result { - match *req.method() { - Method::POST - | Method::PUT - | Method::DELETE - | Method::GET - | Method::PATCH - | Method::HEAD - | Method::OPTIONS => proxy_request(&req, payload).await, - _ => Err(ErrorMethodNotAllowed("Method not allowed")), - } -} - -//根据原始请求,解析url,构建转发请求并转发,获取响应 -async fn proxy_request( - req: &HttpRequest, - payload: web::Payload, -) -> actix_web::Result { - let function_name = req.match_info().get("name").unwrap_or(""); - if function_name.is_empty() { - return Err(ErrorBadRequest("Function name is required")); - } - - let function_addr = InvokeResolver::resolve_function_url(function_name).await?; - - let proxy_req = create_proxy_request(req, &function_addr, payload); - - // Handle the error conversion explicitly - let proxy_resp = match proxy_req.await { - Ok(resp) => resp, - Err(e) => { - log::error!("Proxy request failed: {}", e); - return Err(ErrorInternalServerError(format!( - "Proxy request failed: {}", - e - ))); - } - }; - - // Now create an HttpResponse from the proxy response - let mut client_resp = HttpResponse::build(proxy_resp.status()); - - // Stream the response body - Ok(client_resp.streaming(proxy_resp)) -} diff --git a/crates/provider/src/proxy/proxy_handler_test.rs b/crates/provider/src/proxy/proxy_handler_test.rs deleted file mode 100644 index 38391cd..0000000 --- a/crates/provider/src/proxy/proxy_handler_test.rs +++ /dev/null @@ -1,127 +0,0 @@ -#[cfg(test)] -mod test { - use crate::proxy::proxy_handler::proxy_handler; - use actix_web::{ - App, HttpRequest, HttpResponse, Responder, http, - test::{self}, - web::{self, Bytes}, - }; - - #[actix_web::test] - #[ignore] - async fn test_proxy_handler_success() { - todo!() - } - - #[actix_web::test] - async fn test_path_parsing() { - let test_cases = vec![ - ("simple_name_match", "/function/echo", "echo", "", 200), - ( - "simple_name_match", - "/function/echo.faasd-in-rs-fn", - "echo.faasd-in-rs-fn", - "", - 200, - ), - ( - "simple_name_match_with_trailing_slash", - "/function/echo/", - "echo", - "", - 200, - ), - ( - "name_match_with_additional_path_values", - "/function/echo/subPath/extras", - "echo", - "subPath/extras", - 200, - ), - ( - "name_match_with_additional_path_values_and_querystring", - "/function/echo/subPath/extras?query=true", - "echo", - "subPath/extras", - 200, - ), - ("not_found_if_no_name", "/function/", "", "", 404), - ]; - - let app = test::init_service( - App::new() - .route("/function/{name}", web::get().to(var_handler)) - .route("/function/{name}/", web::get().to(var_handler)) - .route("/function/{name}/{params:.*}", web::get().to(var_handler)), - ) - .await; - - for (name, path, function_name, extra_path, status_code) in test_cases { - let req = test::TestRequest::get().uri(path).to_request(); - let resp = test::call_service(&app, req).await; - - assert_eq!(resp.status().as_u16(), status_code, "Test case: {}", name); - - if status_code == 200 { - let body = test::read_body(resp).await; - let expected_body = format!("name: {} params: {}", function_name, extra_path); - assert_eq!(body, expected_body.as_bytes(), "Test case: {}", name); - } - } - } - - #[actix_web::test] - async fn test_handler_func_invalid_method() { - let app = test::init_service( - App::new().route("/function/{name}{path:/?.*}", web::to(proxy_handler)), - ) - .await; - - let req = test::TestRequest::with_uri("/function/test-service/path") - .method(http::Method::from_bytes(b"INVALID").unwrap()) - .to_request(); - let resp = test::call_service(&app, req).await; - assert_eq!(resp.status(), http::StatusCode::METHOD_NOT_ALLOWED); - } - - #[actix_web::test] - async fn test_handler_func_empty_function_nam() { - let app = test::init_service( - App::new().route("/function{name:/?}{path:/?.*}", web::to(proxy_handler)), - ) - .await; - - let req = test::TestRequest::post() - .uri("/function") - .insert_header((http::header::CONTENT_TYPE, "application/json")) - .set_payload(Bytes::from_static(b"{\"key\":\"value\"}")) - .to_request(); - let resp = test::call_service(&app, req).await; - assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST); - } - - #[actix_web::test] - async fn test_handler_func_empty_function_name() { - let app = test::init_service( - App::new().route("/function{name:/?}{path:/?.*}", web::to(proxy_handler)), - ) - .await; - - let req = test::TestRequest::post() - .uri("/function") - .insert_header((http::header::CONTENT_TYPE, "application/json")) - .set_payload(Bytes::from_static(b"{\"key\":\"value\"}")) - .to_request(); - let resp = test::call_service(&app, req).await; - assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST); - } - - async fn var_handler(req: HttpRequest) -> impl Responder { - let vars = req.match_info(); - HttpResponse::Ok().body(format!( - "name: {} params: {}", - vars.get("name").unwrap_or(""), - vars.get("params").unwrap_or("") - )) - } -} diff --git a/crates/provider/src/types/function_deployment.rs b/crates/provider/src/types/function_deployment.rs deleted file mode 100644 index 4c33633..0000000 --- a/crates/provider/src/types/function_deployment.rs +++ /dev/null @@ -1,71 +0,0 @@ -use serde::{Deserialize, Serialize}; -//use std::collections::HashMap; - -#[derive(Serialize, Deserialize, Debug)] -pub struct FunctionDeployment { - /// Service is the name of the function deployment - pub service: String, - - /// Image is a fully-qualified container image - pub image: String, - - /// Namespace for the function, if supported by the faas-provider - #[serde(skip_serializing_if = "Option::is_none")] - pub namespace: Option, - // /// EnvProcess overrides the fprocess environment variable and can be used - // /// with the watchdog - // #[serde(rename = "envProcess", skip_serializing_if = "Option::is_none")] - // pub env_process: Option, - - // /// EnvVars can be provided to set environment variables for the function runtime. - // #[serde(skip_serializing_if = "Option::is_none")] - // pub env_vars: Option>, - - // /// Constraints are specific to the faas-provider. - // #[serde(skip_serializing_if = "Option::is_none")] - // pub constraints: Option>, - - // /// Secrets list of secrets to be made available to function - // #[serde(skip_serializing_if = "Option::is_none")] - // pub secrets: Option>, - - // /// Labels are metadata for functions which may be used by the - // /// faas-provider or the gateway - // #[serde(skip_serializing_if = "Option::is_none")] - // pub labels: Option>, - - // /// Annotations are metadata for functions which may be used by the - // /// faas-provider or the gateway - // #[serde(skip_serializing_if = "Option::is_none")] - // pub annotations: Option>, - - // /// Limits for function - // #[serde(skip_serializing_if = "Option::is_none")] - // pub limits: Option, - - // /// Requests of resources requested by function - // #[serde(skip_serializing_if = "Option::is_none")] - // pub requests: Option, - - // /// ReadOnlyRootFilesystem removes write-access from the root filesystem - // /// mount-point. - // #[serde(rename = "readOnlyRootFilesystem", default)] - // pub read_only_root_filesystem: bool, -} - -// #[derive(Debug, Serialize, Deserialize)] -// pub struct FunctionResources { -// #[serde(skip_serializing_if = "Option::is_none")] -// pub memory: Option, - -// #[serde(skip_serializing_if = "Option::is_none")] -// pub cpu: Option, -// } -#[derive(serde::Deserialize)] -pub struct DeployFunctionInfo { - pub function_name: String, - pub image: String, - - #[serde(skip_serializing_if = "Option::is_none")] - pub namespace: Option, -} diff --git a/crates/provider/src/types/mod.rs b/crates/provider/src/types/mod.rs deleted file mode 100644 index e6e144a..0000000 --- a/crates/provider/src/types/mod.rs +++ /dev/null @@ -1,2 +0,0 @@ -pub mod config; -pub mod function_deployment; diff --git a/crates/service/Cargo.toml b/crates/service/Cargo.toml deleted file mode 100644 index 872590d..0000000 --- a/crates/service/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "service" -version = "0.1.0" -edition = "2024" - -[dependencies] -containerd-client = "0.8" -tokio = { version = "1", features = ["full"] } -tonic = "0.12" -serde = { version = "1.0", features = ["derive"] } -serde_json = "1.0" -log = "0.4" -env_logger = "0.10" -prost-types = "0.13.4" -oci-spec = "0.6" -sha2 = "0.10" -hex = "0.4" -my-workspace-hack = { version = "0.1", path = "../my-workspace-hack" } -cni = { version = "0.1", path = "../cni" } -handlebars= "4.1.0" -lazy_static = "1.4" \ No newline at end of file diff --git a/crates/service/src/containerd_manager.rs b/crates/service/src/containerd_manager.rs deleted file mode 100644 index 1447a29..0000000 --- a/crates/service/src/containerd_manager.rs +++ /dev/null @@ -1,599 +0,0 @@ -use std::{fs, panic, sync::Arc}; - -use containerd_client::{ - Client, - services::v1::{ - Container, CreateContainerRequest, CreateTaskRequest, DeleteContainerRequest, - DeleteTaskRequest, KillRequest, ListContainersRequest, ListNamespacesRequest, - ListTasksRequest, ListTasksResponse, StartRequest, WaitRequest, WaitResponse, - container::Runtime, - snapshots::{MountsRequest, PrepareSnapshotRequest}, - }, - tonic::Request, - types::{Mount, v1::Process}, - with_namespace, -}; -use prost_types::Any; -use sha2::{Digest, Sha256}; -use tokio::{ - sync::OnceCell, - time::{Duration, timeout}, -}; - -use crate::{ - FunctionScope, GLOBAL_NETNS_MAP, NetworkConfig, image_manager::ImageManager, - spec::generate_spec, -}; - -pub(super) static CLIENT: OnceCell> = OnceCell::const_new(); - -#[derive(Debug)] -pub struct ContainerdManager; - -impl ContainerdManager { - pub async fn init(socket_path: &str) { - if let Err(e) = CLIENT.set(Arc::new(Client::from_path(socket_path).await.unwrap())) { - panic!("Failed to set client: {}", e); - } - let _ = cni::init_net_work(); - log::info!("ContainerdManager initialized"); - } - - async fn get_client() -> Arc { - CLIENT - .get() - .unwrap_or_else(|| panic!("Client not initialized, Please run init first")) - .clone() - } - - /// 创建容器 - pub async fn create_container( - image_name: &str, - cid: &str, - ns: &str, - ) -> Result<(), ContainerdError> { - Self::prepare_snapshot(image_name, cid, ns) - .await - .map_err(|e| { - log::error!("Failed to create container: {}", e); - ContainerdError::CreateContainerError(e.to_string()) - })?; - - let spec = Self::get_spec(cid, ns, image_name).unwrap(); - - let container = Container { - id: cid.to_string(), - image: image_name.to_string(), - runtime: Some(Runtime { - name: "io.containerd.runc.v2".to_string(), - options: None, - }), - spec, - snapshotter: "overlayfs".to_string(), - snapshot_key: cid.to_string(), - ..Default::default() - }; - - Self::do_create_container(container, ns).await?; - Self::prepare_cni_network(cid, ns, image_name)?; - - Ok(()) - } - - async fn do_create_container(container: Container, ns: &str) -> Result<(), ContainerdError> { - let mut cc = Self::get_client().await.containers(); - let req = CreateContainerRequest { - container: Some(container), - }; - let _resp = cc.create(with_namespace!(req, ns)).await.map_err(|e| { - log::error!("Failed to create container: {}", e); - ContainerdError::CreateContainerError(e.to_string()) - })?; - Ok(()) - } - - /// 删除容器 - pub async fn delete_container(cid: &str, ns: &str) -> Result<(), ContainerdError> { - let container_list = Self::list_container(ns).await?; - if !container_list.iter().any(|container| container.id == cid) { - log::info!("Container {} not found", cid); - return Ok(()); - } - - let resp = Self::list_task_by_cid(cid, ns).await?; - if let Some(task) = resp.tasks.iter().find(|task| task.id == cid) { - log::info!("Task found: {}, Status: {}", task.id, task.status); - // TASK_UNKNOWN (0) — 未知状态 - // TASK_CREATED (1) — 任务已创建 - // TASK_RUNNING (2) — 任务正在运行 - // TASK_STOPPED (3) — 任务已停止 - // TASK_EXITED (4) — 任务已退出 - // TASK_PAUSED (5) — 任务已暂停 - // TASK_FAILED (6) — 任务失败 - Self::kill_task_with_timeout(cid, ns).await?; - } - - Self::do_delete_container(cid, ns).await?; - - Self::remove_cni_network(cid, ns).map_err(|e| { - log::error!("Failed to remove CNI network: {}", e); - ContainerdError::CreateTaskError(e.to_string()) - })?; - Ok(()) - } - - async fn do_delete_container(cid: &str, ns: &str) -> Result<(), ContainerdError> { - let mut cc = Self::get_client().await.containers(); - let delete_request = DeleteContainerRequest { - id: cid.to_string(), - }; - - let _ = cc - .delete(with_namespace!(delete_request, ns)) - .await - .expect("Failed to delete container"); - - Ok(()) - } - - /// 创建并启动任务 - pub async fn new_task(cid: &str, ns: &str) -> Result<(), ContainerdError> { - let mounts = Self::get_mounts(cid, ns).await?; - Self::do_create_task(cid, ns, mounts).await?; - Self::do_start_task(cid, ns).await?; - Ok(()) - } - - async fn do_start_task(cid: &str, ns: &str) -> Result<(), ContainerdError> { - let mut c = Self::get_client().await.tasks(); - let req = StartRequest { - container_id: cid.to_string(), - ..Default::default() - }; - let _resp = c.start(with_namespace!(req, ns)).await.map_err(|e| { - log::error!("Failed to start task: {}", e); - ContainerdError::StartTaskError(e.to_string()) - })?; - log::info!("Task: {:?} started", cid); - - Ok(()) - } - - async fn do_create_task( - cid: &str, - ns: &str, - rootfs: Vec, - ) -> Result<(), ContainerdError> { - let mut tc = Self::get_client().await.tasks(); - let create_request = CreateTaskRequest { - container_id: cid.to_string(), - rootfs, - ..Default::default() - }; - let _resp = tc - .create(with_namespace!(create_request, ns)) - .await - .map_err(|e| { - log::error!("Failed to create task: {}", e); - ContainerdError::CreateTaskError(e.to_string()) - })?; - - Ok(()) - } - - pub async fn get_task(cid: &str, ns: &str) -> Result { - let mut tc = Self::get_client().await.tasks(); - - let request = ListTasksRequest { - filter: format!("container=={}", cid), - }; - - let response = tc.list(with_namespace!(request, ns)).await.map_err(|e| { - log::error!("Failed to list tasks: {}", e); - ContainerdError::GetContainerListError(e.to_string()) - })?; - let tasks = response.into_inner().tasks; - - let task = - tasks - .into_iter() - .find(|task| task.id == cid) - .ok_or_else(|| -> ContainerdError { - log::error!("Task not found for container: {}", cid); - ContainerdError::CreateTaskError("Task not found".to_string()) - })?; - - Ok(task) - } - - async fn get_mounts(cid: &str, ns: &str) -> Result, ContainerdError> { - let mut sc = Self::get_client().await.snapshots(); - let req = MountsRequest { - snapshotter: "overlayfs".to_string(), - key: cid.to_string(), - }; - let mounts = sc - .mounts(with_namespace!(req, ns)) - .await - .map_err(|e| { - log::error!("Failed to get mounts: {}", e); - ContainerdError::CreateTaskError(e.to_string()) - })? - .into_inner() - .mounts; - - Ok(mounts) - } - - async fn list_task_by_cid(cid: &str, ns: &str) -> Result { - let mut c = Self::get_client().await.tasks(); - - let request = ListTasksRequest { - filter: format!("container=={}", cid), - }; - let response = c - .list(with_namespace!(request, ns)) - .await - .map_err(|e| { - log::error!("Failed to list tasks: {}", e); - ContainerdError::GetContainerListError(e.to_string()) - })? - .into_inner(); - - Ok(response) - } - - async fn do_kill_task(cid: &str, ns: &str) -> Result<(), ContainerdError> { - let mut c = Self::get_client().await.tasks(); - let kill_request = KillRequest { - container_id: cid.to_string(), - signal: 15, - all: true, - ..Default::default() - }; - c.kill(with_namespace!(kill_request, ns)) - .await - .map_err(|e| { - log::error!("Failed to kill task: {}", e); - ContainerdError::KillTaskError(e.to_string()) - })?; - - Ok(()) - } - - async fn do_kill_task_force(cid: &str, ns: &str) -> Result<(), ContainerdError> { - let mut c = Self::get_client().await.tasks(); - let kill_request = KillRequest { - container_id: cid.to_string(), - signal: 9, - all: true, - ..Default::default() - }; - c.kill(with_namespace!(kill_request, ns)) - .await - .map_err(|e| { - log::error!("Failed to force kill task: {}", e); - ContainerdError::KillTaskError(e.to_string()) - })?; - - Ok(()) - } - - async fn do_delete_task(cid: &str, ns: &str) -> Result<(), ContainerdError> { - let mut c = Self::get_client().await.tasks(); - let delete_request = DeleteTaskRequest { - container_id: cid.to_string(), - }; - c.delete(with_namespace!(delete_request, ns)) - .await - .map_err(|e| { - log::error!("Failed to delete task: {}", e); - ContainerdError::DeleteTaskError(e.to_string()) - })?; - - Ok(()) - } - - async fn do_wait_task(cid: &str, ns: &str) -> Result { - let mut c = Self::get_client().await.tasks(); - let wait_request = WaitRequest { - container_id: cid.to_string(), - ..Default::default() - }; - let resp = c - .wait(with_namespace!(wait_request, ns)) - .await - .map_err(|e| { - log::error!("wait error: {}", e); - ContainerdError::WaitTaskError(e.to_string()) - })? - .into_inner(); - - Ok(resp) - } - - /// 杀死并删除任务 - pub async fn kill_task_with_timeout(cid: &str, ns: &str) -> Result<(), ContainerdError> { - let kill_timeout = Duration::from_secs(5); - - let wait_future = Self::do_wait_task(cid, ns); - - Self::do_kill_task(cid, ns).await?; - - match timeout(kill_timeout, wait_future).await { - Ok(Ok(_)) => { - // 正常退出,尝试删除任务 - Self::do_delete_task(cid, ns).await?; - } - Ok(Err(e)) => { - // wait 报错 - log::error!("Error while waiting for task {}: {}", cid, e); - } - Err(_) => { - // 超时,强制 kill - log::warn!("Task {} did not exit in time, sending SIGKILL", cid); - Self::do_kill_task_force(cid, ns).await?; - - // 尝试删除任务 - if let Err(e) = Self::do_delete_task(cid, ns).await { - log::error!("Failed to delete task {} after SIGKILL: {}", cid, e); - } - } - } - - Ok(()) - } - - /// 获取一个容器 - pub async fn load_container(cid: &str, ns: &str) -> Result, ContainerdError> { - let container_list = Self::list_container(ns).await?; - let container = container_list - .into_iter() - .find(|container| container.id == cid); - - Ok(container) - } - - /// 获取容器列表 - pub async fn list_container(ns: &str) -> Result, ContainerdError> { - let mut cc = Self::get_client().await.containers(); - - let request = ListContainersRequest { - ..Default::default() - }; - - let resp = cc.list(with_namespace!(request, ns)).await.map_err(|e| { - log::error!("Failed to list containers: {}", e); - ContainerdError::CreateContainerError(e.to_string()) - })?; - - Ok(resp.into_inner().containers) - } - - pub async fn list_container_into_string(ns: &str) -> Result, ContainerdError> { - let mut cc = Self::get_client().await.containers(); - - let request = ListContainersRequest { - ..Default::default() - }; - - let resp = cc.list(with_namespace!(request, ns)).await.map_err(|e| { - log::error!("Failed to list containers: {}", e); - ContainerdError::CreateContainerError(e.to_string()) - })?; - - Ok(resp - .into_inner() - .containers - .into_iter() - .map(|container| container.id) - .collect()) - } - - async fn prepare_snapshot( - image_name: &str, - cid: &str, - ns: &str, - ) -> Result<(), ContainerdError> { - let parent_snapshot = Self::get_parent_snapshot(image_name).await?; - Self::do_prepare_snapshot(cid, ns, parent_snapshot).await?; - - Ok(()) - } - - async fn do_prepare_snapshot( - cid: &str, - ns: &str, - parent_snapshot: String, - ) -> Result<(), ContainerdError> { - let req = PrepareSnapshotRequest { - snapshotter: "overlayfs".to_string(), - key: cid.to_string(), - parent: parent_snapshot, - ..Default::default() - }; - let client = Self::get_client().await; - let _resp = client - .snapshots() - .prepare(with_namespace!(req, ns)) - .await - .map_err(|e| { - log::error!("Failed to prepare snapshot: {}", e); - ContainerdError::CreateSnapshotError(e.to_string()) - })?; - - Ok(()) - } - - async fn get_parent_snapshot(image_name: &str) -> Result { - let config = ImageManager::get_image_config(image_name).map_err(|e| { - log::error!("Failed to get image config: {}", e); - ContainerdError::GetParentSnapshotError(e.to_string()) - })?; - - if config.rootfs().diff_ids().is_empty() { - log::error!("Image config has no diff_ids for image: {}", image_name); - return Err(ContainerdError::GetParentSnapshotError( - "No diff_ids found in image config".to_string(), - )); - } - - let mut iter = config.rootfs().diff_ids().iter(); - let mut ret = iter - .next() - .map_or_else(String::new, |layer_digest| layer_digest.clone()); - - for layer_digest in iter { - let mut hasher = Sha256::new(); - hasher.update(ret.as_bytes()); - ret.push_str(&format!(",{}", layer_digest)); - hasher.update(" "); - hasher.update(layer_digest); - let digest = ::hex::encode(hasher.finalize()); - ret = format!("sha256:{digest}"); - } - Ok(ret) - } - - fn get_spec(cid: &str, ns: &str, image_name: &str) -> Result, ContainerdError> { - let config = ImageManager::get_runtime_config(image_name).unwrap(); - let spec_path = generate_spec(cid, ns, &config).map_err(|e| { - log::error!("Failed to generate spec: {}", e); - ContainerdError::GenerateSpecError(e.to_string()) - })?; - let spec = fs::read_to_string(spec_path).unwrap(); - let spec = Any { - type_url: "types.containerd.io/opencontainers/runtime-spec/1/Spec".to_string(), - value: spec.into_bytes(), - }; - Ok(Some(spec)) - } - - /// 为一个容器准备cni网络并写入全局map中 - fn prepare_cni_network(cid: &str, ns: &str, image_name: &str) -> Result<(), ContainerdError> { - let ip = cni::create_cni_network(cid.to_string(), ns.to_string()).map_err(|e| { - log::error!("Failed to create CNI network: {}", e); - ContainerdError::CreateTaskError(e.to_string()) - })?; - let ports = ImageManager::get_runtime_config(image_name).unwrap().ports; - let network_config = NetworkConfig::new(ip, ports); - let function = FunctionScope { - function_name: cid.to_string(), - namespace: ns.to_string(), - }; - Self::save_container_network_config(function, network_config); - Ok(()) - } - - /// 删除cni网络,删除全局map中的网络配置 - fn remove_cni_network(cid: &str, ns: &str) -> Result<(), ContainerdError> { - cni::delete_cni_network(ns, cid); - let function = FunctionScope { - function_name: cid.to_string(), - namespace: ns.to_string(), - }; - Self::remove_container_network_config(&function); - Ok(()) - } - - fn save_container_network_config(function: FunctionScope, net_conf: NetworkConfig) { - let mut map = GLOBAL_NETNS_MAP.write().unwrap(); - map.insert(function, net_conf); - } - - pub fn get_address(function: &FunctionScope) -> String { - let map = GLOBAL_NETNS_MAP.read().unwrap(); - let addr = map.get(function).map(|net_conf| net_conf.get_address()); - addr.unwrap_or_default() - } - - fn remove_container_network_config(function: &FunctionScope) { - let mut map = GLOBAL_NETNS_MAP.write().unwrap(); - map.remove(function); - } - - pub async fn list_namespaces() -> Result, ContainerdError> { - let mut c = Self::get_client().await.namespaces(); - let req = ListNamespacesRequest { - ..Default::default() - }; - let resp = c.list(req).await.map_err(|e| { - log::error!("Failed to list namespaces: {}", e); - ContainerdError::GetContainerListError(e.to_string()) - })?; - Ok(resp - .into_inner() - .namespaces - .into_iter() - .map(|ns| ns.name) - .collect()) - } - - pub async fn pause_task() { - todo!() - } - - pub async fn resume_task() { - todo!() - } -} - -#[derive(Debug)] -pub enum ContainerdError { - CreateContainerError(String), - CreateSnapshotError(String), - GetParentSnapshotError(String), - GenerateSpecError(String), - DeleteContainerError(String), - GetContainerListError(String), - KillTaskError(String), - DeleteTaskError(String), - WaitTaskError(String), - CreateTaskError(String), - StartTaskError(String), - #[allow(dead_code)] - OtherError, -} - -impl std::fmt::Display for ContainerdError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - ContainerdError::CreateContainerError(msg) => { - write!(f, "Failed to create container: {}", msg) - } - ContainerdError::CreateSnapshotError(msg) => { - write!(f, "Failed to create snapshot: {}", msg) - } - ContainerdError::GetParentSnapshotError(msg) => { - write!(f, "Failed to get parent snapshot: {}", msg) - } - ContainerdError::GenerateSpecError(msg) => { - write!(f, "Failed to generate spec: {}", msg) - } - ContainerdError::DeleteContainerError(msg) => { - write!(f, "Failed to delete container: {}", msg) - } - ContainerdError::GetContainerListError(msg) => { - write!(f, "Failed to get container list: {}", msg) - } - ContainerdError::KillTaskError(msg) => { - write!(f, "Failed to kill task: {}", msg) - } - ContainerdError::DeleteTaskError(msg) => { - write!(f, "Failed to delete task: {}", msg) - } - ContainerdError::WaitTaskError(msg) => { - write!(f, "Failed to wait task: {}", msg) - } - ContainerdError::CreateTaskError(msg) => { - write!(f, "Failed to create task: {}", msg) - } - ContainerdError::StartTaskError(msg) => { - write!(f, "Failed to start task: {}", msg) - } - ContainerdError::OtherError => write!(f, "Other error happened"), - } - } -} - -impl std::error::Error for ContainerdError {} diff --git a/crates/service/src/lib.rs b/crates/service/src/lib.rs deleted file mode 100644 index c9e1b76..0000000 --- a/crates/service/src/lib.rs +++ /dev/null @@ -1,48 +0,0 @@ -pub mod containerd_manager; -pub mod image_manager; -pub mod namespace_manager; -pub mod spec; -pub mod systemd; - -use std::{ - collections::HashMap, - sync::{Arc, RwLock}, -}; - -// config.json,dockerhub密钥 -// const DOCKER_CONFIG_DIR: &str = "/var/lib/faasd/.docker/"; - -type NetnsMap = Arc>>; -lazy_static::lazy_static! { - static ref GLOBAL_NETNS_MAP: NetnsMap = Arc::new(RwLock::new(HashMap::new())); -} - -#[derive(Hash, Eq, PartialEq)] -pub struct FunctionScope { - pub function_name: String, - pub namespace: String, -} - -#[derive(Debug, Clone)] -pub struct NetworkConfig { - ip: String, - ports: Vec, -} - -impl NetworkConfig { - pub fn new(ip: String, ports: Vec) -> Self { - NetworkConfig { ip, ports } - } - - pub fn get_ip(&self) -> String { - self.ip.clone() - } - - pub fn get_address(&self) -> String { - format!( - "{}:{}", - self.ip.split('/').next().unwrap_or(""), - self.ports[0].split('/').next().unwrap_or("") - ) - } -} diff --git a/crates/service/src/namespace_manager.rs b/crates/service/src/namespace_manager.rs deleted file mode 100644 index 5babcc7..0000000 --- a/crates/service/src/namespace_manager.rs +++ /dev/null @@ -1,81 +0,0 @@ -use crate::containerd_manager::CLIENT; -use containerd_client::{ - Client, - services::v1::{CreateNamespaceRequest, DeleteNamespaceRequest, Namespace}, -}; -use std::sync::Arc; - -pub struct NSManager { - namespaces: Vec, -} - -impl NSManager { - async fn get_client() -> Arc { - CLIENT - .get() - .unwrap_or_else(|| panic!("Client not initialized, Please run init first")) - .clone() - } - - pub async fn create_namespace(&mut self, name: &str) -> Result<(), NameSpaceError> { - let client = Self::get_client().await; - let mut ns_client = client.namespaces(); - - let request = CreateNamespaceRequest { - namespace: Some(Namespace { - name: name.to_string(), - ..Default::default() - }), - }; - - let response = ns_client.create(request).await.map_err(|e| { - NameSpaceError::CreateError(format!("Failed to create namespace {}: {}", name, e)) - })?; - - self.namespaces - .push(response.into_inner().namespace.unwrap()); - Ok(()) - } - - pub async fn delete_namespace(&mut self, name: &str) -> Result<(), NameSpaceError> { - let client = Self::get_client().await; - let mut ns_client = client.namespaces(); - - let req = DeleteNamespaceRequest { - name: name.to_string(), - }; - - ns_client.delete(req).await.map_err(|e| { - NameSpaceError::DeleteError(format!("Failed to delete namespace {}: {}", name, e)) - })?; - - self.namespaces.retain(|ns| ns.name != name); - Ok(()) - } - - pub async fn list_namespace(&self) -> Result, NameSpaceError> { - // 这里没有选择直接列举所有的命名空间,而是返回当前对象中存储的命名空间 - // 觉得应该只能看见自己创建的命名空间而不能看见其他人的命名空间 - // 是不是应该把namespaces做持久化存储,作为一个用户自己的namespace - Ok(self.namespaces.clone()) - } -} - -#[derive(Debug)] -pub enum NameSpaceError { - CreateError(String), - DeleteError(String), - ListError(String), -} - -impl std::fmt::Display for NameSpaceError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - NameSpaceError::CreateError(msg) => write!(f, "Create Namespace Error: {}", msg), - NameSpaceError::DeleteError(msg) => write!(f, "Delete Namespace Error: {}", msg), - NameSpaceError::ListError(msg) => write!(f, "List Namespace Error: {}", msg), - } - } -} - -impl std::error::Error for NameSpaceError {} diff --git a/crates/service/src/spec.rs b/crates/service/src/spec.rs deleted file mode 100644 index 1213d1f..0000000 --- a/crates/service/src/spec.rs +++ /dev/null @@ -1,339 +0,0 @@ -use serde::{Deserialize, Serialize}; -use std::fs::File; - -use crate::image_manager::ImageRuntimeConfig; - -// 定义版本的常量 -const VERSION_MAJOR: u32 = 1; -const VERSION_MINOR: u32 = 1; -const VERSION_PATCH: u32 = 0; -const VERSION_DEV: &str = ""; // 对应开发分支 - -const RWM: &str = "rwm"; -const DEFAULT_ROOTFS_PATH: &str = "rootfs"; -pub const DEFAULT_NAMESPACE: &str = "default"; -const PATH_TO_SPEC_PREFIX: &str = "/tmp/containerd-spec"; - -// const DEFAULT_UNIX_ENV: &str = "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"; - -const PID_NAMESPACE: &str = "pid"; -const NETWORK_NAMESPACE: &str = "network"; -const MOUNT_NAMESPACE: &str = "mount"; -const IPC_NAMESPACE: &str = "ipc"; -const UTS_NAMESPACE: &str = "uts"; - -#[derive(Serialize, Deserialize, Debug)] -pub struct Spec { - #[serde(rename = "ociVersion")] - pub oci_version: String, - pub root: Root, - pub process: Process, - pub linux: Linux, - pub mounts: Vec, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct Root { - pub path: String, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct Process { - pub cwd: String, - #[serde(rename = "noNewPrivileges")] - pub no_new_privileges: bool, - pub user: User, - pub capabilities: LinuxCapabilities, - pub rlimits: Vec, - pub args: Vec, - pub env: Vec, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct User { - pub uid: u32, - pub gid: u32, - #[serde(rename = "additionalGids")] - pub additional_gids: Vec, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct Mount { - pub destination: String, - #[serde(rename = "type")] - pub type_: String, - pub source: String, - pub options: Vec, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct LinuxCapabilities { - pub bounding: Vec, - pub permitted: Vec, - pub effective: Vec, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct POSIXRlimit { - pub hard: u64, - pub soft: u64, - #[serde(rename = "type")] - pub type_: String, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct Linux { - pub masked_paths: Vec, - pub readonly_paths: Vec, - pub cgroups_path: String, - pub resources: LinuxResources, - pub namespaces: Vec, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct LinuxResources { - pub devices: Vec, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct LinuxDeviceCgroup { - pub allow: bool, - pub access: String, -} - -#[derive(Serialize, Deserialize, Debug)] -pub struct LinuxNamespace { - #[serde(rename = "type")] - pub type_: String, - pub path: Option, -} - -pub fn default_unix_caps() -> Vec { - vec![ - String::from("CAP_CHOWN"), - String::from("CAP_DAC_OVERRIDE"), - String::from("CAP_FSETID"), - String::from("CAP_FOWNER"), - String::from("CAP_MKNOD"), - String::from("CAP_NET_RAW"), - String::from("CAP_SETGID"), - String::from("CAP_SETUID"), - String::from("CAP_SETFCAP"), - String::from("CAP_SETPCAP"), - String::from("CAP_NET_BIND_SERVICE"), - String::from("CAP_SYS_CHROOT"), - String::from("CAP_KILL"), - String::from("CAP_AUDIT_WRITE"), - ] -} - -fn default_masked_parhs() -> Vec { - vec![ - String::from("/proc/acpi"), - String::from("/proc/asound"), - String::from("/proc/kcore"), - String::from("/proc/keys"), - String::from("/proc/latency_stats"), - String::from("/proc/timer_list"), - String::from("/proc/timer_stats"), - String::from("/proc/sched_debug"), - String::from("/proc/scsi"), - String::from("/sys/firmware"), - String::from("/sys/devices/virtual/powercap"), - ] -} - -fn default_readonly_paths() -> Vec { - vec![ - String::from("/proc/bus"), - String::from("/proc/fs"), - String::from("/proc/irq"), - String::from("/proc/sys"), - String::from("/proc/sysrq-trigger"), - ] -} - -fn default_unix_namespaces(ns: &str, cid: &str) -> Vec { - vec![ - LinuxNamespace { - type_: String::from(PID_NAMESPACE), - path: None, - }, - LinuxNamespace { - type_: String::from(IPC_NAMESPACE), - path: None, - }, - LinuxNamespace { - type_: String::from(UTS_NAMESPACE), - path: None, - }, - LinuxNamespace { - type_: String::from(MOUNT_NAMESPACE), - path: None, - }, - LinuxNamespace { - type_: String::from(NETWORK_NAMESPACE), - path: Some(format!("/var/run/netns/{}", get_netns(ns, cid))), - }, - ] -} - -fn default_mounts() -> Vec { - vec![ - Mount { - destination: "/proc".to_string(), - type_: "proc".to_string(), - source: "proc".to_string(), - options: vec![], - }, - Mount { - destination: "/dev".to_string(), - type_: "tmpfs".to_string(), - source: "tmpfs".to_string(), - options: vec![ - "nosuid".to_string(), - "strictatime".to_string(), - "mode=755".to_string(), - "size=65536k".to_string(), - ], - }, - Mount { - destination: "/dev/pts".to_string(), - type_: "devpts".to_string(), - source: "devpts".to_string(), - options: vec![ - "nosuid".to_string(), - "noexec".to_string(), - "newinstance".to_string(), - "ptmxmode=0666".to_string(), - "mode=0620".to_string(), - "gid=5".to_string(), - ], - }, - Mount { - destination: "/dev/shm".to_string(), - type_: "tmpfs".to_string(), - source: "shm".to_string(), - options: vec![ - "nosuid".to_string(), - "noexec".to_string(), - "nodev".to_string(), - "mode=1777".to_string(), - "size=65536k".to_string(), - ], - }, - Mount { - destination: "/dev/mqueue".to_string(), - type_: "mqueue".to_string(), - source: "mqueue".to_string(), - options: vec![ - "nosuid".to_string(), - "noexec".to_string(), - "nodev".to_string(), - ], - }, - Mount { - destination: "/sys".to_string(), - type_: "sysfs".to_string(), - source: "sysfs".to_string(), - options: vec![ - "nosuid".to_string(), - "noexec".to_string(), - "nodev".to_string(), - "ro".to_string(), - ], - }, - Mount { - destination: "/sys/fs/cgroup".to_string(), - type_: "cgroup".to_string(), - source: "cgroup".to_string(), - options: vec![ - "nosuid".to_string(), - "noexec".to_string(), - "nodev".to_string(), - "relatime".to_string(), - "ro".to_string(), - ], - }, - ] -} - -fn get_version() -> String { - format!( - "{}.{}.{}{}", - VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_DEV - ) -} - -pub fn populate_default_unix_spec(id: &str, ns: &str) -> Spec { - Spec { - oci_version: get_version(), - root: Root { - path: DEFAULT_ROOTFS_PATH.to_string(), - }, - process: Process { - cwd: String::from("/"), - no_new_privileges: true, - user: User { - uid: 0, - gid: 0, - additional_gids: vec![], - }, - capabilities: LinuxCapabilities { - bounding: default_unix_caps(), - permitted: default_unix_caps(), - effective: default_unix_caps(), - }, - rlimits: vec![POSIXRlimit { - type_: String::from("RLIMIT_NOFILE"), - hard: 1024, - soft: 1024, - }], - args: vec![], - env: vec![], - }, - linux: Linux { - masked_paths: default_masked_parhs(), - readonly_paths: default_readonly_paths(), - cgroups_path: format!("/{}/{}", ns, id), - resources: LinuxResources { - devices: vec![LinuxDeviceCgroup { - allow: false, - access: RWM.to_string(), - }], - }, - namespaces: default_unix_namespaces(ns, id), - }, - mounts: default_mounts(), - } -} - -pub fn save_spec_to_file(spec: &Spec, path: &str) -> Result<(), std::io::Error> { - let file = File::create(path)?; - serde_json::to_writer(file, spec)?; - Ok(()) -} - -fn get_netns(ns: &str, cid: &str) -> String { - format!("{}-{}", ns, cid) -} - -pub fn generate_spec( - id: &str, - ns: &str, - runtime_config: &ImageRuntimeConfig, -) -> Result { - let namespace = match ns { - "" => DEFAULT_NAMESPACE, - _ => ns, - }; - let mut spec = populate_default_unix_spec(id, ns); - spec.process.args = runtime_config.args.clone(); - spec.process.env = runtime_config.env.clone(); - spec.process.cwd = runtime_config.cwd.clone(); - let dir_path = format!("{}/{}", PATH_TO_SPEC_PREFIX, namespace); - let path = format!("{}/{}.json", dir_path, id); - std::fs::create_dir_all(&dir_path)?; - save_spec_to_file(&spec, &path)?; - Ok(path) -} diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 1600a09..74e173f 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -6,7 +6,7 @@ info: name: GPL-3.0 version: 0.1.0 servers: -- url: "http://localhost:8090" +- url: "http://localhost:8080" description: Local server tags: - name: internal diff --git a/flake.nix b/flake.nix index 73b3efb..a946827 100644 --- a/flake.nix +++ b/flake.nix @@ -59,10 +59,8 @@ fileset = lib.fileset.unions [ ./Cargo.toml ./Cargo.lock - (craneLib.fileset.commonCargoSources ./crates/app) - (craneLib.fileset.commonCargoSources ./crates/service) - (craneLib.fileset.commonCargoSources ./crates/provider) - (craneLib.fileset.commonCargoSources ./crates/cni) + (craneLib.fileset.commonCargoSources ./crates/faas-containerd) + (craneLib.fileset.commonCargoSources ./crates/gateway) (craneLib.fileset.commonCargoSources ./crates/my-workspace-hack) (craneLib.fileset.commonCargoSources crate) ]; @@ -70,8 +68,8 @@ faas-rs-crate = craneLib.buildPackage ( individualCrateArgs // { pname = "faas-rs"; - cargoExtraArgs = "-p faas-rs"; - src = fileSetForCrate ./crates/app; + cargoExtraArgs = "-p faas-containerd"; + src = fileSetForCrate ./crates/faas-containerd; }); in with pkgs;