Dataset Viewer
Auto-converted to Parquet Duplicate
repo
stringclasses
1 value
pull_number
int64
382
2.48k
instance_id
stringclasses
4 values
issue_numbers
sequencelengths
1
1
base_commit
stringclasses
4 values
patch
stringclasses
4 values
test_patch
stringclasses
4 values
problem_statement
stringclasses
4 values
hints_text
stringclasses
2 values
created_at
stringclasses
4 values
bottlerocket-os/bottlerocket
2,476
bottlerocket-os__bottlerocket-2476
[ "2412" ]
a90cc5f7e019fb67dccf5af2e3eea2190e529cf6
diff --git a/sources/Cargo.lock b/sources/Cargo.lock index 0252b80b229..f1954ef41d6 100644 --- a/sources/Cargo.lock +++ b/sources/Cargo.lock @@ -459,9 +459,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "aws-config" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11a8c971b0cb0484fc9436a291a44503b95141edc36ce7a6af6b6d7a06a02ab0" +checksum = "7d4cf4608abd7c8038a4c609a1270e61b73c86550f5655654ca28322e0a2e2c1" dependencies = [ "aws-http", "aws-sdk-sso", @@ -478,6 +478,7 @@ dependencies = [ "http", "hyper", "ring", + "time 0.3.14", "tokio", "tower", "tracing", @@ -486,11 +487,12 @@ dependencies = [ [[package]] name = "aws-endpoint" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bc956f415dda77215372e5bc751a2463d1f9a1ec34edf3edc6c0ff67e5c8e43" +checksum = "7ffaf1da7a11d38a5afe7cdd202ab2e25528de7cf38c47b571c0dde4008d98ae" dependencies = [ "aws-smithy-http", + "aws-smithy-types", "aws-types", "http", "regex", @@ -499,9 +501,9 @@ dependencies = [ [[package]] name = "aws-http" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a0d98a1d606aa24554e604f220878db4aa3b525b72f88798524497cc3867fc6" +checksum = "8309108743e2e74f249ff29a7c7be79c6343ea649dd8c31e4c0e07ca6946d8ed" dependencies = [ "aws-smithy-http", "aws-smithy-types", @@ -517,9 +519,9 @@ dependencies = [ [[package]] name = "aws-sdk-cloudformation" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11ee3a29cc2cea6ab8bf930f03a2c926430c686a5bd58d8f0f8b9f5d5c386f47" +checksum = "cafaf0b9199f52cd69ef07c1d15fc7a57bf3ff53a8b0885cf708110fa49f6450" dependencies = [ "aws-endpoint", "aws-http", @@ -541,9 +543,9 @@ dependencies = [ [[package]] name = "aws-sdk-eks" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "18165a110897844ed983b2e4fd339c09a77c0c9cec4ffe50452d0da361f3a503" +checksum = "0279da965d60a577f3e7a200f5df0586aea060a8ab2c09e691e29710a4ad9145" dependencies = [ "aws-endpoint", "aws-http", @@ -564,9 +566,9 @@ dependencies = [ [[package]] name = "aws-sdk-sso" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa0c66fab12976065403cf4cafacffe76afa91d0da335d195af379d4223d235" +checksum = "f7a0659e5269f8c4bd06f362ec7e35b4f55956c4d60e0ca177b575db80584a45" dependencies = [ "aws-endpoint", "aws-http", @@ -586,9 +588,9 @@ dependencies = [ [[package]] name = "aws-sdk-sts" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "048037cdfd7f42fb29b5f969c7f639b4b7eac00e8f911e4eac4f89fb7b3a0500" +checksum = "edc795c7851c0e9bcefde5e6bb610c16a9e03220e0336fc12f75bb80d9ce7e80" dependencies = [ "aws-endpoint", "aws-http", @@ -608,9 +610,9 @@ dependencies = [ [[package]] name = "aws-sig-auth" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8386fc0d218dbf2011f65bd8300d21ba98603fd150b962f61239be8b02d1fc6" +checksum = "0ee4bf20136757fd9f606bb4adafe6d19fb02bc48033a8d4f205f21d56fa783a" dependencies = [ "aws-sigv4", "aws-smithy-http", @@ -621,9 +623,9 @@ dependencies = [ [[package]] name = "aws-sigv4" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd866926c2c4978210bcb01d7d1b431c794f0c23ca9ee1e420204b018836b5fb" +checksum = "b99b21b3aceaf224cccd693b353e1f38af4ede8c5fc618b97dd458bb63238efc" dependencies = [ "aws-smithy-http", "form_urlencoded", @@ -639,9 +641,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deb59cfdd21143006c01b9ca4dc4a9190b8c50c2ef831f9eb36f54f69efa42f1" +checksum = "ef79062cf5fa881dd156938ca438ec2de0f7ec9342c2f84fa6303274e1484b43" dependencies = [ "futures-util", "pin-project-lite", @@ -651,9 +653,9 @@ dependencies = [ [[package]] name = "aws-smithy-client" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44243329ba8618474c3b7f396de281f175ae172dd515b3d35648671a3cf51871" +checksum = "13f402fa9a45353f7f02f8046a6a568143844d201c5b4cc3bedb6442058538c8" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -674,9 +676,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fba78f69a5bbe7ac1826389304c67b789032d813574e78f9a2d450634277f833" +checksum = "23861d0b53a1369eab1e8d48c8bb3492eb3def1c2f2222dfb1bad58dd03914a5" dependencies = [ "aws-smithy-types", "bytes", @@ -695,9 +697,9 @@ dependencies = [ [[package]] name = "aws-smithy-http-tower" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff8a512d68350561e901626baa08af9491cfbd54596201b84b4da846a59e4da3" +checksum = "04f6b3ae42d5c52bbaadfdd31c09fd11c92b823d329915dedbb08c0e9525755c" dependencies = [ "aws-smithy-http", "bytes", @@ -710,18 +712,18 @@ dependencies = [ [[package]] name = "aws-smithy-json" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b7633698853aae80bd8b26866531420138eca91ea4620735d20b0537c93c2e" +checksum = "5048b693643803c001f88fad36c5a7aa1159e56b0025527fadc57e830aa48b11" dependencies = [ "aws-smithy-types", ] [[package]] name = "aws-smithy-query" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95a94b5a8cc94a85ccbff89eb7bc80dc135ede02847a73d68c04ac2a3e4cf6b7" +checksum = "b317cd3b326444e659a2f287f67e8c72903495c71a3473b0764880454b3aa25c" dependencies = [ "aws-smithy-types", "urlencoding", @@ -729,9 +731,9 @@ dependencies = [ [[package]] name = "aws-smithy-types" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d230d281653de22fb0e9c7c74d18d724a39d7148e2165b1e760060064c4967c0" +checksum = "4149b09b9d8cf37f0afc390144f5d71b8f4daadfd9540ddf43ad27b54d407470" dependencies = [ "itoa", "num-integer", @@ -741,18 +743,18 @@ dependencies = [ [[package]] name = "aws-smithy-xml" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4aacaf6c0fa549ebe5d9daa96233b8635965721367ee7c69effc8d8078842df3" +checksum = "2c6d8e7a15feb04f041cf0ede8f6c16e03fe5a4b03e164ae3a090e829404d925" dependencies = [ "xmlparser", ] [[package]] name = "aws-types" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb54f097516352475a0159c9355f8b4737c54044538a4d9aca4d376ef2361ccc" +checksum = "1bba03e59e1a0223a2bd3567da2b07a458b067ccf7846996b82406e80008ebc1" dependencies = [ "aws-smithy-async", "aws-smithy-client", @@ -2445,9 +2447,9 @@ dependencies = [ [[package]] name = "olpc-cjson" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72ca49fe685014bbf124ee547da94ed7bb65a6eb9dc9c4711773c081af96a39c" +checksum = "87dc75cf72208cd853671c1abccc5d5d1e43b1e378dde67340ef933219a8c13c" dependencies = [ "serde", "serde_json", @@ -3715,9 +3717,9 @@ dependencies = [ [[package]] name = "tough" -version = "0.12.4" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70a537c6b4307f5401e82a0196e97aaab9599e9c0f880e168eafb176abbac63d" +checksum = "dc636dd1ee889a366af6731f1b63b60baf19528b46df5a7c2d4b3bf8b60bca2d" dependencies = [ "chrono", "dyn-clone", diff --git a/sources/api/pluto/Cargo.toml b/sources/api/pluto/Cargo.toml index e0727172d38..438f44ec20f 100644 --- a/sources/api/pluto/Cargo.toml +++ b/sources/api/pluto/Cargo.toml @@ -17,10 +17,10 @@ hyper-proxy = { version = "0.9", default-features = false, features = ["rustls" hyper-rustls = { version = "0.23", default-features = false, features = ["http2", "native-tokio", "tls12", "logging"] } imdsclient = { path = "../../imdsclient", version = "0.1.0" } models = { path = "../../models", version = "0.1.0" } -aws-config = "0.46.0" -aws-sdk-eks = "0.16.0" -aws-types = "0.46.0" -aws-smithy-client = { version = "0.46.0", default-features = false, features = ["rustls"] } +aws-config = "0.48.0" +aws-sdk-eks = "0.18.0" +aws-types = "0.48.0" +aws-smithy-client = { version = "0.48.0", default-features = false, features = ["rustls"] } serde_json = "1" snafu = "0.7" tokio = { version = "~1.14", default-features = false, features = ["macros", "rt-multi-thread"] } # LTS diff --git a/sources/cfsignal/Cargo.toml b/sources/cfsignal/Cargo.toml index a3ce9f566e1..7a01a49d0c1 100644 --- a/sources/cfsignal/Cargo.toml +++ b/sources/cfsignal/Cargo.toml @@ -14,9 +14,9 @@ simplelog = "0.12" snafu = { version = "0.7" } toml = "0.5.1" tokio = { version = "~1.14", default-features = false, features = ["macros", "rt-multi-thread"] } -aws-config = "0.46.0" -aws-sdk-cloudformation = "0.16.0" -aws-types = "0.46.0" +aws-config = "0.48.0" +aws-sdk-cloudformation = "0.18.0" +aws-types = "0.48.0" imdsclient = { path = "../imdsclient", version = "0.1.0" } hyper = "0.14.2" diff --git a/tools/Cargo.lock b/tools/Cargo.lock index d78f9919212..6ae14c31b4a 100644 --- a/tools/Cargo.lock +++ b/tools/Cargo.lock @@ -130,9 +130,9 @@ checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" [[package]] name = "aws-config" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "11a8c971b0cb0484fc9436a291a44503b95141edc36ce7a6af6b6d7a06a02ab0" +checksum = "7d4cf4608abd7c8038a4c609a1270e61b73c86550f5655654ca28322e0a2e2c1" dependencies = [ "aws-http", "aws-sdk-sso", @@ -149,6 +149,7 @@ dependencies = [ "http", "hyper", "ring", + "time 0.3.14", "tokio", "tower", "tracing", @@ -157,11 +158,12 @@ dependencies = [ [[package]] name = "aws-endpoint" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bc956f415dda77215372e5bc751a2463d1f9a1ec34edf3edc6c0ff67e5c8e43" +checksum = "7ffaf1da7a11d38a5afe7cdd202ab2e25528de7cf38c47b571c0dde4008d98ae" dependencies = [ "aws-smithy-http", + "aws-smithy-types", "aws-types", "http", "regex", @@ -170,9 +172,9 @@ dependencies = [ [[package]] name = "aws-http" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a0d98a1d606aa24554e604f220878db4aa3b525b72f88798524497cc3867fc6" +checksum = "8309108743e2e74f249ff29a7c7be79c6343ea649dd8c31e4c0e07ca6946d8ed" dependencies = [ "aws-smithy-http", "aws-smithy-types", @@ -188,9 +190,9 @@ dependencies = [ [[package]] name = "aws-sdk-ebs" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "702e6f505ce8d61f0bef4d2b2747f156dcbd6ba23b2a870ad9aa868830f026c5" +checksum = "e901db77b1cbdce5804ee5587882aceac22250171dfdde51f6a2f95161bd1394" dependencies = [ "aws-endpoint", "aws-http", @@ -211,9 +213,9 @@ dependencies = [ [[package]] name = "aws-sdk-ec2" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85b6c04720f5846edb80aa8c4dda848b77efdf99597f1ae48e12ea6b1ad1d3ce" +checksum = "e17191be59536e96d100c9dca58f6807fc8d2b0848a06c360b1ffa164bf16bca" dependencies = [ "aws-endpoint", "aws-http", @@ -235,9 +237,9 @@ dependencies = [ [[package]] name = "aws-sdk-kms" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6fee45083be6f062676aaeab0fe16c931a4e188d2ddce6f2c8d17399c014dc81" +checksum = "829bf306cb8d20fc1d5d08a8dc440f37d24bfe6690657f55612ccc8a0c083675" dependencies = [ "aws-endpoint", "aws-http", @@ -257,9 +259,9 @@ dependencies = [ [[package]] name = "aws-sdk-ssm" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df79d41b62dcea814079c2f6540c465b6d45210b20a4e30efdcd24cc5dcf4aec" +checksum = "504854d33ea2be4f61391b5c701be7e411c212272367fd1f810e793d255a547d" dependencies = [ "aws-endpoint", "aws-http", @@ -280,9 +282,9 @@ dependencies = [ [[package]] name = "aws-sdk-sso" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa0c66fab12976065403cf4cafacffe76afa91d0da335d195af379d4223d235" +checksum = "f7a0659e5269f8c4bd06f362ec7e35b4f55956c4d60e0ca177b575db80584a45" dependencies = [ "aws-endpoint", "aws-http", @@ -302,9 +304,9 @@ dependencies = [ [[package]] name = "aws-sdk-sts" -version = "0.16.0" +version = "0.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "048037cdfd7f42fb29b5f969c7f639b4b7eac00e8f911e4eac4f89fb7b3a0500" +checksum = "edc795c7851c0e9bcefde5e6bb610c16a9e03220e0336fc12f75bb80d9ce7e80" dependencies = [ "aws-endpoint", "aws-http", @@ -324,9 +326,9 @@ dependencies = [ [[package]] name = "aws-sig-auth" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8386fc0d218dbf2011f65bd8300d21ba98603fd150b962f61239be8b02d1fc6" +checksum = "0ee4bf20136757fd9f606bb4adafe6d19fb02bc48033a8d4f205f21d56fa783a" dependencies = [ "aws-sigv4", "aws-smithy-http", @@ -337,9 +339,9 @@ dependencies = [ [[package]] name = "aws-sigv4" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd866926c2c4978210bcb01d7d1b431c794f0c23ca9ee1e420204b018836b5fb" +checksum = "b99b21b3aceaf224cccd693b353e1f38af4ede8c5fc618b97dd458bb63238efc" dependencies = [ "aws-smithy-http", "form_urlencoded", @@ -355,9 +357,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "deb59cfdd21143006c01b9ca4dc4a9190b8c50c2ef831f9eb36f54f69efa42f1" +checksum = "ef79062cf5fa881dd156938ca438ec2de0f7ec9342c2f84fa6303274e1484b43" dependencies = [ "futures-util", "pin-project-lite", @@ -367,9 +369,9 @@ dependencies = [ [[package]] name = "aws-smithy-client" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44243329ba8618474c3b7f396de281f175ae172dd515b3d35648671a3cf51871" +checksum = "13f402fa9a45353f7f02f8046a6a568143844d201c5b4cc3bedb6442058538c8" dependencies = [ "aws-smithy-async", "aws-smithy-http", @@ -390,9 +392,9 @@ dependencies = [ [[package]] name = "aws-smithy-http" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fba78f69a5bbe7ac1826389304c67b789032d813574e78f9a2d450634277f833" +checksum = "23861d0b53a1369eab1e8d48c8bb3492eb3def1c2f2222dfb1bad58dd03914a5" dependencies = [ "aws-smithy-types", "bytes", @@ -411,9 +413,9 @@ dependencies = [ [[package]] name = "aws-smithy-http-tower" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff8a512d68350561e901626baa08af9491cfbd54596201b84b4da846a59e4da3" +checksum = "04f6b3ae42d5c52bbaadfdd31c09fd11c92b823d329915dedbb08c0e9525755c" dependencies = [ "aws-smithy-http", "bytes", @@ -426,18 +428,18 @@ dependencies = [ [[package]] name = "aws-smithy-json" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31b7633698853aae80bd8b26866531420138eca91ea4620735d20b0537c93c2e" +checksum = "5048b693643803c001f88fad36c5a7aa1159e56b0025527fadc57e830aa48b11" dependencies = [ "aws-smithy-types", ] [[package]] name = "aws-smithy-query" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95a94b5a8cc94a85ccbff89eb7bc80dc135ede02847a73d68c04ac2a3e4cf6b7" +checksum = "b317cd3b326444e659a2f287f67e8c72903495c71a3473b0764880454b3aa25c" dependencies = [ "aws-smithy-types", "urlencoding", @@ -445,9 +447,9 @@ dependencies = [ [[package]] name = "aws-smithy-types" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d230d281653de22fb0e9c7c74d18d724a39d7148e2165b1e760060064c4967c0" +checksum = "4149b09b9d8cf37f0afc390144f5d71b8f4daadfd9540ddf43ad27b54d407470" dependencies = [ "itoa", "num-integer", @@ -457,18 +459,18 @@ dependencies = [ [[package]] name = "aws-smithy-xml" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4aacaf6c0fa549ebe5d9daa96233b8635965721367ee7c69effc8d8078842df3" +checksum = "2c6d8e7a15feb04f041cf0ede8f6c16e03fe5a4b03e164ae3a090e829404d925" dependencies = [ "xmlparser", ] [[package]] name = "aws-types" -version = "0.46.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb54f097516352475a0159c9355f8b4737c54044538a4d9aca4d376ef2361ccc" +checksum = "1bba03e59e1a0223a2bd3567da2b07a458b067ccf7846996b82406e80008ebc1" dependencies = [ "aws-smithy-async", "aws-smithy-client", @@ -701,9 +703,9 @@ dependencies = [ [[package]] name = "coldsnap" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "111badfcdc635ecbffc73bfa46ad0a83ae0c41bc01e09c4045ca3ffb1046c5c5" +checksum = "284c5dc4766d176cbd1ccc07cd5e0ffabe0e2abc1a944faa60fd6bd0de537f17" dependencies = [ "argh", "async-trait", @@ -733,6 +735,7 @@ dependencies = [ "libc", "once_cell", "terminal_size", + "unicode-width", "winapi", ] @@ -1395,14 +1398,13 @@ dependencies = [ [[package]] name = "indicatif" -version = "0.16.2" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d207dc617c7a380ab07ff572a6e52fa202a2a8f355860ac9c38e23f8196be1b" +checksum = "bfddc9561e8baf264e0e45e197fd7696320026eb10a8180340debc27b18f535b" dependencies = [ "console", - "lazy_static", "number_prefix", - "regex", + "unicode-width", ] [[package]] @@ -1726,10 +1728,11 @@ dependencies = [ [[package]] name = "nix" -version = "0.24.2" +version = "0.25.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "195cdbc1741b8134346d515b3a56a1c94b0912758009cfd53f99ea0f57b065fc" +checksum = "e322c04a9e3440c327fca7b6c8a63e6890a32fa2ad689db972425f07e0d22abb" dependencies = [ + "autocfg", "bitflags", "cfg-if", "libc", @@ -1796,9 +1799,9 @@ dependencies = [ [[package]] name = "olpc-cjson" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72ca49fe685014bbf124ee547da94ed7bb65a6eb9dc9c4711773c081af96a39c" +checksum = "87dc75cf72208cd853671c1abccc5d5d1e43b1e378dde67340ef933219a8c13c" dependencies = [ "serde", "serde_json", @@ -3142,9 +3145,9 @@ checksum = "ea68304e134ecd095ac6c3574494fc62b909f416c4fca77e440530221e549d3d" [[package]] name = "tough" -version = "0.12.4" +version = "0.12.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70a537c6b4307f5401e82a0196e97aaab9599e9c0f880e168eafb176abbac63d" +checksum = "dc636dd1ee889a366af6731f1b63b60baf19528b46df5a7c2d4b3bf8b60bca2d" dependencies = [ "chrono", "dyn-clone", @@ -3169,9 +3172,9 @@ dependencies = [ [[package]] name = "tough-kms" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "52e17edfb12e2c08c9ac3fe6ebb43fafc82fa9ffbfffbe50030b7623f8f42f34" +checksum = "6d12f5356a5902062ec2aaf6ca003b8742c7c8f82e959698fee903275a8ba506" dependencies = [ "aws-config", "aws-sdk-kms", @@ -3184,9 +3187,9 @@ dependencies = [ [[package]] name = "tough-ssm" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "71e423321963b68b425bc844c01a16bfcab3b8300ab768dad46992201026421e" +checksum = "dffd50ee15d08e9b104b398e4537acfc3c02f76e1d0c569856290d278bb5180b" dependencies = [ "aws-config", "aws-sdk-ssm", diff --git a/tools/deny.toml b/tools/deny.toml index 372ac1aa821..9e050d23521 100644 --- a/tools/deny.toml +++ b/tools/deny.toml @@ -70,7 +70,7 @@ skip-tree = [ { name = "structopt", version = "0.3.26" }, # aws-smithy-client uses an older hyper-rustls - { name = "aws-smithy-client", version = "0.46.0" }, + { name = "aws-smithy-client", version = "0.48.0" }, ] [sources] diff --git a/tools/pubsys/Cargo.toml b/tools/pubsys/Cargo.toml index 4d30af5c294..903909a0943 100644 --- a/tools/pubsys/Cargo.toml +++ b/tools/pubsys/Cargo.toml @@ -8,21 +8,21 @@ publish = false [dependencies] async-trait = "0.1.53" -aws-config = "0.46.0" -aws-sdk-ebs = "0.16.0" -aws-sdk-ec2 = "0.16.0" -aws-sdk-kms = "0.16.0" -aws-sdk-ssm = "0.16.0" -aws-sdk-sts = "0.16.0" -aws-smithy-types = "0.46.0" -aws-types = "0.46.0" +aws-config = "0.48.0" +aws-sdk-ebs = "0.18.0" +aws-sdk-ec2 = "0.18.0" +aws-sdk-kms = "0.18.0" +aws-sdk-ssm = "0.18.0" +aws-sdk-sts = "0.18.0" +aws-smithy-types = "0.48.0" +aws-types = "0.48.0" chrono = "0.4" clap = "3.1" coldsnap = { version = "0.4", default-features = false, features = ["aws-sdk-rust-rustls"] } duct = "0.13.0" futures = "0.3.5" http = "0.2.8" -indicatif = "0.16.0" +indicatif = "0.17.1" lazy_static = "1.4" log = "0.4" num_cpus = "1" diff --git a/tools/pubsys/src/aws/ami/snapshot.rs b/tools/pubsys/src/aws/ami/snapshot.rs index b26249d85a5..15b25611910 100644 --- a/tools/pubsys/src/aws/ami/snapshot.rs +++ b/tools/pubsys/src/aws/ami/snapshot.rs @@ -4,17 +4,18 @@ use snafu::{OptionExt, ResultExt}; use std::path::Path; /// Create a progress bar to show status of snapshot blocks, if wanted. -fn build_progress_bar(no_progress: bool, verb: &str) -> Option<ProgressBar> { +fn build_progress_bar(no_progress: bool, verb: &str) -> Result<Option<ProgressBar>> { if no_progress { - return None; + return Ok(None); } let progress_bar = ProgressBar::new(0); progress_bar.set_style( ProgressStyle::default_bar() .template(&[" ", verb, " [{bar:50.white/black}] {pos}/{len} ({eta})"].concat()) + .context(error::ProgressBarTemplateSnafu)? .progress_chars("=> "), ); - Some(progress_bar) + Ok(Some(progress_bar)) } /// Uploads the given path into a snapshot. @@ -35,7 +36,7 @@ where .to_string_lossy(); uploader - .upload_from_file(path, desired_size, Some(&filename), progress_bar) + .upload_from_file(path, desired_size, Some(&filename), progress_bar?) .await .context(error::UploadSnapshotSnafu) } @@ -51,6 +52,11 @@ mod error { #[snafu(display("Invalid image path '{}'", path.display()))] InvalidImagePath { path: PathBuf }, + #[snafu(display("Failed to parse progress style template: {}", source))] + ProgressBarTemplate { + source: indicatif::style::TemplateError, + }, + #[snafu(display("Failed to upload snapshot: {}", source))] UploadSnapshot { source: coldsnap::UploadError }, }
diff --git a/tools/testsys/Cargo.toml b/tools/testsys/Cargo.toml index 0da89992484..a02b2636303 100644 --- a/tools/testsys/Cargo.toml +++ b/tools/testsys/Cargo.toml @@ -8,8 +8,8 @@ publish = false [dependencies] anyhow = "1.0" -aws-config = "0.46" -aws-sdk-ec2 = "0.16" +aws-config = "0.48" +aws-sdk-ec2 = "0.18" bottlerocket-types = { git = "https://github.com/bottlerocket-os/bottlerocket-test-system", rev = "07b9ae8", version = "0.0.1"} bottlerocket-variant = { version = "0.1", path = "../../sources/bottlerocket-variant" } clap = { version = "3", features = ["derive", "env"] }
Update rust dependencies for 1.10.0 <!-- Tips: - Please search for similar requests, including closed issues. - Please include details about the environment you're running in. --> We should update dependencies of our Rust packages in Bottlerocket to prepare for 1.10.0. We did this for 1.9.0 in https://github.com/bottlerocket-os/bottlerocket/pull/2303 --- **Update tasks:** - [x] cargo update `sources` #2458 - [x] cargo update `tools` #2458 - [x] Update `tough` https://github.com/awslabs/tough/pull/514 https://github.com/awslabs/tough/pull/516 https://github.com/awslabs/tough/pull/518 - [x] Update `coldsnap` https://github.com/awslabs/coldsnap/pull/197 https://github.com/awslabs/coldsnap/pull/201 - [x] Update AWS SDK for Rust and `tough` in `sources` https://github.com/bottlerocket-os/bottlerocket/pull/2476 - [x] Update AWS SDK for Rust, `tough`, `coldsnap`, and `indicatif` in `tools` https://github.com/bottlerocket-os/bottlerocket/pull/2476
2022-10-03T23:41:47Z
bottlerocket-os/bottlerocket
2,445
bottlerocket-os__bottlerocket-2445
[ "2204" ]
d04eaa730285cf32430c3897bf33b4593042242c
diff --git a/PROVISIONING-METAL.md b/PROVISIONING-METAL.md index 33427d52ded..ae9299769aa 100644 --- a/PROVISIONING-METAL.md +++ b/PROVISIONING-METAL.md @@ -76,7 +76,7 @@ When these services fail, your machine will not connect to any cluster and will #### `net.toml` structure The configuration file must be valid TOML and have the filename `net.toml`. -The first and required top level key in the file is `version`, currently only `1` is supported. +The first and required top level key in the file is `version`; the latest is version `2`. The rest of the file is a map of interface name to supported settings. Interface names are expected to be correct as per `udevd` naming, no interface naming or matching is supported. (See the note below regarding `udevd` interface naming.) @@ -92,9 +92,22 @@ Interface names are expected to be correct as per `udevd` naming, no interface n * `enabled` (boolean, required): Enables DHCP6. * `optional` (boolean): the system will request a lease using this protocol, but will not wait for a valid lease to consider this interface configured. +As of version `2` static addressing with simple routes is supported via the below settings. +Please keep in mind that when using static addresses, DNS information must be supplied to the system via user data: [`settings.dns`](https://github.com/bottlerocket-os/bottlerocket#network-settings). +* `static4` (map): IPv4 static address settings. + * `addresses` (list of quoted IPv4 address including prefix): The desired IPv4 IP addresses, including prefix i.e. `["192.168.14.2/24"]`. The first IP in the list will be used as the primary IP which `kubelet` will use when joining the cluster. If IPv4 and IPv6 static addresses exist, the first IPv4 address is used. +* `static6` (map): IPv6 static address settings. + * `addresses` (list of quoted IPv6 address including prefix): The desired IPv6 IP addresses, including prefix i.e. `["2001:dead:beef::2/64"]`. The first IP in the list will be used as the primary IP which `kubelet` will use when joining the cluster. If IPv4 and IPv6 static addresses exist, the first IPv4 address is used. + +* `route` (map): Static route; multiple routes can be added. (cannot be used in conjuction with DHCP) + * `to` (`"default"` or IP address with prefix, required): Destination address. + * `from` (IP address): Source IP address. + * `via` (IP address): Gateway IP address. If no gateway is provided, a scope of `link` is assumed. + * `route-metric` (integer): Relative route priority. + Example `net.toml` with comments: ```toml -version = 1 +version = 2 # "eno1" is the interface name [eno1] @@ -108,12 +121,35 @@ primary = true # `enabled` is a boolean and is a required key when # setting up DHCP this way enabled = true -# Route metric may be supplied for ipv4 +# Route metric may be supplied for IPv4 route-metric = 200 [eno2.dhcp6] enabled = true optional = true + +[eno3.static4] +addresses = ["10.0.0.10/24", "11.0.0.11/24"] + +# Multiple routes may be configured +[[eno3.route]] +to = "default" +via = "10.0.0.1" +route-metric = 100 + +[[eno3.route]] +to = "default" +via = "11.0.0.1" +route-metric = 200 + +[eno4.static4] +addresses = ["192.168.14.5/24"] + +# Using a source IP and non-default route +[[eno4.route]] +to = "10.10.10.0/24" +from = "192.168.14.5" +via = "192.168.14.25" ``` **An additional note on network device names** diff --git a/sources/api/netdog/src/cli/install.rs b/sources/api/netdog/src/cli/install.rs index 02fe3490668..6e5b9d9cdb7 100644 --- a/sources/api/netdog/src/cli/install.rs +++ b/sources/api/netdog/src/cli/install.rs @@ -1,12 +1,12 @@ use super::{error, InterfaceFamily, InterfaceType, Result}; use crate::dns::DnsSettings; -use crate::lease::{lease_path, LeaseInfo}; +use crate::lease::{dhcp_lease_path, static_lease_path, LeaseInfo}; use crate::{CURRENT_IP, PRIMARY_INTERFACE}; use argh::FromArgs; -use snafu::{OptionExt, ResultExt}; +use snafu::{ensure, OptionExt, ResultExt}; use std::fs; use std::net::IpAddr; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; #[derive(FromArgs, PartialEq, Debug)] #[argh(subcommand, name = "install")] @@ -50,36 +50,57 @@ pub(crate) fn run(args: InstallArgs) -> Result<()> { } match (&args.interface_type, &args.interface_family) { - (InterfaceType::Dhcp, InterfaceFamily::Ipv4 | InterfaceFamily::Ipv6) => { - // A lease should exist when using DHCP - let primary_lease_path = - lease_path(&primary_interface).context(error::MissingLeaseSnafu { - interface: primary_interface, - })?; - if args.data_file != primary_lease_path { - return error::PrimaryLeaseConflictSnafu { - wicked_path: args.data_file, - generated_path: primary_lease_path, - } - .fail(); - } - - // Use DNS API settings if they exist, supplementing any missing settings with settings - // derived from the primary interface's DHCP lease - let lease = - LeaseInfo::from_lease(primary_lease_path).context(error::LeaseParseFailedSnafu)?; - let dns_settings = DnsSettings::from_config_or_lease(Some(&lease)) - .context(error::GetDnsSettingsSnafu)?; - dns_settings - .write_resolv_conf() - .context(error::ResolvConfWriteFailedSnafu)?; - + ( + interface_type @ (InterfaceType::Dhcp | InterfaceType::Static), + InterfaceFamily::Ipv4 | InterfaceFamily::Ipv6, + ) => { + let lease = fetch_lease(primary_interface, interface_type, args.data_file)?; + write_resolv_conf(&lease)?; write_current_ip(&lease.ip_address.addr())?; } } Ok(()) } +/// Given an interface, its type, and wicked's known location of the lease, compare our known lease +/// location, parse and return a LeaseInfo. +fn fetch_lease<S, P>( + interface: S, + interface_type: &InterfaceType, + data_file: P, +) -> Result<LeaseInfo> +where + S: AsRef<str>, + P: AsRef<Path>, +{ + let interface = interface.as_ref(); + let data_file = data_file.as_ref(); + let lease_path = match interface_type { + InterfaceType::Dhcp => dhcp_lease_path(interface), + InterfaceType::Static => static_lease_path(interface), + } + .context(error::MissingLeaseSnafu { interface })?; + + ensure!( + data_file == lease_path, + error::PrimaryLeaseConflictSnafu { + wicked_path: data_file, + generated_path: lease_path, + } + ); + + LeaseInfo::from_lease(&lease_path).context(error::LeaseParseFailedSnafu) +} + +/// Given a lease, fetch DNS settings from the lease and/or config and write the resolv.conf +fn write_resolv_conf(lease: &LeaseInfo) -> Result<()> { + let dns_settings = + DnsSettings::from_config_or_lease(Some(lease)).context(error::GetDnsSettingsSnafu)?; + dns_settings + .write_resolv_conf() + .context(error::ResolvConfWriteFailedSnafu) +} + /// Persist the current IP address to file fn write_current_ip(ip: &IpAddr) -> Result<()> { fs::write(CURRENT_IP, ip.to_string()) diff --git a/sources/api/netdog/src/cli/mod.rs b/sources/api/netdog/src/cli/mod.rs index b43560ac1b5..de8709ffb1c 100644 --- a/sources/api/netdog/src/cli/mod.rs +++ b/sources/api/netdog/src/cli/mod.rs @@ -22,6 +22,7 @@ pub(crate) use write_resolv_conf::WriteResolvConfArgs; #[serde(rename_all = "kebab-case")] enum InterfaceType { Dhcp, + Static, } #[derive(Debug, PartialEq, Deserialize)] diff --git a/sources/api/netdog/src/cli/write_resolv_conf.rs b/sources/api/netdog/src/cli/write_resolv_conf.rs index f15208f31e7..552c2ca0b01 100644 --- a/sources/api/netdog/src/cli/write_resolv_conf.rs +++ b/sources/api/netdog/src/cli/write_resolv_conf.rs @@ -1,6 +1,6 @@ use super::{error, Result}; use crate::dns::DnsSettings; -use crate::lease::{lease_path, LeaseInfo}; +use crate::lease::{dhcp_lease_path, LeaseInfo}; use crate::PRIMARY_INTERFACE; use argh::FromArgs; use snafu::ResultExt; @@ -12,8 +12,9 @@ use std::fs; pub(crate) struct WriteResolvConfArgs {} pub(crate) fn run() -> Result<()> { - // Use DNS API settings if they exist, supplementing any missing settings with settings - // derived from the primary interface's DHCP lease if it exists + // Use DNS API settings if they exist, supplementing any missing settings with settings derived + // from the primary interface's DHCP lease if it exists. Static leases don't contain any DNS + // data, so don't bother looking there. let primary_interface = fs::read_to_string(PRIMARY_INTERFACE) .context(error::PrimaryInterfaceReadSnafu { path: PRIMARY_INTERFACE, @@ -21,7 +22,7 @@ pub(crate) fn run() -> Result<()> { .trim() .to_lowercase(); - let primary_lease_path = lease_path(&primary_interface); + let primary_lease_path = dhcp_lease_path(&primary_interface); let dns_settings = if let Some(primary_lease_path) = primary_lease_path { let lease = LeaseInfo::from_lease(&primary_lease_path).context(error::LeaseParseFailedSnafu)?; diff --git a/sources/api/netdog/src/dns.rs b/sources/api/netdog/src/dns.rs index c76c7d88e14..10ccc5c3ffe 100644 --- a/sources/api/netdog/src/dns.rs +++ b/sources/api/netdog/src/dns.rs @@ -37,7 +37,7 @@ impl DnsSettings { /// Merge missing DNS settings into `self` using DHCP lease fn merge_lease(&mut self, lease: &LeaseInfo) { if self.nameservers.is_none() { - self.nameservers = Some(lease.dns_servers.clone()); + self.nameservers = lease.dns_servers.clone(); } if self.search.is_none() { diff --git a/sources/api/netdog/src/lease.rs b/sources/api/netdog/src/lease.rs index 81c4a0eb080..36772b93cb5 100644 --- a/sources/api/netdog/src/lease.rs +++ b/sources/api/netdog/src/lease.rs @@ -21,10 +21,13 @@ lazy_static! { #[derive(Debug, Deserialize)] #[allow(dead_code)] pub(crate) struct LeaseInfo { + // When multiple IP addresses exist for an interface, the second address's key in the lease + // file will be `IPADDR_1`, `IPADDR_2`, and so on. Parsing the lease for "ipaddr" means we + // will always pick up the first configured IP address. #[serde(rename = "ipaddr")] pub(crate) ip_address: IpNet, #[serde(rename = "dnsservers")] - pub(crate) dns_servers: BTreeSet<IpAddr>, + pub(crate) dns_servers: Option<BTreeSet<IpAddr>>, #[serde(rename = "dnsdomain")] pub(crate) dns_domain: Option<String>, #[serde(rename = "dnssearch")] @@ -63,15 +66,36 @@ impl LeaseInfo { } } -/// Return the path to a given interface's ipv4/ipv6 lease if it exists, favoring ipv4 if both +/// Return the path to a given interface's DHCP ipv4/ipv6 lease if it exists, favoring ipv4 if both /// ipv4 and ipv6 exist -pub(crate) fn lease_path<S>(interface: S) -> Option<PathBuf> +pub(crate) fn dhcp_lease_path<S>(interface: S) -> Option<PathBuf> where S: AsRef<str>, { + get_lease_path("dhcp", interface) +} + +/// Return the path to a given interface's static ipv4/ipv6 lease if it exists, favoring ipv4 if +/// both ipv4 and ipv6 exist +pub(crate) fn static_lease_path<S>(interface: S) -> Option<PathBuf> +where + S: AsRef<str>, +{ + get_lease_path("static", interface) +} + +/// Given a lease type and interface, return the path to the ipv4/6 lease file if it exists, +/// favoring ipv4 if both ipv4 and ipv6 exist +fn get_lease_path<S1, S2>(lease_type: S1, interface: S2) -> Option<PathBuf> +where + S1: AsRef<str>, + S2: AsRef<str>, +{ + let lease_type = lease_type.as_ref(); let interface = interface.as_ref(); - let ipv4 = Path::new(LEASE_DIR).join(format!("leaseinfo.{}.dhcp.ipv4", interface)); - let ipv6 = Path::new(LEASE_DIR).join(format!("leaseinfo.{}.dhcp.ipv6", interface)); + + let ipv4 = Path::new(LEASE_DIR).join(format!("leaseinfo.{}.{}.ipv4", interface, lease_type)); + let ipv6 = Path::new(LEASE_DIR).join(format!("leaseinfo.{}.{}.ipv6", interface, lease_type)); // If both ipv4 and ipv6 leases exist, use the ipv4 lease for DNS settings let ipv4_exists = Path::exists(&ipv4); diff --git a/sources/api/netdog/src/net_config/mod.rs b/sources/api/netdog/src/net_config/mod.rs index c76f3f81c02..977203eebce 100644 --- a/sources/api/netdog/src/net_config/mod.rs +++ b/sources/api/netdog/src/net_config/mod.rs @@ -5,13 +5,16 @@ //! These structures are the user-facing options for configuring one or more network interfaces. mod dhcp; mod error; +mod static_address; mod v1; +mod v2; use crate::wicked::WickedInterface; pub(crate) use dhcp::{Dhcp4ConfigV1, Dhcp4OptionsV1, Dhcp6ConfigV1, Dhcp6OptionsV1}; pub(crate) use error::{Error, Result}; use serde::Deserialize; use snafu::{ensure, ResultExt}; +pub(crate) use static_address::{RouteTo, RouteV1, StaticConfigV1}; use std::fs; use std::path::Path; use std::str::FromStr; @@ -93,7 +96,8 @@ fn deserialize_config(config_str: &str) -> Result<Box<dyn Interfaces>> { } = toml::from_str(config_str).context(error::NetConfigParseSnafu)?; let net_config: Box<dyn Interfaces> = match version { - 1 => validate_config::<NetConfigV1>(interface_config)?, + 1 => validate_config::<v1::NetConfigV1>(interface_config)?, + 2 => validate_config::<v2::NetConfigV2>(interface_config)?, _ => { return error::InvalidNetConfigSnafu { reason: format!("Unknown network config version: {}", version), diff --git a/sources/api/netdog/src/net_config/static_address.rs b/sources/api/netdog/src/net_config/static_address.rs new file mode 100644 index 00000000000..9d4c7beceba --- /dev/null +++ b/sources/api/netdog/src/net_config/static_address.rs @@ -0,0 +1,65 @@ +use ipnet::IpNet; +use serde::Deserialize; +use snafu::ResultExt; +use std::collections::BTreeSet; +use std::convert::TryFrom; +use std::net::IpAddr; + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct StaticConfigV1 { + pub(crate) addresses: BTreeSet<IpNet>, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct RouteV1 { + pub(crate) to: RouteTo, + pub(crate) from: Option<IpAddr>, + pub(crate) via: Option<IpAddr>, + #[serde(rename = "route-metric")] + pub(crate) route_metric: Option<u32>, +} + +#[derive(Clone, Debug, Deserialize)] +#[serde(try_from = "String")] +pub(crate) enum RouteTo { + DefaultRoute, + Ip(IpNet), +} + +// Allows the user to pass the string "default" or a valid ip address prefix. We can't use an +// untagged enum for this (#[serde(untagged)]) because "default" directly maps to one of the +// variants. Serde will only allow the "untagged" attribute if neither variant directly matches. +impl TryFrom<String> for RouteTo { + type Error = error::Error; + + fn try_from(input: String) -> Result<Self> { + let input = input.to_lowercase(); + Ok(match input.as_str() { + "default" => RouteTo::DefaultRoute, + _ => { + let ip: IpNet = input + .parse() + .context(error::InvalidRouteDestinationSnafu { input })?; + RouteTo::Ip(ip) + } + }) + } +} + +mod error { + use snafu::Snafu; + + #[derive(Debug, Snafu)] + #[snafu(visibility(pub(crate)))] + pub(crate) enum Error { + #[snafu(display("Invalid route destination, must be 'default' or a valid IP address prefix. Received '{}': {}", input, source))] + InvalidRouteDestination { + input: String, + source: ipnet::AddrParseError, + }, + } +} + +type Result<T> = std::result::Result<T, error::Error>; diff --git a/sources/api/netdog/src/net_config/v1.rs b/sources/api/netdog/src/net_config/v1.rs index 1ecf7c08356..9b39ec37587 100644 --- a/sources/api/netdog/src/net_config/v1.rs +++ b/sources/api/netdog/src/net_config/v1.rs @@ -5,7 +5,7 @@ use super::{error, Dhcp4ConfigV1, Dhcp6ConfigV1, Error, Interfaces, Result, Vali use crate::{ interface_name::InterfaceName, net_config::{Dhcp4OptionsV1, Dhcp6OptionsV1}, - wicked::{WickedControl, WickedDhcp4, WickedDhcp6, WickedInterface}, + wicked::{WickedDhcp4, WickedDhcp6, WickedInterface}, }; use indexmap::indexmap; use indexmap::IndexMap; @@ -55,13 +55,11 @@ impl Interfaces for NetConfigV1 { for (name, config) in &self.interfaces { let wicked_dhcp4 = config.dhcp4.clone().map(WickedDhcp4::from); let wicked_dhcp6 = config.dhcp6.clone().map(WickedDhcp6::from); - let wicked_interface = WickedInterface { - name: name.clone(), - control: WickedControl::default(), - ipv4_dhcp: wicked_dhcp4, - ipv6_dhcp: wicked_dhcp6, - }; - wicked_interfaces.push(wicked_interface) + let mut interface = WickedInterface::new(name.clone()); + interface.ipv4_dhcp = wicked_dhcp4; + interface.ipv6_dhcp = wicked_dhcp6; + + wicked_interfaces.push(interface) } wicked_interfaces diff --git a/sources/api/netdog/src/net_config/v2.rs b/sources/api/netdog/src/net_config/v2.rs new file mode 100644 index 00000000000..1dd4965fd33 --- /dev/null +++ b/sources/api/netdog/src/net_config/v2.rs @@ -0,0 +1,145 @@ +//! The `v2` module contains the second version of the network configuration and implements the +//! appropriate traits. + +use super::static_address::{RouteV1, StaticConfigV1}; +use super::{error, Dhcp4ConfigV1, Dhcp6ConfigV1, Interfaces, Result, Validate}; +use crate::interface_name::InterfaceName; +use crate::wicked::{WickedDhcp4, WickedDhcp6, WickedInterface, WickedRoutes, WickedStaticAddress}; +use indexmap::IndexMap; +use ipnet::IpNet; +use serde::Deserialize; +use snafu::ensure; + +#[derive(Debug, Deserialize)] +pub(crate) struct NetConfigV2 { + #[serde(flatten)] + pub(crate) interfaces: IndexMap<InterfaceName, NetInterfaceV2>, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct NetInterfaceV2 { + // Use this interface as the primary interface for the system + pub(crate) primary: Option<bool>, + pub(crate) dhcp4: Option<Dhcp4ConfigV1>, + pub(crate) dhcp6: Option<Dhcp6ConfigV1>, + pub(crate) static4: Option<StaticConfigV1>, + pub(crate) static6: Option<StaticConfigV1>, + #[serde(rename = "route")] + pub(crate) routes: Option<Vec<RouteV1>>, +} + +impl Interfaces for NetConfigV2 { + fn primary_interface(&self) -> Option<String> { + self.interfaces + .iter() + .find(|(_, v)| v.primary == Some(true)) + .or_else(|| self.interfaces.first()) + .map(|(n, _)| n.to_string()) + } + + fn has_interfaces(&self) -> bool { + !self.interfaces.is_empty() + } + + fn as_wicked_interfaces(&self) -> Vec<WickedInterface> { + let mut wicked_interfaces = Vec::with_capacity(self.interfaces.len()); + for (name, config) in &self.interfaces { + let mut interface = WickedInterface::new(name.clone()); + interface.ipv4_dhcp = config.dhcp4.clone().map(WickedDhcp4::from); + interface.ipv6_dhcp = config.dhcp6.clone().map(WickedDhcp6::from); + + // Based on the existence of static addresses and routes, create the ipv4/6_static + // struct members. They must be `Option`s because we want to avoid serializing empty + // tags into the config file + let maybe_routes = config.routes.clone().map(WickedRoutes::from); + let maybe_ipv4_static = WickedStaticAddress::maybe_new( + config.static4.clone(), + maybe_routes.as_ref().and_then(|s| s.ipv4.clone()), + ); + let maybe_ipv6_static = WickedStaticAddress::maybe_new( + config.static6.clone(), + maybe_routes.as_ref().and_then(|s| s.ipv6.clone()), + ); + interface.ipv4_static = maybe_ipv4_static; + interface.ipv6_static = maybe_ipv6_static; + + wicked_interfaces.push(interface); + } + + wicked_interfaces + } +} + +impl Validate for NetConfigV2 { + fn validate(&self) -> Result<()> { + for (_name, config) in &self.interfaces { + let has_static = config.static4.is_some() || config.static6.is_some(); + let has_dhcp = config.dhcp4.is_some() || config.dhcp6.is_some(); + let has_routes = config.routes.is_some(); + + if !has_dhcp && !has_static { + return error::InvalidNetConfigSnafu { + reason: "each interface must configure dhcp and/or static addresses", + } + .fail(); + } + + // wicked doesn't support static routes with dhcp + if has_dhcp && has_routes { + return error::InvalidNetConfigSnafu { + reason: "static routes are not supported with dhcp", + } + .fail(); + } + + if has_routes && !has_static { + return error::InvalidNetConfigSnafu { + reason: "interfaces must set static addresses in order to use routes", + } + .fail(); + } + + if let Some(config) = &config.static4 { + ensure!( + config.addresses.iter().all(|a| matches!(a, IpNet::V4(_))), + error::InvalidNetConfigSnafu { + reason: "'static4' may only contain IPv4 addresses" + } + ) + } + + if let Some(config) = &config.static6 { + ensure!( + config.addresses.iter().all(|a| matches!(a, IpNet::V6(_))), + error::InvalidNetConfigSnafu { + reason: "'static6' may only contain IPv6 addresses" + } + ) + } + } + + let primary_count = self + .interfaces + .values() + .filter(|v| v.primary == Some(true)) + .count(); + ensure!( + primary_count <= 1, + error::InvalidNetConfigSnafu { + reason: "multiple primary interfaces defined, expected 1" + } + ); + + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use crate::net_config::test_macros::{basic_tests, dhcp_tests, static_address_tests}; + + basic_tests!(2); + dhcp_tests!(2); + static_address_tests!(2); +} diff --git a/sources/api/netdog/src/wicked/dhcp.rs b/sources/api/netdog/src/wicked/dhcp.rs new file mode 100644 index 00000000000..3caba072868 --- /dev/null +++ b/sources/api/netdog/src/wicked/dhcp.rs @@ -0,0 +1,119 @@ +use crate::net_config::{Dhcp4ConfigV1, Dhcp4OptionsV1, Dhcp6ConfigV1, Dhcp6OptionsV1}; +use serde::Serialize; + +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "kebab-case")] +pub(crate) struct WickedDhcp4 { + #[serde(rename = "$unflatten=enabled")] + enabled: bool, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "$unflatten=route-priority")] + route_priority: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "$unflatten=defer-timeout")] + defer_timeout: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + flags: Option<AddrConfFlags>, +} + +impl Default for WickedDhcp4 { + fn default() -> Self { + WickedDhcp4 { + enabled: true, + route_priority: None, + defer_timeout: None, + flags: None, + } + } +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +#[serde(rename_all = "kebab-case")] +pub(crate) struct WickedDhcp6 { + #[serde(rename = "$unflatten=enabled")] + enabled: bool, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "$unflatten=defer-timeout")] + defer_timeout: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + flags: Option<AddrConfFlags>, +} + +impl Default for WickedDhcp6 { + fn default() -> Self { + WickedDhcp6 { + enabled: true, + defer_timeout: None, + flags: None, + } + } +} + +// This is technically an enum, but considering we don't expose anything other than "optional" to +// the user, a struct makes handling tags much simpler. +#[derive(Default, Clone, Debug, Serialize, PartialEq)] +struct AddrConfFlags { + #[serde(rename = "$unflatten=optional")] + optional: (), +} + +impl From<Dhcp4ConfigV1> for WickedDhcp4 { + fn from(dhcp4: Dhcp4ConfigV1) -> Self { + match dhcp4 { + Dhcp4ConfigV1::DhcpEnabled(b) => WickedDhcp4 { + enabled: b, + ..Default::default() + }, + Dhcp4ConfigV1::WithOptions(o) => WickedDhcp4::from(o), + } + } +} + +impl From<Dhcp4OptionsV1> for WickedDhcp4 { + fn from(options: Dhcp4OptionsV1) -> Self { + let mut defer_timeout = None; + let mut flags = None; + + if options.optional == Some(true) { + defer_timeout = Some(1); + flags = Some(AddrConfFlags::default()); + } + + WickedDhcp4 { + enabled: options.enabled, + route_priority: options.route_metric, + defer_timeout, + flags, + } + } +} + +impl From<Dhcp6ConfigV1> for WickedDhcp6 { + fn from(dhcp6: Dhcp6ConfigV1) -> Self { + match dhcp6 { + Dhcp6ConfigV1::DhcpEnabled(b) => WickedDhcp6 { + enabled: b, + ..Default::default() + }, + Dhcp6ConfigV1::WithOptions(o) => WickedDhcp6::from(o), + } + } +} + +impl From<Dhcp6OptionsV1> for WickedDhcp6 { + fn from(options: Dhcp6OptionsV1) -> Self { + let mut defer_timeout = None; + let mut flags = None; + + if options.optional == Some(true) { + defer_timeout = Some(1); + flags = Some(AddrConfFlags::default()); + } + + WickedDhcp6 { + enabled: options.enabled, + defer_timeout, + flags, + } + } +} diff --git a/sources/api/netdog/src/wicked.rs b/sources/api/netdog/src/wicked/mod.rs similarity index 56% rename from sources/api/netdog/src/wicked.rs rename to sources/api/netdog/src/wicked/mod.rs index 3762c0a6e31..ad2f13a8986 100644 --- a/sources/api/netdog/src/wicked.rs +++ b/sources/api/netdog/src/wicked/mod.rs @@ -3,10 +3,14 @@ //! //! The structures in this module are meant to be created from the user-facing structures in the //! `net_config` module. `Default` implementations for WickedInterface exist here as well. +mod dhcp; +mod static_address; + use crate::interface_name::InterfaceName; -use crate::net_config::{Dhcp4ConfigV1, Dhcp4OptionsV1, Dhcp6ConfigV1, Dhcp6OptionsV1}; +pub(crate) use dhcp::{WickedDhcp4, WickedDhcp6}; use serde::Serialize; use snafu::ResultExt; +pub(crate) use static_address::{WickedRoutes, WickedStaticAddress}; use std::fs; use std::path::Path; @@ -25,6 +29,12 @@ pub(crate) struct WickedInterface { #[serde(skip_serializing_if = "Option::is_none")] #[serde(rename = "ipv6:dhcp")] pub(crate) ipv6_dhcp: Option<WickedDhcp6>, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "ipv4:static")] + pub(crate) ipv4_static: Option<WickedStaticAddress>, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "ipv6:static")] + pub(crate) ipv6_static: Option<WickedStaticAddress>, } #[derive(Debug, Serialize, PartialEq)] @@ -56,124 +66,18 @@ struct LinkDetection { require_link: (), } -#[derive(Debug, Clone, Serialize, PartialEq)] -#[serde(rename_all = "kebab-case")] -pub(crate) struct WickedDhcp4 { - #[serde(rename = "$unflatten=enabled")] - enabled: bool, - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(rename = "$unflatten=route-priority")] - route_priority: Option<u32>, - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(rename = "$unflatten=defer-timeout")] - defer_timeout: Option<u32>, - #[serde(skip_serializing_if = "Option::is_none")] - flags: Option<AddrConfFlags>, -} - -impl Default for WickedDhcp4 { - fn default() -> Self { - WickedDhcp4 { - enabled: true, - route_priority: None, - defer_timeout: None, - flags: None, - } - } -} - -#[derive(Debug, Clone, Serialize, PartialEq)] -#[serde(rename_all = "kebab-case")] -pub(crate) struct WickedDhcp6 { - #[serde(rename = "$unflatten=enabled")] - enabled: bool, - #[serde(skip_serializing_if = "Option::is_none")] - #[serde(rename = "$unflatten=defer-timeout")] - defer_timeout: Option<u32>, - #[serde(skip_serializing_if = "Option::is_none")] - flags: Option<AddrConfFlags>, -} - -impl Default for WickedDhcp6 { - fn default() -> Self { - WickedDhcp6 { - enabled: true, - defer_timeout: None, - flags: None, - } - } -} - -// This is technically an enum, but considering we don't expose anything other than "optional" to -// the user, a struct makes handling tags much simpler. -#[derive(Default, Clone, Debug, Serialize, PartialEq)] -struct AddrConfFlags { - #[serde(rename = "$unflatten=optional")] - optional: (), -} - -impl From<Dhcp4ConfigV1> for WickedDhcp4 { - fn from(dhcp4: Dhcp4ConfigV1) -> Self { - match dhcp4 { - Dhcp4ConfigV1::DhcpEnabled(b) => WickedDhcp4 { - enabled: b, - ..Default::default() - }, - Dhcp4ConfigV1::WithOptions(o) => WickedDhcp4::from(o), - } - } -} - -impl From<Dhcp4OptionsV1> for WickedDhcp4 { - fn from(options: Dhcp4OptionsV1) -> Self { - let mut defer_timeout = None; - let mut flags = None; - - if options.optional == Some(true) { - defer_timeout = Some(1); - flags = Some(AddrConfFlags::default()); - } - - WickedDhcp4 { - enabled: options.enabled, - route_priority: options.route_metric, - defer_timeout, - flags, - } - } -} - -impl From<Dhcp6ConfigV1> for WickedDhcp6 { - fn from(dhcp6: Dhcp6ConfigV1) -> Self { - match dhcp6 { - Dhcp6ConfigV1::DhcpEnabled(b) => WickedDhcp6 { - enabled: b, - ..Default::default() - }, - Dhcp6ConfigV1::WithOptions(o) => WickedDhcp6::from(o), - } - } -} - -impl From<Dhcp6OptionsV1> for WickedDhcp6 { - fn from(options: Dhcp6OptionsV1) -> Self { - let mut defer_timeout = None; - let mut flags = None; - - if options.optional == Some(true) { - defer_timeout = Some(1); - flags = Some(AddrConfFlags::default()); - } - - WickedDhcp6 { - enabled: options.enabled, - defer_timeout, - flags, +impl WickedInterface { + pub(crate) fn new(name: InterfaceName) -> Self { + Self { + name, + control: WickedControl::default(), + ipv4_dhcp: None, + ipv6_dhcp: None, + ipv4_static: None, + ipv6_static: None, } } -} -impl WickedInterface { /// Serialize the interface's configuration file pub(crate) fn write_config_file(&self) -> Result<()> { let mut cfg_path = Path::new(WICKED_CONFIG_DIR).join(self.name.to_string()); @@ -212,9 +116,13 @@ type Result<T> = std::result::Result<T, error::Error>; mod tests { use super::*; use crate::net_config::{self, Interfaces, NetConfigV1}; + use handlebars::Handlebars; + use serde::Serialize; use std::path::PathBuf; use std::str::FromStr; + static NET_CONFIG_VERSIONS: &[u8] = &[1, 2]; + fn test_data() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_data") } @@ -223,10 +131,6 @@ mod tests { test_data().join("wicked") } - fn net_config() -> PathBuf { - test_data().join("net_config") - } - // Test the end-to-end trip: "net config from cmdline -> wicked -> serialized XML" #[test] fn interface_config_from_str() { @@ -263,17 +167,52 @@ mod tests { // Test the end to end trip: "net config -> wicked -> serialized XML" #[test] fn net_config_to_interface_config() { - let net_config_path = net_config().join("net_config.toml"); - let net_config = net_config::from_path(&net_config_path).unwrap().unwrap(); + let net_config_path = wicked_config().join("net_config.toml"); - let wicked_interfaces = net_config.as_wicked_interfaces(); - for interface in wicked_interfaces { - let mut path = wicked_config().join(interface.name.to_string()); - path.set_extension("xml"); - let expected = fs::read_to_string(path).unwrap(); - let generated = quick_xml::se::to_string(&interface).unwrap(); + for version in NET_CONFIG_VERSIONS { + let temp_config = tempfile::NamedTempFile::new().unwrap(); - assert_eq!(expected.trim(), generated) + render_config_template(&net_config_path, &temp_config, &version); + let net_config = net_config::from_path(&temp_config).unwrap().unwrap(); + let wicked_interfaces = net_config.as_wicked_interfaces(); + for interface in wicked_interfaces { + let mut path = wicked_config().join(interface.name.to_string()); + path.set_extension("xml"); + let expected = fs::read_to_string(path).unwrap(); + let generated = quick_xml::se::to_string(&interface).unwrap(); + dbg!(&generated); + + assert_eq!( + expected.trim(), + generated, + "failed test for net config version: '{}', interface: '{}'", + version, + interface.name.to_string() + ) + } + } + } + + fn render_config_template<P1, P2>(template_path: P1, output_path: P2, version: &u8) + where + P1: AsRef<Path>, + P2: AsRef<Path>, + { + #[derive(Serialize)] + struct Context { + version: u8, } + + let output_path = output_path.as_ref(); + let template_path = template_path.as_ref(); + let template_str = fs::read_to_string(template_path).unwrap(); + + let mut hb = Handlebars::new(); + hb.register_template_string("template", &template_str) + .unwrap(); + + let context = Context { version: *version }; + let rendered = hb.render("template", &context).unwrap(); + fs::write(output_path, rendered).unwrap() } } diff --git a/sources/api/netdog/src/wicked/static_address.rs b/sources/api/netdog/src/wicked/static_address.rs new file mode 100644 index 00000000000..fa252fec195 --- /dev/null +++ b/sources/api/netdog/src/wicked/static_address.rs @@ -0,0 +1,146 @@ +use crate::net_config::{RouteTo, RouteV1, StaticConfigV1}; +use ipnet::IpNet; +use lazy_static::lazy_static; +use serde::Serialize; +use std::net::IpAddr; + +lazy_static! { + static ref DEFAULT_ROUTE_IPV4: IpNet = "0.0.0.0/0".parse().unwrap(); + static ref DEFAULT_ROUTE_IPV6: IpNet = "::/0".parse().unwrap(); +} + +#[derive(Default, Debug, Serialize, PartialEq)] +pub(crate) struct WickedStaticAddress { + #[serde(skip_serializing_if = "Option::is_none")] + address: Option<Vec<StaticAddress>>, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "route")] + routes: Option<Vec<WickedRoute>>, +} + +impl WickedStaticAddress { + /// Given the existence, or lack thereof, of addresses and routes, return a + /// WickedStaticAddress. The reason we return an `Option` here is that we don't want to + /// serialize an empty tag if no addresses or routes exist. + /// + /// If routes exist, but no static addresses exist, we drop them on the floor since there is a + /// guard for this condition when validating the network configuration, + pub(crate) fn maybe_new( + addresses: Option<StaticConfigV1>, + routes: Option<Vec<WickedRoute>>, + ) -> Option<Self> { + let static_addresses: Option<Vec<StaticAddress>> = addresses.map(StaticConfigV1::into); + // Wicked doesn't allow routes with DHCP, and routes are worthless without addresses, so + // don't bother creating anything without addresses + static_addresses.as_ref()?; + + Some(WickedStaticAddress { + address: static_addresses, + routes, + }) + } +} + +#[derive(Debug, Serialize, PartialEq)] +pub(crate) struct StaticAddress { + #[serde(rename = "$unflatten=local")] + local: IpNet, +} + +impl From<StaticConfigV1> for Vec<StaticAddress> { + fn from(s: StaticConfigV1) -> Self { + s.addresses + .into_iter() + .map(|a| StaticAddress { local: a }) + .collect() + } +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub(crate) struct WickedRoute { + #[serde(rename = "$unflatten=destination")] + destination: IpNet, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "$unflatten=pref-source")] + pref_source: Option<IpAddr>, + #[serde(skip_serializing_if = "Option::is_none")] + nexthop: Option<WickedNextHop>, + #[serde(skip_serializing_if = "Option::is_none")] + #[serde(rename = "$unflatten=priority")] + priority: Option<u32>, +} + +impl WickedRoute { + pub(crate) fn is_ipv4(&self) -> bool { + match self.destination { + IpNet::V4(_) => true, + IpNet::V6(_) => false, + } + } + + pub(crate) fn is_ipv6(&self) -> bool { + match self.destination { + IpNet::V4(_) => false, + IpNet::V6(_) => true, + } + } +} + +#[derive(Clone, Debug, Serialize, PartialEq)] +pub(crate) struct WickedNextHop { + #[serde(rename = "$unflatten=gateway")] + gateway: Option<IpAddr>, +} + +impl From<RouteV1> for WickedRoute { + fn from(route: RouteV1) -> Self { + let destination = match route.to { + RouteTo::DefaultRoute => match route.via.or(route.from) { + Some(IpAddr::V4(_)) => *DEFAULT_ROUTE_IPV4, + Some(IpAddr::V6(_)) => *DEFAULT_ROUTE_IPV6, + // If no gateway or from is given, assume the ipv4 default + None => *DEFAULT_ROUTE_IPV4, + }, + RouteTo::Ip(ip) => ip, + }; + + let nexthop = WickedNextHop { gateway: route.via }; + + WickedRoute { + destination, + nexthop: Some(nexthop), + pref_source: route.from, + priority: route.route_metric, + } + } +} + +// This type is not meant to be serialized, it's only purpose is to aggregate and categorize the +// ipv4/6 routes on their way to (maybe) being included in a `WickedRoute` which ends up being +// serialized to file. +#[derive(Clone, Default, Debug, PartialEq)] +pub(crate) struct WickedRoutes { + pub(crate) ipv4: Option<Vec<WickedRoute>>, + pub(crate) ipv6: Option<Vec<WickedRoute>>, +} + +impl WickedRoutes { + pub(crate) fn add_route(&mut self, route: WickedRoute) { + if route.is_ipv4() { + self.ipv4.get_or_insert_with(Vec::new).push(route) + } else if route.is_ipv6() { + self.ipv6.get_or_insert_with(Vec::new).push(route) + } + } +} + +impl From<Vec<RouteV1>> for WickedRoutes { + fn from(routes: Vec<RouteV1>) -> Self { + let mut wicked_routes = Self::default(); + for route in routes { + let wicked_route = WickedRoute::from(route); + wicked_routes.add_route(wicked_route); + } + wicked_routes + } +}
diff --git a/sources/api/netdog/src/net_config/test_macros/mod.rs b/sources/api/netdog/src/net_config/test_macros/mod.rs index 782c7476a16..7677dfa02b6 100644 --- a/sources/api/netdog/src/net_config/test_macros/mod.rs +++ b/sources/api/netdog/src/net_config/test_macros/mod.rs @@ -15,9 +15,12 @@ pub(super) mod basic; #[cfg(test)] pub(super) mod dhcp; +#[cfg(test)] +pub(super) mod static_address; pub(super) use basic::basic_tests; pub(super) use dhcp::dhcp_tests; +pub(super) use static_address::static_address_tests; /// gen_boilerplate!() is a convenience macro meant to be used inside of test macros to generate /// some generally useful boilerplate code. It creates a `VERSION` constant in case the test diff --git a/sources/api/netdog/src/net_config/test_macros/static_address.rs b/sources/api/netdog/src/net_config/test_macros/static_address.rs new file mode 100644 index 00000000000..0ad472f470e --- /dev/null +++ b/sources/api/netdog/src/net_config/test_macros/static_address.rs @@ -0,0 +1,67 @@ +macro_rules! static_address_tests { + ($version:expr) => { + mod static_address { + use $crate::net_config::deserialize_config; + use $crate::net_config::test_macros::gen_boilerplate; + + gen_boilerplate!($version, "static_address"); + + #[test] + fn ok_config() { + let ok = net_config().join("net_config.toml"); + let rendered = render_config_template(ok); + assert!(deserialize_config(&rendered).is_ok()) + } + + #[test] + fn dhcp_and_static_addresses() { + let ok = net_config().join("dhcp_and_static.toml"); + let rendered = render_config_template(ok); + assert!(deserialize_config(&rendered).is_ok()) + } + + #[test] + fn dhcp_and_routes() { + let bad = net_config().join("dhcp_and_routes.toml"); + let rendered = render_config_template(bad); + assert!(deserialize_config(&rendered).is_err()) + } + + #[test] + fn no_dhcp_or_static() { + let bad = net_config().join("no_dhcp_or_static.toml"); + let rendered = render_config_template(bad); + assert!(deserialize_config(&rendered).is_err()) + } + + #[test] + fn routes_no_addresses() { + let bad = net_config().join("routes_no_addresses.toml"); + let rendered = render_config_template(bad); + assert!(deserialize_config(&rendered).is_err()) + } + + #[test] + fn invalid_static_config() { + let bad = net_config().join("invalid_static_config.toml"); + let rendered = render_config_template(bad); + assert!(deserialize_config(&rendered).is_err()) + } + + #[test] + fn ipv6_in_static4() { + let bad = net_config().join("ipv6_in_static4.toml"); + let rendered = render_config_template(bad); + assert!(deserialize_config(&rendered).is_err()) + } + + #[test] + fn ipv4_in_static6() { + let bad = net_config().join("ipv4_in_static6.toml"); + let rendered = render_config_template(bad); + assert!(deserialize_config(&rendered).is_err()) + } + } + }; +} +pub(crate) use static_address_tests; diff --git a/sources/api/netdog/test_data/net_config/static_address/dhcp_and_routes.toml b/sources/api/netdog/test_data/net_config/static_address/dhcp_and_routes.toml new file mode 100644 index 00000000000..bcdc644b4af --- /dev/null +++ b/sources/api/netdog/test_data/net_config/static_address/dhcp_and_routes.toml @@ -0,0 +1,11 @@ +version = {{version}} + +[eno1] +dhcp4 = true + +[eno1.static4] +addresses = ["1.2.3.4/24", "2.3.4.5/25"] + +[[eno1.route]] +to = "4.5.6.7/24" +via = "10.0.0.1" diff --git a/sources/api/netdog/test_data/net_config/static_address/dhcp_and_static.toml b/sources/api/netdog/test_data/net_config/static_address/dhcp_and_static.toml new file mode 100644 index 00000000000..4e3190de3ea --- /dev/null +++ b/sources/api/netdog/test_data/net_config/static_address/dhcp_and_static.toml @@ -0,0 +1,7 @@ +version = {{version}} + +[eno1] +dhcp4 = true + +[eno1.static4] +addresses = ["1.2.3.4/24", "2.3.4.5/25"] diff --git a/sources/api/netdog/test_data/net_config/static_address/invalid_static_config.toml b/sources/api/netdog/test_data/net_config/static_address/invalid_static_config.toml new file mode 100644 index 00000000000..03b1d693cc6 --- /dev/null +++ b/sources/api/netdog/test_data/net_config/static_address/invalid_static_config.toml @@ -0,0 +1,6 @@ +version = {{version}} + +[eno1.static4] +addresses = ["1.2.3.4/24", "2.3.4.5/25"] +# `route-metric` is not a valid static4 option +route-metric = 100 diff --git a/sources/api/netdog/test_data/net_config/static_address/ipv4_in_static6.toml b/sources/api/netdog/test_data/net_config/static_address/ipv4_in_static6.toml new file mode 100644 index 00000000000..bf84ee093fd --- /dev/null +++ b/sources/api/netdog/test_data/net_config/static_address/ipv4_in_static6.toml @@ -0,0 +1,4 @@ +version = {{version}} + +[eno1.static6] +addresses = ["1.2.3.4/24", "2.3.4.5/25", "2001:dead:beef::2/64"] diff --git a/sources/api/netdog/test_data/net_config/static_address/ipv6_in_static4.toml b/sources/api/netdog/test_data/net_config/static_address/ipv6_in_static4.toml new file mode 100644 index 00000000000..03774c6740a --- /dev/null +++ b/sources/api/netdog/test_data/net_config/static_address/ipv6_in_static4.toml @@ -0,0 +1,4 @@ +version = {{version}} + +[eno1.static4] +addresses = ["2001:dead:beef::2/64", "10.0.0.10/24"] diff --git a/sources/api/netdog/test_data/net_config/static_address/net_config.toml b/sources/api/netdog/test_data/net_config/static_address/net_config.toml new file mode 100644 index 00000000000..bf9cec7c248 --- /dev/null +++ b/sources/api/netdog/test_data/net_config/static_address/net_config.toml @@ -0,0 +1,90 @@ +version = {{version}} + +# IPv4 static addresses/routes +[eno11.static4] +addresses = ["192.168.14.2/24"] + +[eno12.static4] +addresses = ["10.0.0.9/24"] + +[[eno12.route]] +to = "10.10.10.0/24" +via = "10.0.0.1" + +[eno13.static4] +addresses = ["192.168.14.2/24"] + +[[eno13.route]] +to = "9.9.0.0/16" +via = "192.168.1.1" + +[[eno13.route]] +to = "10.10.10.0/24" +via = "192.168.1.3" + +[eno14.static4] +addresses = ["10.0.0.10/24", "11.0.0.11/24"] + +[[eno14.route]] +to = "default" +via = "10.0.0.1" +route-metric = 100 + +[[eno14.route]] +to = "default" +via = "11.0.0.1" +route-metric = 200 + +# IPv6 static addresses/routes +[eno15.static6] +addresses = ["2001:cafe:face:beef::dead:dead/64"] + +[eno16.static6] +addresses = ["2001:dead:beef::2/64"] + +[[eno16.route]] +to = "default" +via = "2001:beef:beef::1" + +[eno17.static6] +addresses = ["3001:f00f:f00f::2/64", "3001:f00f:f00f::3/64"] + +[[eno17.route]] +to = "3001:dead:beef::2/64" +via = "3001:beef:beef::1" +route-metric = 100 + +[[eno17.route]] +to = "3001:dead:feed::2/64" +via = "3001:beef:beef::2" +route-metric = 200 + +# DHCP4/6 and static addresses +[eno18] +dhcp4 = true + +[eno18.static4] +addresses = ["10.0.0.10/24", "11.0.0.11/24"] + +[eno19] +dhcp6 = true + +[eno19.static6] +addresses = ["3001:f00f:f00f::2/64", "3001:f00f:f00f::3/64"] + +# Source IP +[eno20.static4] +addresses = ["192.168.14.5/24"] + +[[eno20.route]] +to = "10.10.10.0/24" +from = "192.168.14.5" +via = "192.168.14.25" + +[eno21.static6] +addresses = ["2001:dead:beef::2/64"] + +[[eno21.route]] +to = "3001:dead:beef::2/64" +from = "2001:dead:beef::2" +via = "2001:beef:beef::1" diff --git a/sources/api/netdog/test_data/net_config/static_address/no_dhcp_or_static.toml b/sources/api/netdog/test_data/net_config/static_address/no_dhcp_or_static.toml new file mode 100644 index 00000000000..2a1c5698f18 --- /dev/null +++ b/sources/api/netdog/test_data/net_config/static_address/no_dhcp_or_static.toml @@ -0,0 +1,3 @@ +version = {{version}} + +[eno1] diff --git a/sources/api/netdog/test_data/net_config/static_address/routes_no_addresses.toml b/sources/api/netdog/test_data/net_config/static_address/routes_no_addresses.toml new file mode 100644 index 00000000000..933d0287eec --- /dev/null +++ b/sources/api/netdog/test_data/net_config/static_address/routes_no_addresses.toml @@ -0,0 +1,5 @@ +version = {{version}} + +[[eno1.route]] +to = "4.5.6.7/24" +via = "10.0.0.1" diff --git a/sources/api/netdog/test_data/wicked/eno11.xml b/sources/api/netdog/test_data/wicked/eno11.xml new file mode 100644 index 00000000000..5dbd71fb438 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno11.xml @@ -0,0 +1,1 @@ +<interface><name>eno11</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv4:static><address><local>192.168.14.2/24</local></address></ipv4:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno12.xml b/sources/api/netdog/test_data/wicked/eno12.xml new file mode 100644 index 00000000000..d8a371db5f1 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno12.xml @@ -0,0 +1,1 @@ +<interface><name>eno12</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv4:static><address><local>10.0.0.9/24</local></address><route><destination>10.10.10.0/24</destination><nexthop><gateway>10.0.0.1</gateway></nexthop></route></ipv4:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno13.xml b/sources/api/netdog/test_data/wicked/eno13.xml new file mode 100644 index 00000000000..7a1ddd018ad --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno13.xml @@ -0,0 +1,1 @@ +<interface><name>eno13</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv4:static><address><local>192.168.14.2/24</local></address><route><destination>9.9.0.0/16</destination><nexthop><gateway>192.168.1.1</gateway></nexthop></route><route><destination>10.10.10.0/24</destination><nexthop><gateway>192.168.1.3</gateway></nexthop></route></ipv4:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno14.xml b/sources/api/netdog/test_data/wicked/eno14.xml new file mode 100644 index 00000000000..28b55a50495 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno14.xml @@ -0,0 +1,1 @@ +<interface><name>eno14</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv4:static><address><local>10.0.0.10/24</local></address><address><local>11.0.0.11/24</local></address><route><destination>0.0.0.0/0</destination><nexthop><gateway>10.0.0.1</gateway></nexthop><priority>100</priority></route><route><destination>0.0.0.0/0</destination><nexthop><gateway>11.0.0.1</gateway></nexthop><priority>200</priority></route></ipv4:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno15.xml b/sources/api/netdog/test_data/wicked/eno15.xml new file mode 100644 index 00000000000..c17f0fce1df --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno15.xml @@ -0,0 +1,1 @@ +<interface><name>eno15</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv6:static><address><local>2001:cafe:face:beef::dead:dead/64</local></address></ipv6:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno16.xml b/sources/api/netdog/test_data/wicked/eno16.xml new file mode 100644 index 00000000000..76f650b2d26 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno16.xml @@ -0,0 +1,1 @@ +<interface><name>eno16</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv6:static><address><local>2001:dead:beef::2/64</local></address><route><destination>::/0</destination><nexthop><gateway>2001:beef:beef::1</gateway></nexthop></route></ipv6:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno17.xml b/sources/api/netdog/test_data/wicked/eno17.xml new file mode 100644 index 00000000000..510b690fca5 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno17.xml @@ -0,0 +1,1 @@ +<interface><name>eno17</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv6:static><address><local>3001:f00f:f00f::2/64</local></address><address><local>3001:f00f:f00f::3/64</local></address><route><destination>3001:dead:beef::2/64</destination><nexthop><gateway>3001:beef:beef::1</gateway></nexthop><priority>100</priority></route><route><destination>3001:dead:feed::2/64</destination><nexthop><gateway>3001:beef:beef::2</gateway></nexthop><priority>200</priority></route></ipv6:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno18.xml b/sources/api/netdog/test_data/wicked/eno18.xml new file mode 100644 index 00000000000..8dc6e886763 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno18.xml @@ -0,0 +1,1 @@ +<interface><name>eno18</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv4:dhcp><enabled>true</enabled></ipv4:dhcp><ipv4:static><address><local>10.0.0.10/24</local></address><address><local>11.0.0.11/24</local></address></ipv4:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno19.xml b/sources/api/netdog/test_data/wicked/eno19.xml new file mode 100644 index 00000000000..5816d3e7ab1 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno19.xml @@ -0,0 +1,1 @@ +<interface><name>eno19</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv6:dhcp><enabled>true</enabled></ipv6:dhcp><ipv6:static><address><local>3001:f00f:f00f::2/64</local></address><address><local>3001:f00f:f00f::3/64</local></address></ipv6:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno20.xml b/sources/api/netdog/test_data/wicked/eno20.xml new file mode 100644 index 00000000000..4ea7420e425 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno20.xml @@ -0,0 +1,1 @@ +<interface><name>eno20</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv4:static><address><local>192.168.14.5/24</local></address><route><destination>10.10.10.0/24</destination><pref-source>192.168.14.5</pref-source><nexthop><gateway>192.168.14.25</gateway></nexthop></route></ipv4:static></interface> diff --git a/sources/api/netdog/test_data/wicked/eno21.xml b/sources/api/netdog/test_data/wicked/eno21.xml new file mode 100644 index 00000000000..f40d0150d77 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/eno21.xml @@ -0,0 +1,1 @@ +<interface><name>eno21</name><control><mode>boot</mode><link-detection><require-link></require-link></link-detection></control><ipv6:static><address><local>2001:dead:beef::2/64</local></address><route><destination>3001:dead:beef::2/64</destination><pref-source>2001:dead:beef::2</pref-source><nexthop><gateway>2001:beef:beef::1</gateway></nexthop></route></ipv6:static></interface> diff --git a/sources/api/netdog/test_data/wicked/net_config.toml b/sources/api/netdog/test_data/wicked/net_config.toml new file mode 100644 index 00000000000..b3ad92b7452 --- /dev/null +++ b/sources/api/netdog/test_data/wicked/net_config.toml @@ -0,0 +1,141 @@ +version = {{version}} + +[eno1] +dhcp4 = true + +[eno2] +dhcp6 = true +primary = true + +[eno3] +dhcp4 = true +dhcp6 = false + +[eno4] +dhcp4 = false +dhcp6 = true + +[eno5] +dhcp4 = true +dhcp6 = true + +[eno6.dhcp4] +enabled = true +route-metric = 100 + +[eno6] +dhcp6 = false + +[eno7] +dhcp4 = true + +[eno7.dhcp6] +enabled = true +optional = true + +[eno8.dhcp4] +enabled = true +optional = true + +[eno8.dhcp6] +enabled = true +optional = true + +[eno9.dhcp4] +enabled = true +optional = true + +[eno10.dhcp6] +enabled = true +optional = true + +{{#if (eq version 2)}} +# IPv4 static addresses/routes +[eno11.static4] +addresses = ["192.168.14.2/24"] + +[eno12.static4] +addresses = ["10.0.0.9/24"] + +[[eno12.route]] +to = "10.10.10.0/24" +via = "10.0.0.1" + +[eno13.static4] +addresses = ["192.168.14.2/24"] + +[[eno13.route]] +to = "9.9.0.0/16" +via = "192.168.1.1" + +[[eno13.route]] +to = "10.10.10.0/24" +via = "192.168.1.3" + +[eno14.static4] +addresses = ["10.0.0.10/24", "11.0.0.11/24"] + +[[eno14.route]] +to = "default" +via = "10.0.0.1" +route-metric = 100 + +[[eno14.route]] +to = "default" +via = "11.0.0.1" +route-metric = 200 + +# IPv6 static addresses/routes +[eno15.static6] +addresses = ["2001:cafe:face:beef::dead:dead/64"] + +[eno16.static6] +addresses = ["2001:dead:beef::2/64"] + +[[eno16.route]] +to = "default" +via = "2001:beef:beef::1" + +[eno17.static6] +addresses = ["3001:f00f:f00f::2/64", "3001:f00f:f00f::3/64"] + +[[eno17.route]] +to = "3001:dead:beef::2/64" +via = "3001:beef:beef::1" +route-metric = 100 + +[[eno17.route]] +to = "3001:dead:feed::2/64" +via = "3001:beef:beef::2" +route-metric = 200 + +# DHCP4/6 and static addresses +[eno18] +dhcp4 = true + +[eno18.static4] +addresses = ["10.0.0.10/24", "11.0.0.11/24"] + +[eno19] +dhcp6 = true + +[eno19.static6] +addresses = ["3001:f00f:f00f::2/64", "3001:f00f:f00f::3/64"] + +# Source IP +[eno20.static4] +addresses = ["192.168.14.5/24"] + +[[eno20.route]] +to = "10.10.10.0/24" +from = "192.168.14.5" +via = "192.168.14.25" + +[eno21.static6] +addresses = ["2001:dead:beef::2/64"] + +[[eno21.route]] +to = "3001:dead:beef::2/64" +from = "2001:dead:beef::2" +via = "2001:beef:beef::1" +{{/if}}
Support static addressing via `net.toml` - Depends on #2214 **What I'd like:** I would like the ability to set up a static IP for a network interface. This means we will need to be able to set the following at the least - IPv4/6 IP - gateway - nameservers - destination IP
2022-09-20T20:38:21Z
bottlerocket-os/bottlerocket
386
bottlerocket-os__bottlerocket-386
[ "314" ]
a16dc3189f7b3b19e20e545bf95ad065b240ba7a
diff --git a/Makefile.toml b/Makefile.toml index 003acbdf10a..d4334fa1cb9 100644 --- a/Makefile.toml +++ b/Makefile.toml @@ -34,7 +34,7 @@ for ws in workspaces packages images ; do done chmod o+r -R ${CARGO_HOME} -cd ${BUILDSYS_SOURCES_DIR}/host-containers/cmd/host-ctr +cd ${BUILDSYS_SOURCES_DIR}/host-ctr/cmd/host-ctr docker run --rm \ -e GOPRIVATE='*' \ -e GOCACHE='/tmp/.cache' \ diff --git a/packages/Cargo.lock b/packages/Cargo.lock index 7c6a6856eb6..8f4a2a9688c 100644 --- a/packages/Cargo.lock +++ b/packages/Cargo.lock @@ -606,7 +606,7 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "host-containers" +name = "host-ctr" version = "0.1.0" dependencies = [ "buildsys 0.1.0", diff --git a/packages/Cargo.toml b/packages/Cargo.toml index 1841e1f5c3d..c6992d8f5c3 100644 --- a/packages/Cargo.toml +++ b/packages/Cargo.toml @@ -22,7 +22,7 @@ members = [ "golang", "growpart", "grub", - "host-containers", + "host-ctr", "iproute", "iptables", "iputils", diff --git a/packages/api/api.spec b/packages/api/api.spec index 4f5fb4e6eda..37a45157dd3 100644 --- a/packages/api/api.spec +++ b/packages/api/api.spec @@ -22,6 +22,8 @@ Source7: settings-applier.service Source8: data-store-version Source9: migrator.service Source10: api-sysusers.conf +Source11: host-containers@.service +Source12: host-containers-tmpfiles.conf BuildRequires: gcc-%{_cross_target} BuildRequires: %{_cross_os}glibc-devel BuildRequires: %{_cross_os}systemd-devel @@ -83,6 +85,12 @@ Requires: %{_cross_os}apiserver = %{version}-%{release} %description -n %{_cross_os}servicedog %{summary}. +%package -n %{_cross_os}host-containers +Summary: Manages system- and user-defined host containers +Requires: %{_cross_os}apiserver = %{version}-%{release} +%description -n %{_cross_os}host-containers +%{summary}. + %package -n %{_cross_os}storewolf Summary: Data store creator Requires: %{_cross_os}apiserver = %{version}-%{release} @@ -109,7 +117,8 @@ Summary: Commits settings from user data, defaults, and generators at boot for p in \ apiclient \ moondog netdog sundog pluto bork \ - thar-be-settings servicedog storewolf settings-committer \ + thar-be-settings servicedog host-containers \ + storewolf settings-committer \ migration/migrator ; do %cargo_build --path %{workspace_dir}/${p} @@ -128,7 +137,8 @@ install -d %{buildroot}%{_cross_bindir} for p in \ apiclient apiserver \ moondog netdog sundog pluto bork \ - thar-be-settings servicedog storewolf settings-committer \ + thar-be-settings servicedog host-containers \ + storewolf settings-committer \ migrator ; do install -p -m 0755 bin/${p} %{buildroot}%{_cross_bindir} @@ -136,7 +146,7 @@ done install -d %{buildroot}%{_cross_unitdir} install -p -m 0644 \ - %{S:1} %{S:2} %{S:3} %{S:4} %{S:5} %{S:7} %{S:9} \ + %{S:1} %{S:2} %{S:3} %{S:4} %{S:5} %{S:7} %{S:9} %{S:11} \ %{buildroot}%{_cross_unitdir} install -d %{buildroot}%{_cross_datadir}/thar @@ -150,6 +160,7 @@ done install -d %{buildroot}%{_cross_tmpfilesdir} install -p -m 0644 %{S:6} %{buildroot}%{_cross_tmpfilesdir}/migration.conf +install -p -m 0644 %{S:12} %{buildroot}%{_cross_tmpfilesdir}/host-containers.conf install -d %{buildroot}%{_cross_sysusersdir} install -p -m 0644 %{S:10} %{buildroot}%{_cross_sysusersdir}/api.conf @@ -188,6 +199,11 @@ install -p -m 0644 %{S:10} %{buildroot}%{_cross_sysusersdir}/api.conf %files -n %{_cross_os}servicedog %{_cross_bindir}/servicedog +%files -n %{_cross_os}host-containers +%{_cross_bindir}/host-containers +%{_cross_unitdir}/host-containers@.service +%{_cross_tmpfilesdir}/host-containers.conf + %files -n %{_cross_os}storewolf %{_cross_bindir}/storewolf %{_cross_unitdir}/storewolf.service diff --git a/packages/api/host-containers-tmpfiles.conf b/packages/api/host-containers-tmpfiles.conf new file mode 100644 index 00000000000..a200b7bef69 --- /dev/null +++ b/packages/api/host-containers-tmpfiles.conf @@ -0,0 +1,1 @@ +d /etc/host-containers 0755 root root - diff --git a/packages/api/host-containers@.service b/packages/api/host-containers@.service new file mode 100644 index 00000000000..993ec60cb7b --- /dev/null +++ b/packages/api/host-containers@.service @@ -0,0 +1,16 @@ +[Unit] +Description=Host container: %i +After=host-containerd.service +Requires=host-containerd.service + +[Service] +Type=simple +EnvironmentFile=/etc/host-containers/%i.env +ExecStart=/usr/bin/host-ctr -ctr-id='%i' -source='${CTR_SOURCE}' -superpowered='${CTR_SUPERPOWERED}' +Restart=always +RestartSec=10 +TimeoutStopSec=60 +KillMode=mixed + +[Install] +WantedBy=multi-user.target diff --git a/packages/host-containers/Cargo.toml b/packages/host-ctr/Cargo.toml similarity index 84% rename from packages/host-containers/Cargo.toml rename to packages/host-ctr/Cargo.toml index 0e75ce2e1b0..d3f28e97121 100644 --- a/packages/host-containers/Cargo.toml +++ b/packages/host-ctr/Cargo.toml @@ -1,12 +1,12 @@ [package] -name = "host-containers" +name = "host-ctr" version = "0.1.0" edition = "2018" publish = false build = "build.rs" [package.metadata.build-package] -source-groups = [ "host-containers" ] +source-groups = [ "host-ctr" ] [lib] path = "pkg.rs" diff --git a/packages/host-containers/build.rs b/packages/host-ctr/build.rs similarity index 100% rename from packages/host-containers/build.rs rename to packages/host-ctr/build.rs diff --git a/packages/host-containers/host-containers.spec b/packages/host-ctr/host-ctr.spec similarity index 88% rename from packages/host-containers/host-containers.spec rename to packages/host-ctr/host-ctr.spec index f87416fb92f..4e98559e95a 100644 --- a/packages/host-containers/host-containers.spec +++ b/packages/host-ctr/host-ctr.spec @@ -1,10 +1,10 @@ -%global workspace_name host-containers +%global workspace_name host-ctr %global systemd_systemdir %{_cross_libdir}/systemd/system Name: %{_cross_os}%{workspace_name} Version: 0.0 Release: 0%{?dist} -Summary: Thar host container management +Summary: Thar host container runner License: FIXME BuildRequires: gcc-%{_cross_target} BuildRequires: %{_cross_os}glibc-devel diff --git a/packages/host-containers/pkg.rs b/packages/host-ctr/pkg.rs similarity index 100% rename from packages/host-containers/pkg.rs rename to packages/host-ctr/pkg.rs diff --git a/packages/release/host-containers-systemd-unit-admin.template b/packages/release/host-containers-systemd-unit-admin.template deleted file mode 100644 index d4271812661..00000000000 --- a/packages/release/host-containers-systemd-unit-admin.template +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=Admin container -After=host-containerd.service -Requires=host-containerd.service - -[Service] -Type=simple -ExecStart=/usr/bin/host-ctr -ctr-id admin -source {{ settings.host-containers.admin.source }} {{#if settings.host-containers.admin.superpowered }}-superpowered{{/if}} -Restart=always -RestartSec=10 -TimeoutStopSec=60 -KillMode=mixed - -[Install] -WantedBy=multi-user.target diff --git a/packages/release/host-containers-systemd-unit-control.template b/packages/release/host-containers-systemd-unit-control.template deleted file mode 100644 index e3dc7c06a29..00000000000 --- a/packages/release/host-containers-systemd-unit-control.template +++ /dev/null @@ -1,15 +0,0 @@ -[Unit] -Description=Control container -After=host-containerd.service -Requires=host-containerd.service - -[Service] -Type=simple -ExecStart=/usr/bin/host-ctr -ctr-id control -source {{ settings.host-containers.control.source }} {{#if settings.host-containers.control.superpowered }}-superpowered{{/if}} -Restart=always -RestartSec=10 -TimeoutStopSec=60 -KillMode=mixed - -[Install] -WantedBy=multi-user.target diff --git a/packages/release/release.spec b/packages/release/release.spec index 05cd6aee688..fa1e3db8efe 100644 --- a/packages/release/release.spec +++ b/packages/release/release.spec @@ -16,8 +16,6 @@ Source99: release-tmpfiles.conf # FIXME What should own system-level file templates? Source200: hostname.template -Source201: host-containers-systemd-unit-admin.template -Source202: host-containers-systemd-unit-control.template Source1000: eth0.xml Source1002: configured.target @@ -55,7 +53,7 @@ Requires: %{_cross_os}signpost Requires: %{_cross_os}sundog Requires: %{_cross_os}pluto Requires: %{_cross_os}storewolf -Requires: %{_cross_os}servicedog +Requires: %{_cross_os}host-containers Requires: %{_cross_os}settings-committer Requires: %{_cross_os}systemd Requires: %{_cross_os}thar-be-settings @@ -64,7 +62,7 @@ Requires: %{_cross_os}updog Requires: %{_cross_os}util-linux Requires: %{_cross_os}preinit Requires: %{_cross_os}wicked -Requires: %{_cross_os}host-containers +Requires: %{_cross_os}host-ctr %description %{summary}. @@ -107,8 +105,6 @@ install -p -m 0644 %{S:1002} %{S:1003} %{S:1006} %{S:1007} %{S:1008} %{S:1009} % install -d %{buildroot}%{_cross_templatedir} install -p -m 0644 %{S:200} %{buildroot}%{_cross_templatedir}/hostname -install -p -m 0644 %{S:201} %{buildroot}%{_cross_templatedir}/host-containers-systemd-unit-admin -install -p -m 0644 %{S:202} %{buildroot}%{_cross_templatedir}/host-containers-systemd-unit-control %files %if %{with shell} @@ -130,7 +126,5 @@ install -p -m 0644 %{S:202} %{buildroot}%{_cross_templatedir}/host-containers-sy %{_cross_unitdir}/var-lib-thar.mount %dir %{_cross_templatedir} %{_cross_templatedir}/hostname -%{_cross_templatedir}/host-containers-systemd-unit-admin -%{_cross_templatedir}/host-containers-systemd-unit-control %changelog diff --git a/workspaces/Cargo.lock b/workspaces/Cargo.lock index fe53b8033b9..6e38c07436b 100644 --- a/workspaces/Cargo.lock +++ b/workspaces/Cargo.lock @@ -1024,6 +1024,21 @@ dependencies = [ "digest 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "host-containers" +version = "0.1.0" +dependencies = [ + "apiclient 0.1.0", + "apiserver 0.1.0", + "cargo-readme 3.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "http 0.1.18 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.101 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 1.0.40 (registry+https://github.com/rust-lang/crates.io-index)", + "snafu 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "tracing 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", + "tracing-subscriber 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "hostname" version = "0.1.5" diff --git a/workspaces/Cargo.toml b/workspaces/Cargo.toml index 6a1f7a7ca61..5b79aaf67d8 100644 --- a/workspaces/Cargo.toml +++ b/workspaces/Cargo.toml @@ -9,6 +9,7 @@ members = [ "api/sundog", "api/pluto", "api/servicedog", + "api/host-containers", "api/storewolf", "api/thar-be-settings", "api/settings-committer", diff --git a/workspaces/api/apiserver/src/model.rs b/workspaces/api/apiserver/src/model.rs index 9b2331d535e..b2d36cf0509 100644 --- a/workspaces/api/apiserver/src/model.rs +++ b/workspaces/api/apiserver/src/model.rs @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::net::Ipv4Addr; -use crate::modeled_types::ValidBase64; +use crate::modeled_types::{SingleLineString, ValidBase64}; ///// Primary user-visible settings @@ -32,7 +32,7 @@ pub struct Settings { pub updates: Option<UpdatesSettings>, #[serde(skip_serializing_if = "Option::is_none")] - pub host_containers: Option<HostContainersSettings>, + pub host_containers: Option<HashMap<SingleLineString, ContainerImage>>, #[serde(skip_serializing_if = "Option::is_none")] pub ntp: Option<NtpSettings>, @@ -82,23 +82,11 @@ pub struct UpdatesSettings { pub seed: Option<String>, } -// Settings for HostContainers, which manages the lifecycle of privileged, unorchestrated -// containers that are used for system management purposes. -#[derive(Debug, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields, rename_all = "kebab-case")] -pub struct HostContainersSettings { - #[serde(skip_serializing_if = "Option::is_none")] - pub admin: Option<ContainerImage>, - - #[serde(skip_serializing_if = "Option::is_none")] - pub control: Option<ContainerImage>, -} - #[derive(Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] pub struct ContainerImage { #[serde(skip_serializing_if = "Option::is_none")] - pub source: Option<String>, + pub source: Option<SingleLineString>, #[serde(skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, diff --git a/workspaces/api/apiserver/src/modeled_types.rs b/workspaces/api/apiserver/src/modeled_types.rs index 63776854729..23d7a7f6a86 100644 --- a/workspaces/api/apiserver/src/modeled_types.rs +++ b/workspaces/api/apiserver/src/modeled_types.rs @@ -75,7 +75,7 @@ impl fmt::Display for ValidBase64 { } #[cfg(test)] -mod test { +mod test_valid_base64 { use super::ValidBase64; #[test] @@ -92,3 +92,116 @@ mod test { assert!(serde_json::from_str::<ValidBase64>("").is_err()); } } + +// =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= =^..^= + +/// SingleLineString can only be created by deserializing from a string that contains at most one +/// line. It stores the original form and makes it accessible through standard traits. Its +/// purpose is input validation, for example in cases where you want to accept input for a +/// configuration file and want to ensure a user can't create a new line with extra configuration. +#[derive(Debug, Clone, Eq, PartialEq, Hash)] +pub struct SingleLineString { + inner: String, +} + +/// Validate line count before we accept a deserialization. +impl<'de> Deserialize<'de> for SingleLineString { + fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> + where + D: Deserializer<'de>, + { + let original = String::deserialize(deserializer)?; + + // Rust does not treat all Unicode line terminators as starting a new line, so we check for + // specific characters here, rather than just counting from lines(). + // https://en.wikipedia.org/wiki/Newline#Unicode + let line_terminators = [ + '\n', // newline (0A) + '\r', // carriage return (0D) + '\u{000B}', // vertical tab + '\u{000C}', // form feed + '\u{0085}', // next line + '\u{2028}', // line separator + '\u{2029}', // paragraph separator + ]; + if let Some(term) = original.find(&line_terminators[..]) { + Err(D::Error::custom(format!( + "Can't create SingleLineString with line terminator '{}'", + term, + ))) + } else { + Ok(SingleLineString { inner: original }) + } + } +} + +/// Serialize the original string back out. +impl Serialize for SingleLineString { + fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> + where + S: Serializer, + { + serializer.serialize_str(&self.inner) + } +} + +impl Deref for SingleLineString { + type Target = str; + fn deref(&self) -> &Self::Target { + &self.inner + } +} + +impl Borrow<String> for SingleLineString { + fn borrow(&self) -> &String { + &self.inner + } +} + +impl Borrow<str> for SingleLineString { + fn borrow(&self) -> &str { + &self.inner + } +} + +impl AsRef<str> for SingleLineString { + fn as_ref(&self) -> &str { + &self.inner + } +} + +impl fmt::Display for SingleLineString { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.inner) + } +} + +#[cfg(test)] +mod test_single_line_string { + use super::SingleLineString; + + #[test] + fn valid_single_line_string() { + assert!(serde_json::from_str::<SingleLineString>("\"\"").is_ok()); + assert!(serde_json::from_str::<SingleLineString>("\"hi\"").is_ok()); + let long_string = std::iter::repeat(" ").take(9999).collect::<String>(); + let json_long_string = format!("\"{}\"", &long_string); + assert!(serde_json::from_str::<SingleLineString>(&json_long_string).is_ok()); + } + + #[test] + fn invalid_single_line_string() { + assert!(serde_json::from_str::<SingleLineString>("\"Hello\nWorld\"").is_err()); + + assert!(serde_json::from_str::<SingleLineString>("\"\n\"").is_err()); + assert!(serde_json::from_str::<SingleLineString>("\"\r\"").is_err()); + assert!(serde_json::from_str::<SingleLineString>("\"\r\n\"").is_err()); + + assert!(serde_json::from_str::<SingleLineString>("\"\u{000B}\"").is_err()); // vertical tab + assert!(serde_json::from_str::<SingleLineString>("\"\u{000C}\"").is_err()); // form feed + assert!(serde_json::from_str::<SingleLineString>("\"\u{0085}\"").is_err()); // next line + assert!(serde_json::from_str::<SingleLineString>("\"\u{2028}\"").is_err()); // line separator + assert!(serde_json::from_str::<SingleLineString>("\"\u{2029}\"").is_err()); + // paragraph separator + } +} diff --git a/workspaces/api/host-containers/Cargo.toml b/workspaces/api/host-containers/Cargo.toml new file mode 100644 index 00000000000..ca77b3f968a --- /dev/null +++ b/workspaces/api/host-containers/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "host-containers" +version = "0.1.0" +authors = ["Tom Kirchner <tjk@amazon.com>", "Zac Mrowicki <mrowicki@amazon.com>"] +edition = "2018" +publish = false +build = "build.rs" + +[dependencies] +apiclient = { path = "../apiclient" } +apiserver = { path = "../apiserver" } +http = "0.1" +tracing = "0.1" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1" +snafu = "0.5" +tracing-subscriber = "0.1" + +[build-dependencies] +cargo-readme = "3.1" diff --git a/workspaces/api/host-containers/README.md b/workspaces/api/host-containers/README.md new file mode 100644 index 00000000000..fbdf82cc6e6 --- /dev/null +++ b/workspaces/api/host-containers/README.md @@ -0,0 +1,13 @@ +# host-containers + +Current version: 0.1.0 + +## Background + +host-containers is a tool that queries the API for the currently enabled host containers and +ensures the relevant systemd service is enabled/started or disabled/stopped for each one depending +on its 'enabled' flag. + +## Colophon + +This text was generated using [cargo-readme](https://crates.io/crates/cargo-readme), and includes the rustdoc from `src/main.rs`. \ No newline at end of file diff --git a/workspaces/api/host-containers/README.tpl b/workspaces/api/host-containers/README.tpl new file mode 100644 index 00000000000..bf207d023ff --- /dev/null +++ b/workspaces/api/host-containers/README.tpl @@ -0,0 +1,9 @@ +# {{crate}} + +Current version: {{version}} + +{{readme}} + +## Colophon + +This text was generated using [cargo-readme](https://crates.io/crates/cargo-readme), and includes the rustdoc from `src/main.rs`. diff --git a/workspaces/api/host-containers/build.rs b/workspaces/api/host-containers/build.rs new file mode 100644 index 00000000000..49828a1c42f --- /dev/null +++ b/workspaces/api/host-containers/build.rs @@ -0,0 +1,32 @@ +// Automatically generate README.md from rustdoc. + +use std::env; +use std::fs::File; +use std::io::Write; +use std::path::PathBuf; + +fn main() { + // Check for environment variable "SKIP_README". If it is set, + // skip README generation + if env::var_os("SKIP_README").is_some() { + return; + } + + let mut source = File::open("src/main.rs").unwrap(); + let mut template = File::open("README.tpl").unwrap(); + + let content = cargo_readme::generate_readme( + &PathBuf::from("."), // root + &mut source, // source + Some(&mut template), // template + // The "add x" arguments don't apply when using a template. + true, // add title + false, // add badges + false, // add license + true, // indent headings + ) + .unwrap(); + + let mut readme = File::create("README.md").unwrap(); + readme.write_all(content.as_bytes()).unwrap(); +} diff --git a/workspaces/api/host-containers/src/main.rs b/workspaces/api/host-containers/src/main.rs new file mode 100644 index 00000000000..c376623eab2 --- /dev/null +++ b/workspaces/api/host-containers/src/main.rs @@ -0,0 +1,344 @@ +/*! +# Background + +host-containers is a tool that queries the API for the currently enabled host containers and +ensures the relevant systemd service is enabled/started or disabled/stopped for each one depending +on its 'enabled' flag. +*/ + +#![deny(rust_2018_idioms)] + +use snafu::{ensure, OptionExt, ResultExt}; +use std::collections::HashMap; +use std::env; +use std::ffi::OsStr; +use std::fmt::Write; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{self, Command}; + +use apiserver::model; +use apiserver::modeled_types::SingleLineString; + +#[macro_use] +extern crate tracing; + +use tracing_subscriber::{ + filter::{EnvFilter, LevelFilter}, + FmtSubscriber, +}; + +// FIXME Get from configuration in the future +const DEFAULT_API_SOCKET: &str = "/run/api.sock"; +const API_SETTINGS_URI: &str = "/settings"; +const ENV_FILE_DIR: &str = "/etc/host-containers"; + +const SYSTEMCTL_BIN: &str = "/bin/systemctl"; + +mod error { + use http::StatusCode; + use snafu::Snafu; + use std::fmt; + use std::io; + use std::path::PathBuf; + use std::process::{Command, Output}; + + #[derive(Debug, Snafu)] + #[snafu(visibility = "pub(super)")] + pub(super) enum Error { + #[snafu(display("Error sending {} to {}: {}", method, uri, source))] + APIRequest { + method: String, + uri: String, + source: apiclient::Error, + }, + + #[snafu(display("Error {} when sending {} to {}: {}", code, method, uri, response_body))] + APIResponse { + method: String, + uri: String, + code: StatusCode, + response_body: String, + }, + + #[snafu(display( + "Error deserializing response as JSON from {} to {}: {}", + method, + uri, + source + ))] + ResponseJson { + method: &'static str, + uri: String, + source: serde_json::Error, + }, + + #[snafu(display("settings.host_containers missing in API response"))] + MissingSettings {}, + + #[snafu(display("Host containers '{}' missing field '{}'", name, field))] + MissingField { name: String, field: String }, + + #[snafu(display("Unable to create host-containers config dir {}: {}", path.display(), source))] + EnvFileDirCreate { path: PathBuf, source: io::Error }, + + #[snafu(display("Failed to build EnvironmentFile for {}: {}", name, source))] + EnvFileBuildFailed { name: String, source: fmt::Error }, + + #[snafu(display("Failed to write EnvironmentFile to {}: {}", path.display(), source))] + EnvFileWriteFailed { path: PathBuf, source: io::Error }, + + #[snafu(display("Failed to execute '{:?}': {}", command, source))] + ExecutionFailure { + command: Command, + source: std::io::Error, + }, + + #[snafu(display("Systemd command failed - stderr: {}", + std::str::from_utf8(&output.stderr).unwrap_or_else(|_| "<invalid UTF-8>")))] + SystemdCommandFailure { output: Output }, + + #[snafu(display("Failed to parse provided directive: {}", source))] + TracingDirectiveParse { + source: tracing_subscriber::filter::LevelParseError, + }, + + #[snafu(display("Failed to manage {} of {} host containers", failed, tried))] + ManageContainersFailed { failed: usize, tried: usize }, + } +} + +type Result<T> = std::result::Result<T, error::Error>; + +/// Query the API for the currently defined host containers +fn get_host_containers<P>(socket_path: P) -> Result<HashMap<SingleLineString, model::ContainerImage>> +where + P: AsRef<Path>, +{ + debug!("Querying the API for settings"); + + let method = "GET"; + let uri = API_SETTINGS_URI; + let (code, response_body) = apiclient::raw_request(&socket_path, uri, method, None) + .context(error::APIRequest { method, uri })?; + ensure!( + code.is_success(), + error::APIResponse { + method, + uri, + code, + response_body, + } + ); + + // Build a Settings struct from the response string + let settings: model::Settings = + serde_json::from_str(&response_body).context(error::ResponseJson { method, uri })?; + + settings.host_containers.context(error::MissingSettings) +} + +/// SystemdUnit stores the systemd unit being manipulated +struct SystemdUnit<'a> { + unit: &'a str, +} + +impl<'a> SystemdUnit<'a> { + fn new(unit: &'a str) -> Self { + SystemdUnit { unit } + } + + fn enable_and_start(&self) -> Result<()> { + // We enable/start units with --no-block to work around cyclic dependency issues at boot + // time. It would probably be better to give systemd more of a chance to tell us that + // something failed to start, if dependencies can be resolved in another way. + systemctl(&["enable", &self.unit, "--now", "--no-block"]) + } + + fn disable_and_stop(&self) -> Result<()> { + systemctl(&["disable", &self.unit, "--now"]) + } +} + +/// Wrapper around process::Command for systemctl that adds error checking. +fn systemctl<I, S>(args: I) -> Result<()> +where + I: IntoIterator<Item = S>, + S: AsRef<OsStr>, +{ + let mut command = Command::new(SYSTEMCTL_BIN); + command.args(args); + let output = command + .output() + .context(error::ExecutionFailure { command })?; + + trace!("stdout: {}", String::from_utf8_lossy(&output.stdout)); + trace!("stderr: {}", String::from_utf8_lossy(&output.stderr)); + + ensure!( + output.status.success(), + error::SystemdCommandFailure { output } + ); + Ok(()) +} + +/// Write out the EnvironmentFile that systemd uses to fill in arguments to host-ctr +fn write_env_file<S1, S2>(name: S1, source: S2, enabled: bool, superpowered: bool) -> Result<()> +where + S1: AsRef<str>, + S2: AsRef<str>, +{ + let name = name.as_ref(); + let filename = format!("{}.env", name); + let path = Path::new(ENV_FILE_DIR).join(filename); + + let mut output = String::new(); + writeln!(output, "CTR_SUPERPOWERED={}", superpowered) + .context(error::EnvFileBuildFailed { name })?; + writeln!(output, "CTR_SOURCE={}", source.as_ref()) + .context(error::EnvFileBuildFailed { name })?; + + writeln!( + output, + "\n# Just for reference; service is enabled or disabled by host-containers service" + ) + .context(error::EnvFileBuildFailed { name })?; + writeln!(output, "# CTR_ENABLED={}", enabled).context(error::EnvFileBuildFailed { name })?; + + fs::write(&path, output).context(error::EnvFileWriteFailed { path })?; + + Ok(()) +} + +/// Store the args we receive on the command line +struct Args { + socket_path: PathBuf, + verbosity: usize, +} + +/// Print a usage message in the event a bad arg is passed +fn usage() -> ! { + let program_name = env::args().next().unwrap_or_else(|| "program".to_string()); + eprintln!( + r"Usage: {} + [ --socket-path PATH ] + [ --verbose --verbose ... ] + + Socket path defaults to {}", + program_name, DEFAULT_API_SOCKET, + ); + process::exit(2); +} + +/// Prints a more specific message before exiting through usage(). +fn usage_msg<S: AsRef<str>>(msg: S) -> ! { + eprintln!("{}\n", msg.as_ref()); + usage(); +} + +/// Parse the args to the program and return an Args struct +fn parse_args(args: env::Args) -> Args { + let mut socket_path = None; + let mut verbosity = 3; + + let mut iter = args.skip(1); + while let Some(arg) = iter.next() { + match arg.as_ref() { + "-v" | "--verbose" => verbosity += 1, + + "--socket-path" => { + socket_path = Some( + iter.next() + .unwrap_or_else(|| usage_msg("Did not give argument to --socket-path")) + .into(), + ) + } + + _ => usage(), + } + } + + Args { + socket_path: socket_path.unwrap_or_else(|| DEFAULT_API_SOCKET.into()), + verbosity, + } +} + +fn handle_host_container<S>(name: S, image_details: &model::ContainerImage) -> Result<()> +where + S: AsRef<str>, +{ + let name = name.as_ref(); + let source = image_details.source.as_ref().context(error::MissingField { + name, + field: "source", + })?; + let enabled = image_details.enabled.context(error::MissingField { + name, + field: "enabled", + })?; + let superpowered = image_details.superpowered.context(error::MissingField { + name, + field: "superpowered", + })?; + + info!( + "Handling host container '{}' which is enabled: {}", + name, enabled + ); + + // Write the environment file needed for the systemd service to have details about this + // specific host container + write_env_file(name, source, enabled, superpowered)?; + + // Now start/stop the container according to the 'enabled' setting + let unit_name = format!("host-containers@{}.service", name); + let systemd_unit = SystemdUnit::new(&unit_name); + + if enabled { + systemd_unit.enable_and_start()?; + } else { + systemd_unit.disable_and_stop()?; + } + + Ok(()) +} + +fn main() -> Result<()> { + let args = parse_args(env::args()); + + // Start the logger + let level: LevelFilter = args + .verbosity + .to_string() + .parse() + .context(error::TracingDirectiveParse)?; + let filter = EnvFilter::from_default_env().add_directive(level.into()); + let subscriber = FmtSubscriber::builder() + .with_env_filter(filter) + .with_writer(std::io::stderr) + .finish(); + tracing::subscriber::set_global_default(subscriber).expect("setting tracing default failed"); + + info!("host-containers started"); + + let mut failed = 0usize; + let host_containers = get_host_containers(args.socket_path)?; + for (name, image_details) in host_containers.iter() { + // Continue to handle other host containers if we fail one + if let Err(e) = handle_host_container(name, image_details) { + failed += 1; + error!("Failed to handle host container '{}': {}", &name, e); + } + } + + ensure!( + failed == 0, + error::ManageContainersFailed { + failed, + tried: host_containers.len() + } + ); + + Ok(()) +} diff --git a/workspaces/api/storewolf/defaults.toml b/workspaces/api/storewolf/defaults.toml index 14264b2a22e..78d260de9a3 100644 --- a/workspaces/api/storewolf/defaults.toml +++ b/workspaces/api/storewolf/defaults.toml @@ -96,31 +96,14 @@ enabled = true source = "328549459982.dkr.ecr.us-west-2.amazonaws.com/thar-control:v0.1" superpowered = false -[services.host-containers-admin] -configuration-files = ["host-containers-systemd-unit-admin"] -restart-commands = ["/usr/bin/servicedog -s settings.host-containers.admin.enabled -u host-containers@admin.service"] - -[services.host-containers-control] -configuration-files = ["host-containers-systemd-unit-control"] -restart-commands = ["/usr/bin/servicedog -s settings.host-containers.control.enabled -u host-containers@control.service"] - -[configuration-files.host-containers-systemd-unit-admin] -path = "/etc/systemd/system/host-containers@admin.service" -template-path = "/usr/share/templates/host-containers-systemd-unit-admin" - -[configuration-files.host-containers-systemd-unit-control] -path = "/etc/systemd/system/host-containers@control.service" -template-path = "/usr/share/templates/host-containers-systemd-unit-control" - -[[metadata]] -key = "settings.host-containers.admin" -md = "affected-services" -val = ["host-containers-admin"] +[services.host-containers] +configuration-files = [] +restart-commands = ["/usr/bin/host-containers"] [[metadata]] -key = "settings.host-containers.control" +key = "settings.host-containers" md = "affected-services" -val = ["host-containers-control"] +val = ["host-containers"] # NTP diff --git a/workspaces/deny.toml b/workspaces/deny.toml index cfbbdce9c3f..122dc7286ce 100644 --- a/workspaces/deny.toml +++ b/workspaces/deny.toml @@ -33,6 +33,7 @@ skip = [ { name = "bork", licenses = [] }, { name = "data_store_version", licenses = [] }, { name = "growpart", licenses = [] }, + { name = "host-containers", licenses = [] }, { name = "laika", licenses = [] }, { name = "migration-helpers", licenses = [] }, { name = "migrator", licenses = [] }, diff --git a/workspaces/host-containers/cmd/host-ctr/.gitignore b/workspaces/host-ctr/cmd/host-ctr/.gitignore similarity index 100% rename from workspaces/host-containers/cmd/host-ctr/.gitignore rename to workspaces/host-ctr/cmd/host-ctr/.gitignore diff --git a/workspaces/host-containers/cmd/host-ctr/go.mod b/workspaces/host-ctr/cmd/host-ctr/go.mod similarity index 100% rename from workspaces/host-containers/cmd/host-ctr/go.mod rename to workspaces/host-ctr/cmd/host-ctr/go.mod diff --git a/workspaces/host-containers/cmd/host-ctr/go.sum b/workspaces/host-ctr/cmd/host-ctr/go.sum similarity index 100% rename from workspaces/host-containers/cmd/host-ctr/go.sum rename to workspaces/host-ctr/cmd/host-ctr/go.sum diff --git a/workspaces/host-containers/cmd/host-ctr/main.go b/workspaces/host-ctr/cmd/host-ctr/main.go similarity index 100% rename from workspaces/host-containers/cmd/host-ctr/main.go rename to workspaces/host-ctr/cmd/host-ctr/main.go
diff --git a/workspaces/host-containers/cmd/host-ctr/main_test.go b/workspaces/host-ctr/cmd/host-ctr/main_test.go similarity index 100% rename from workspaces/host-containers/cmd/host-ctr/main_test.go rename to workspaces/host-ctr/cmd/host-ctr/main_test.go
User defined host containers #229 implemented the initial work needed to make host containers functional. However, limitations in the current `apiserver` and `thar-be-settings` design make it a bit of effort to add additional host containers. Users should be able to easily define their own host containers. Design to follow. I imagine we will need to consider pieces of #159, #135 , and especially #10 .
2019-10-09T20:22:53Z
bottlerocket-os/bottlerocket
382
bottlerocket-os__bottlerocket-382
[ "351" ]
4360ac84b6314dfd24ab90a0c4d72888dda9e3e4
diff --git a/packages/containerd/containerd-config.toml b/packages/containerd/containerd-config-toml similarity index 77% rename from packages/containerd/containerd-config.toml rename to packages/containerd/containerd-config-toml index cd92491f484..4b62162599f 100644 --- a/packages/containerd/containerd-config.toml +++ b/packages/containerd/containerd-config-toml @@ -10,6 +10,10 @@ disabled_plugins = [ [grpc] address = "/run/containerd/containerd.sock" +[plugins."io.containerd.grpc.v1.cri"] +# Pause container image is specified here, shares the same image as kubelet's pod-infra-container-image +sandbox_image = "{{settings.kubernetes.pod-infra-container-image}}" + [plugins."io.containerd.grpc.v1.cri".containerd] default_runtime_name = "runc" diff --git a/packages/containerd/containerd.spec b/packages/containerd/containerd.spec index 1af5f5e795a..69f93d3d1cb 100644 --- a/packages/containerd/containerd.spec +++ b/packages/containerd/containerd.spec @@ -15,7 +15,7 @@ License: ASL 2.0 URL: https://%{goimport} Source0: https://%{goimport}/archive/v%{gover}/%{gorepo}-%{gover}.tar.gz Source1: containerd.service -Source2: containerd-config.toml +Source2: containerd-config-toml Source3: containerd-tmpfiles.conf BuildRequires: git BuildRequires: gcc-%{_cross_target} @@ -64,8 +64,9 @@ done install -d %{buildroot}%{_cross_unitdir} install -p -m 0644 %{S:1} %{buildroot}%{_cross_unitdir}/containerd.service +install -d %{buildroot}%{_cross_templatedir} install -d %{buildroot}%{_cross_factorydir}%{_cross_sysconfdir}/containerd -install -p -m 0644 %{S:2} %{buildroot}%{_cross_factorydir}%{_cross_sysconfdir}/containerd/config.toml +install -p -m 0644 %{S:2} %{buildroot}%{_cross_templatedir}/containerd-config-toml install -d %{buildroot}%{_cross_tmpfilesdir} install -p -m 0644 %{S:3} %{buildroot}%{_cross_tmpfilesdir}/containerd.conf @@ -78,7 +79,7 @@ install -p -m 0644 %{S:3} %{buildroot}%{_cross_tmpfilesdir}/containerd.conf %{_cross_bindir}/ctr %{_cross_unitdir}/containerd.service %dir %{_cross_factorydir}%{_cross_sysconfdir}/containerd -%{_cross_factorydir}%{_cross_sysconfdir}/containerd/config.toml +%{_cross_templatedir}/containerd-config-toml %{_cross_tmpfilesdir}/containerd.conf %changelog diff --git a/packages/kubernetes/kubelet.service b/packages/kubernetes/kubelet.service index ec050e3b35e..24578571a4c 100644 --- a/packages/kubernetes/kubelet.service +++ b/packages/kubernetes/kubelet.service @@ -8,6 +8,11 @@ Requires=containerd.service [Service] EnvironmentFile=/etc/kubernetes/kubelet/env ExecStartPre=/sbin/iptables -P FORWARD ACCEPT +# Pull the pause container image before starting `kubelet` so `containerd/cri` wouldn't have to +ExecStartPre=/usr/bin/host-ctr -source ${POD_INFRA_CONTAINER_IMAGE} \ + -pull-image-only \ + -containerd-socket /run/containerd/containerd.sock \ + -namespace k8s.io ExecStart=/usr/bin/kubelet \ --cloud-provider aws \ --config /etc/kubernetes/kubelet/config \ diff --git a/workspaces/api/storewolf/defaults.toml b/workspaces/api/storewolf/defaults.toml index b405bbde27a..f930837f20d 100644 --- a/workspaces/api/storewolf/defaults.toml +++ b/workspaces/api/storewolf/defaults.toml @@ -25,7 +25,7 @@ val = ["hostname"] # Kubernetes. [services.kubernetes] -configuration-files = ["kubelet-env", "kubelet-config", "kubelet-kubeconfig", "kubernetes-ca-crt"] +configuration-files = ["kubelet-env", "kubelet-config", "kubelet-kubeconfig", "kubernetes-ca-crt", "containerd-config-toml"] restart-commands = [] [configuration-files.kubelet-env] @@ -44,6 +44,10 @@ template-path = "/usr/share/templates/kubelet-kubeconfig" path = "/etc/kubernetes/pki/ca.crt" template-path = "/usr/share/templates/kubernetes-ca-crt" +[configuration-files.containerd-config-toml] +path = "/etc/containerd/config.toml" +template-path = "/usr/share/templates/containerd-config-toml" + [[metadata]] key = "settings.kubernetes.max-pods" md = "setting-generator" diff --git a/workspaces/host-ctr/cmd/host-ctr/main.go b/workspaces/host-ctr/cmd/host-ctr/main.go index 9553bfba698..80bac447f56 100644 --- a/workspaces/host-ctr/cmd/host-ctr/main.go +++ b/workspaces/host-ctr/cmd/host-ctr/main.go @@ -29,20 +29,29 @@ func main() { func _main() int { // Parse command-line arguments - targetCtr, source := "", "" - superpowered := false - + var ( + targetCtr string + source string + containerdSocket string + namespace string + superpowered bool + pullImageOnly bool + ) flag.StringVar(&targetCtr, "ctr-id", "", "The ID of the container to be started") flag.StringVar(&source, "source", "", "The image to be pulled") flag.BoolVar(&superpowered, "superpowered", false, "Specifies whether to launch the container in `superpowered` mode or not") + flag.BoolVar(&pullImageOnly, "pull-image-only", false, "Only pull and unpack the container image, do not start any container task") + flag.StringVar(&containerdSocket, "containerd-socket", "/run/host-containerd/containerd.sock", "Specifies the path to the containerd socket. Defaults to `/run/host-containerd/containerd.sock`") + flag.StringVar(&namespace, "namespace", "default", "Specifies the containerd namespace") flag.Parse() - if targetCtr == "" || source == "" { + if source == "" || (targetCtr == "" && !pullImageOnly) { flag.Usage() return 2 } - - ctx := namespaces.NamespaceFromEnv(context.Background()) + ctx, cancel := context.WithCancel(context.Background()) + ctx = namespaces.WithNamespace(ctx, namespace) + defer cancel() // Set up channel on which to send signal notifications. // We must use a buffered channel or risk missing the signal @@ -52,21 +61,50 @@ func _main() int { // Set up containerd client // Use host containers' containerd socket - client, err := containerd.New("/run/host-containerd/containerd.sock") + client, err := containerd.New(containerdSocket, containerd.WithDefaultNamespace(namespace)) if err != nil { - log.G(ctx).WithError(err).Error("Failed to connect to containerd") + log.G(ctx).WithError(err).WithFields(map[string]interface{}{"containerdSocket": containerdSocket, "namespace": namespace}).Error("Failed to connect to containerd") return 1 } defer client.Close() - // Clean up target container if it already exists before starting container task - if err := deleteCtrIfExists(ctx, client, targetCtr); err != nil { - return 1 + // Check if the image is from ECR, if it is, convert the image name into a resolvable reference + var ref string + match := ecrRegex.MatchString(source) + if match { + var err error + ref, err = ecrImageNameToRef(source) + if err != nil { + log.G(ctx).WithError(err).WithField("source", source) + return 1 + } } - img, err := pullImage(ctx, source, client) + img, err := pullImage(ctx, ref, client) if err != nil { - log.G(ctx).WithField("source", source).Error(err) + log.G(ctx).WithField("ref", ref).Error(err) + return 1 + } + + // If the image is from ECR, the image reference will be converted into the form of + // `"ecr.aws/" + the ARN of the image repository + label/digest`. + // We tag the image with its original image name so other services can discover this image by its original image reference. + // After the tag operation, this image should be addressable by both its original image reference and its ECR resolver resolvable reference. + if match { + // Include original tag on ECR image for other consumers. + if err := tagImage(ctx, ref, source, client); err != nil { + log.G(ctx).WithError(err).WithField("source", source).Error("Failed to tag an image with original image name") + return 1 + } + } + + // If we're only pulling and unpacking the image, we're done here + if pullImageOnly { + return 0 + } + + // Clean up target container if it already exists before starting container task + if err := deleteCtrIfExists(ctx, client, targetCtr); err != nil { return 1 } @@ -252,15 +290,7 @@ var ecrRegex = regexp.MustCompile(`(^[a-zA-Z0-9][a-zA-Z0-9-_]*)\.dkr\.ecr\.([a-z // Pulls image from specified source func pullImage(ctx context.Context, source string, client *containerd.Client) (containerd.Image, error) { - if match := ecrRegex.MatchString(source); match { - var err error - source, err = ecrImageNameToRef(source) - if err != nil { - return nil, err - } - } - - // Pull the image from ECR + // Pull the image img, err := client.Pull(ctx, source, withDynamicResolver(ctx, source), containerd.WithSchema1Conversion) @@ -275,6 +305,35 @@ func pullImage(ctx context.Context, source string, client *containerd.Client) (c return img, nil } +// Image tag logic derived from: +// https://github.com/containerd/containerd/blob/d80513ee8a6995bc7889c93e7858ddbbc51f063d/cmd/ctr/commands/images/tag.go#L67-L86 +func tagImage(ctx context.Context, imageName string, newImageName string, client *containerd.Client) error { + log.G(ctx).WithField("imageName", newImageName).Info("Tagging image") + // Retrieve image information + imageService := client.ImageService() + image, err := imageService.Get(ctx, imageName) + if err != nil { + return err + } + // Tag with new image name + image.Name = newImageName + // Attempt to create the image first + if _, err = imageService.Create(ctx, image); err != nil { + // The image already exists then delete the original and attempt to create the new one + if errdefs.IsAlreadyExists(err) { + if err = imageService.Delete(ctx, newImageName); err != nil { + return err + } + if _, err = imageService.Create(ctx, image); err != nil { + return err + } + } else { + return err + } + } + return nil +} + // Return the resolver appropriate for the specified image reference func withDynamicResolver(ctx context.Context, ref string) containerd.RemoteOpt { if !strings.HasPrefix(ref, "ecr.aws/") { @@ -293,7 +352,7 @@ func withDynamicResolver(ctx context.Context, ref string) containerd.RemoteOpt { } } -// Transform an ECR image name into a reference resolvable by the Amazon ECR Containerd Resolver +// Transform an ECR image name into a reference resolvable by the Amazon ECR containerd Resolver // e.g. ecr.aws/arn:<partition>:ecr:<region>:<account>:repository/<name>:<tag> func ecrImageNameToRef(input string) (string, error) { ref := "ecr.aws/" @@ -322,24 +381,27 @@ func ecrImageNameToRef(input string) (string, error) { } else if isGovCloudEndpoint { partition = "aws-us-gov" } - // Separate out <name>:<tag> + // Separate out <name>:<tag> for checking validity tokens := strings.Split(input, "/") - if len(tokens) != 2 { + if len(tokens) < 2 { return "", errors.New("No specified name and tag or digest") } - fullImageId := tokens[1] + fullImageId := tokens[len(tokens)-1] matchDigest, _ := regexp.MatchString(`^[a-zA-Z0-9-_]+@sha256:[A-Fa-f0-9]{64}$`, fullImageId) - matchTag, _ := regexp.MatchString(`^[a-zA-Z0-9-_]+:[a-zA-Z0-9.-_]{1,128}$`, fullImageId) + matchTag, _ := regexp.MatchString(`^[a-zA-Z0-9-_]+:[a-zA-Z0-9\.\-_]{1,128}$`, fullImageId) if !matchDigest && !matchTag { return "", errors.New("Malformed name and tag or digest") } + // Need to include the full repository path and the imageID (e.g. /eks/image-name:tag) + tokens = strings.SplitN(input, "/", 2) + fullPath := tokens[len(tokens)-1] // Build the ARN for the reference ecrARN := &arn.ARN{ Partition: partition, Service: "ecr", Region: region, AccountID: account, - Resource: "repository/" + fullImageId, + Resource: "repository/" + fullPath, } return ref + ecrARN.String(), nil }
diff --git a/workspaces/host-ctr/cmd/host-ctr/main_test.go b/workspaces/host-ctr/cmd/host-ctr/main_test.go index 199c1f358f2..f4fa5ba16eb 100644 --- a/workspaces/host-ctr/cmd/host-ctr/main_test.go +++ b/workspaces/host-ctr/cmd/host-ctr/main_test.go @@ -13,6 +13,7 @@ func TestECRImageNameToRefValid(t *testing.T) { expected string }{ {"Standard", "777777777777.dkr.ecr.us-west-2.amazonaws.com/my_image:latest", "ecr.aws/arn:aws:ecr:us-west-2:777777777777:repository/my_image:latest"}, + {"Standard: With additional repository path", "777777777777.dkr.ecr.us-west-2.amazonaws.com/foo/bar/my_image:latest", "ecr.aws/arn:aws:ecr:us-west-2:777777777777:repository/foo/bar/my_image:latest"}, {"Standard: Digests", "777777777777.dkr.ecr.us-west-2.amazonaws.com/my_image@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "ecr.aws/arn:aws:ecr:us-west-2:777777777777:repository/my_image@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, {"AWS CN partition", "777777777777.dkr.ecr.cn-north-1.amazonaws.com.cn/my_image:latest", "ecr.aws/arn:aws-cn:ecr:cn-north-1:777777777777:repository/my_image:latest"}, {"AWS Gov Cloud West", "777777777777.dkr.ecr.us-gov-west-1.amazonaws.com/my_image:latest", "ecr.aws/arn:aws-us-gov:ecr:us-gov-west-1:777777777777:repository/my_image:latest"},
kubelet: pod-infra-container-image flag does not work with containerd > Warning: For remote container runtime, --pod-infra-container-image is ignored in kubelet, which should be set in that remote runtime instead To address this, we need to: - [ ] remove this flag from kubelet unit file - [ ] drop `settings.kubernetes.pod_infra_container_image` - [ ] add `settings.containerd.sandbox_image` - [ ] convert `/etc/containerd/config.toml` and `host-containerd-config.toml` to templates - [ ] modify `pluto` to support the renamed setting
See containerd's [cri plugin config](https://github.com/containerd/cri/blob/master/docs/config.md) for the expected setting.
2019-10-08T22:57:30Z
README.md exists but content is empty.
Downloads last month
1