├── .github └── workflows │ └── code_quality.yml ├── .gitignore ├── CODE-OF-CONDUCT.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE ├── Makefile ├── README.md ├── SECURITY.md ├── build.rs ├── docs ├── krunvm-changevm.1.txt ├── krunvm-config.1.txt ├── krunvm-create.1.txt ├── krunvm-delete.1.txt ├── krunvm-list.1.txt ├── krunvm-start.1.txt └── krunvm.1.txt ├── krunvm.entitlements └── src ├── bindings.rs ├── commands ├── changevm.rs ├── config.rs ├── create.rs ├── delete.rs ├── inspect.rs ├── list.rs ├── mod.rs └── start.rs ├── main.rs └── utils.rs /.github/workflows/code_quality.yml: -------------------------------------------------------------------------------- 1 | name: Code Quality (rustfmt and clippy) 2 | on: [pull_request, create] 3 | 4 | jobs: 5 | build: 6 | if: github.event_name == 'pull_request' 7 | name: Code Quality (clippy, rustfmt) 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | rust: 12 | - stable 13 | target: 14 | - x86_64-unknown-linux-gnu 15 | steps: 16 | - name: Code checkout 17 | uses: actions/checkout@v2 18 | - name: Install Rust toolchain (${{ matrix.rust }}) 19 | uses: actions-rs/toolchain@v1 20 | with: 21 | toolchain: ${{ matrix.rust }} 22 | target: ${{ matrix.target }} 23 | override: true 24 | components: rustfmt, clippy 25 | 26 | - name: Install asciidoctor 27 | run: sudo apt-get install -y asciidoctor 28 | 29 | - name: Install additional Rust rust targets 30 | run: rustup target add aarch64-unknown-linux-gnu aarch64-apple-darwin 31 | 32 | - name: Formatting (rustfmt) 33 | run: cargo fmt -- --check 34 | 35 | - name: Clippy x86_64-unknown-linux-gnu (all features) 36 | run: cargo clippy --all-features --target x86_64-unknown-linux-gnu 37 | 38 | - name: Clippy aarch64-unknown-linux-gnu (all features) 39 | run: cargo clippy --all-features --target aarch64-unknown-linux-gnu 40 | 41 | - name: Clippy aarch64-apple-darwin (all features) 42 | run: cargo clippy --all-features --target aarch64-apple-darwin 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | target 3 | *.rs.bk 4 | *.iml 5 | .idea 6 | __pycache__ 7 | *.pyc 8 | *~ 9 | -------------------------------------------------------------------------------- /CODE-OF-CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## The krunvm Project Community Code of Conduct 2 | 3 | The krunvm Project follows the [Containers Community Code of Conduct](https://github.com/containers/common/blob/master/CODE-OF-CONDUCT.md). 4 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "anstream" 7 | version = "0.6.4" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "2ab91ebe16eb252986481c5b62f6098f3b698a45e34b5b98200cf20dd2484a44" 10 | dependencies = [ 11 | "anstyle", 12 | "anstyle-parse", 13 | "anstyle-query", 14 | "anstyle-wincon", 15 | "colorchoice", 16 | "utf8parse", 17 | ] 18 | 19 | [[package]] 20 | name = "anstyle" 21 | version = "1.0.4" 22 | source = "registry+https://github.com/rust-lang/crates.io-index" 23 | checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87" 24 | 25 | [[package]] 26 | name = "anstyle-parse" 27 | version = "0.2.2" 28 | source = "registry+https://github.com/rust-lang/crates.io-index" 29 | checksum = "317b9a89c1868f5ea6ff1d9539a69f45dffc21ce321ac1fd1160dfa48c8e2140" 30 | dependencies = [ 31 | "utf8parse", 32 | ] 33 | 34 | [[package]] 35 | name = "anstyle-query" 36 | version = "1.0.0" 37 | source = "registry+https://github.com/rust-lang/crates.io-index" 38 | checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b" 39 | dependencies = [ 40 | "windows-sys", 41 | ] 42 | 43 | [[package]] 44 | name = "anstyle-wincon" 45 | version = "3.0.1" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "f0699d10d2f4d628a98ee7b57b289abbc98ff3bad977cb3152709d4bf2330628" 48 | dependencies = [ 49 | "anstyle", 50 | "windows-sys", 51 | ] 52 | 53 | [[package]] 54 | name = "arrayref" 55 | version = "0.3.6" 56 | source = "registry+https://github.com/rust-lang/crates.io-index" 57 | checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" 58 | 59 | [[package]] 60 | name = "arrayvec" 61 | version = "0.5.2" 62 | source = "registry+https://github.com/rust-lang/crates.io-index" 63 | checksum = "23b62fc65de8e4e7f52534fb52b0f3ed04746ae267519eef2a83941e8085068b" 64 | 65 | [[package]] 66 | name = "autocfg" 67 | version = "1.0.1" 68 | source = "registry+https://github.com/rust-lang/crates.io-index" 69 | checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" 70 | 71 | [[package]] 72 | name = "base64" 73 | version = "0.13.0" 74 | source = "registry+https://github.com/rust-lang/crates.io-index" 75 | checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" 76 | 77 | [[package]] 78 | name = "bitflags" 79 | version = "2.4.0" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" 82 | 83 | [[package]] 84 | name = "blake2b_simd" 85 | version = "0.5.11" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "afa748e348ad3be8263be728124b24a24f268266f6f5d58af9d75f6a40b5c587" 88 | dependencies = [ 89 | "arrayref", 90 | "arrayvec", 91 | "constant_time_eq", 92 | ] 93 | 94 | [[package]] 95 | name = "cfg-if" 96 | version = "0.1.10" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 99 | 100 | [[package]] 101 | name = "cfg-if" 102 | version = "1.0.0" 103 | source = "registry+https://github.com/rust-lang/crates.io-index" 104 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 105 | 106 | [[package]] 107 | name = "clap" 108 | version = "4.4.6" 109 | source = "registry+https://github.com/rust-lang/crates.io-index" 110 | checksum = "d04704f56c2cde07f43e8e2c154b43f216dc5c92fc98ada720177362f953b956" 111 | dependencies = [ 112 | "clap_builder", 113 | "clap_derive", 114 | ] 115 | 116 | [[package]] 117 | name = "clap_builder" 118 | version = "4.4.6" 119 | source = "registry+https://github.com/rust-lang/crates.io-index" 120 | checksum = "0e231faeaca65ebd1ea3c737966bf858971cd38c3849107aa3ea7de90a804e45" 121 | dependencies = [ 122 | "anstream", 123 | "anstyle", 124 | "clap_lex", 125 | "strsim", 126 | ] 127 | 128 | [[package]] 129 | name = "clap_derive" 130 | version = "4.4.2" 131 | source = "registry+https://github.com/rust-lang/crates.io-index" 132 | checksum = "0862016ff20d69b84ef8247369fabf5c008a7417002411897d40ee1f4532b873" 133 | dependencies = [ 134 | "heck", 135 | "proc-macro2", 136 | "quote", 137 | "syn 2.0.38", 138 | ] 139 | 140 | [[package]] 141 | name = "clap_lex" 142 | version = "0.5.1" 143 | source = "registry+https://github.com/rust-lang/crates.io-index" 144 | checksum = "cd7cc57abe963c6d3b9d8be5b06ba7c8957a930305ca90304f24ef040aa6f961" 145 | 146 | [[package]] 147 | name = "colorchoice" 148 | version = "1.0.0" 149 | source = "registry+https://github.com/rust-lang/crates.io-index" 150 | checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7" 151 | 152 | [[package]] 153 | name = "confy" 154 | version = "0.4.0" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "2913470204e9e8498a0f31f17f90a0de801ae92c8c5ac18c49af4819e6786697" 157 | dependencies = [ 158 | "directories", 159 | "serde", 160 | "toml", 161 | ] 162 | 163 | [[package]] 164 | name = "constant_time_eq" 165 | version = "0.1.5" 166 | source = "registry+https://github.com/rust-lang/crates.io-index" 167 | checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" 168 | 169 | [[package]] 170 | name = "crossbeam-utils" 171 | version = "0.8.3" 172 | source = "registry+https://github.com/rust-lang/crates.io-index" 173 | checksum = "e7e9d99fa91428effe99c5c6d4634cdeba32b8cf784fc428a2a687f61a952c49" 174 | dependencies = [ 175 | "autocfg", 176 | "cfg-if 1.0.0", 177 | "lazy_static", 178 | ] 179 | 180 | [[package]] 181 | name = "directories" 182 | version = "2.0.2" 183 | source = "registry+https://github.com/rust-lang/crates.io-index" 184 | checksum = "551a778172a450d7fc12e629ca3b0428d00f6afa9a43da1b630d54604e97371c" 185 | dependencies = [ 186 | "cfg-if 0.1.10", 187 | "dirs-sys", 188 | ] 189 | 190 | [[package]] 191 | name = "dirs-sys" 192 | version = "0.3.5" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | checksum = "8e93d7f5705de3e49895a2b5e0b8855a1c27f080192ae9c32a6432d50741a57a" 195 | dependencies = [ 196 | "libc", 197 | "redox_users", 198 | "winapi", 199 | ] 200 | 201 | [[package]] 202 | name = "getrandom" 203 | version = "0.1.16" 204 | source = "registry+https://github.com/rust-lang/crates.io-index" 205 | checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" 206 | dependencies = [ 207 | "cfg-if 1.0.0", 208 | "libc", 209 | "wasi", 210 | ] 211 | 212 | [[package]] 213 | name = "heck" 214 | version = "0.4.1" 215 | source = "registry+https://github.com/rust-lang/crates.io-index" 216 | checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" 217 | 218 | [[package]] 219 | name = "krunvm" 220 | version = "0.2.3" 221 | dependencies = [ 222 | "clap", 223 | "confy", 224 | "libc", 225 | "nix", 226 | "serde", 227 | "serde_derive", 228 | "text_io", 229 | ] 230 | 231 | [[package]] 232 | name = "lazy_static" 233 | version = "1.4.0" 234 | source = "registry+https://github.com/rust-lang/crates.io-index" 235 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 236 | 237 | [[package]] 238 | name = "libc" 239 | version = "0.2.149" 240 | source = "registry+https://github.com/rust-lang/crates.io-index" 241 | checksum = "a08173bc88b7955d1b3145aa561539096c421ac8debde8cbc3612ec635fee29b" 242 | 243 | [[package]] 244 | name = "memoffset" 245 | version = "0.9.0" 246 | source = "registry+https://github.com/rust-lang/crates.io-index" 247 | checksum = "5a634b1c61a95585bd15607c6ab0c4e5b226e695ff2800ba0cdccddf208c406c" 248 | dependencies = [ 249 | "autocfg", 250 | ] 251 | 252 | [[package]] 253 | name = "nix" 254 | version = "0.27.1" 255 | source = "registry+https://github.com/rust-lang/crates.io-index" 256 | checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" 257 | dependencies = [ 258 | "bitflags", 259 | "cfg-if 1.0.0", 260 | "libc", 261 | "memoffset", 262 | ] 263 | 264 | [[package]] 265 | name = "proc-macro2" 266 | version = "1.0.69" 267 | source = "registry+https://github.com/rust-lang/crates.io-index" 268 | checksum = "134c189feb4956b20f6f547d2cf727d4c0fe06722b20a0eec87ed445a97f92da" 269 | dependencies = [ 270 | "unicode-ident", 271 | ] 272 | 273 | [[package]] 274 | name = "quote" 275 | version = "1.0.33" 276 | source = "registry+https://github.com/rust-lang/crates.io-index" 277 | checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" 278 | dependencies = [ 279 | "proc-macro2", 280 | ] 281 | 282 | [[package]] 283 | name = "redox_syscall" 284 | version = "0.1.57" 285 | source = "registry+https://github.com/rust-lang/crates.io-index" 286 | checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce" 287 | 288 | [[package]] 289 | name = "redox_users" 290 | version = "0.3.5" 291 | source = "registry+https://github.com/rust-lang/crates.io-index" 292 | checksum = "de0737333e7a9502c789a36d7c7fa6092a49895d4faa31ca5df163857ded2e9d" 293 | dependencies = [ 294 | "getrandom", 295 | "redox_syscall", 296 | "rust-argon2", 297 | ] 298 | 299 | [[package]] 300 | name = "rust-argon2" 301 | version = "0.8.3" 302 | source = "registry+https://github.com/rust-lang/crates.io-index" 303 | checksum = "4b18820d944b33caa75a71378964ac46f58517c92b6ae5f762636247c09e78fb" 304 | dependencies = [ 305 | "base64", 306 | "blake2b_simd", 307 | "constant_time_eq", 308 | "crossbeam-utils", 309 | ] 310 | 311 | [[package]] 312 | name = "serde" 313 | version = "1.0.124" 314 | source = "registry+https://github.com/rust-lang/crates.io-index" 315 | checksum = "bd761ff957cb2a45fbb9ab3da6512de9de55872866160b23c25f1a841e99d29f" 316 | 317 | [[package]] 318 | name = "serde_derive" 319 | version = "1.0.124" 320 | source = "registry+https://github.com/rust-lang/crates.io-index" 321 | checksum = "1800f7693e94e186f5e25a28291ae1570da908aff7d97a095dec1e56ff99069b" 322 | dependencies = [ 323 | "proc-macro2", 324 | "quote", 325 | "syn 1.0.64", 326 | ] 327 | 328 | [[package]] 329 | name = "strsim" 330 | version = "0.10.0" 331 | source = "registry+https://github.com/rust-lang/crates.io-index" 332 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 333 | 334 | [[package]] 335 | name = "syn" 336 | version = "1.0.64" 337 | source = "registry+https://github.com/rust-lang/crates.io-index" 338 | checksum = "3fd9d1e9976102a03c542daa2eff1b43f9d72306342f3f8b3ed5fb8908195d6f" 339 | dependencies = [ 340 | "proc-macro2", 341 | "quote", 342 | "unicode-xid", 343 | ] 344 | 345 | [[package]] 346 | name = "syn" 347 | version = "2.0.38" 348 | source = "registry+https://github.com/rust-lang/crates.io-index" 349 | checksum = "e96b79aaa137db8f61e26363a0c9b47d8b4ec75da28b7d1d614c2303e232408b" 350 | dependencies = [ 351 | "proc-macro2", 352 | "quote", 353 | "unicode-ident", 354 | ] 355 | 356 | [[package]] 357 | name = "text_io" 358 | version = "0.1.8" 359 | source = "registry+https://github.com/rust-lang/crates.io-index" 360 | checksum = "6cb170b4f47dc48835fbc56259c12d8963e542b05a24be2e3a1f5a6c320fd2d4" 361 | 362 | [[package]] 363 | name = "toml" 364 | version = "0.5.8" 365 | source = "registry+https://github.com/rust-lang/crates.io-index" 366 | checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" 367 | dependencies = [ 368 | "serde", 369 | ] 370 | 371 | [[package]] 372 | name = "unicode-ident" 373 | version = "1.0.12" 374 | source = "registry+https://github.com/rust-lang/crates.io-index" 375 | checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" 376 | 377 | [[package]] 378 | name = "unicode-xid" 379 | version = "0.2.1" 380 | source = "registry+https://github.com/rust-lang/crates.io-index" 381 | checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" 382 | 383 | [[package]] 384 | name = "utf8parse" 385 | version = "0.2.1" 386 | source = "registry+https://github.com/rust-lang/crates.io-index" 387 | checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a" 388 | 389 | [[package]] 390 | name = "wasi" 391 | version = "0.9.0+wasi-snapshot-preview1" 392 | source = "registry+https://github.com/rust-lang/crates.io-index" 393 | checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" 394 | 395 | [[package]] 396 | name = "winapi" 397 | version = "0.3.9" 398 | source = "registry+https://github.com/rust-lang/crates.io-index" 399 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 400 | dependencies = [ 401 | "winapi-i686-pc-windows-gnu", 402 | "winapi-x86_64-pc-windows-gnu", 403 | ] 404 | 405 | [[package]] 406 | name = "winapi-i686-pc-windows-gnu" 407 | version = "0.4.0" 408 | source = "registry+https://github.com/rust-lang/crates.io-index" 409 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 410 | 411 | [[package]] 412 | name = "winapi-x86_64-pc-windows-gnu" 413 | version = "0.4.0" 414 | source = "registry+https://github.com/rust-lang/crates.io-index" 415 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 416 | 417 | [[package]] 418 | name = "windows-sys" 419 | version = "0.48.0" 420 | source = "registry+https://github.com/rust-lang/crates.io-index" 421 | checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" 422 | dependencies = [ 423 | "windows-targets", 424 | ] 425 | 426 | [[package]] 427 | name = "windows-targets" 428 | version = "0.48.5" 429 | source = "registry+https://github.com/rust-lang/crates.io-index" 430 | checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" 431 | dependencies = [ 432 | "windows_aarch64_gnullvm", 433 | "windows_aarch64_msvc", 434 | "windows_i686_gnu", 435 | "windows_i686_msvc", 436 | "windows_x86_64_gnu", 437 | "windows_x86_64_gnullvm", 438 | "windows_x86_64_msvc", 439 | ] 440 | 441 | [[package]] 442 | name = "windows_aarch64_gnullvm" 443 | version = "0.48.5" 444 | source = "registry+https://github.com/rust-lang/crates.io-index" 445 | checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" 446 | 447 | [[package]] 448 | name = "windows_aarch64_msvc" 449 | version = "0.48.5" 450 | source = "registry+https://github.com/rust-lang/crates.io-index" 451 | checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" 452 | 453 | [[package]] 454 | name = "windows_i686_gnu" 455 | version = "0.48.5" 456 | source = "registry+https://github.com/rust-lang/crates.io-index" 457 | checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" 458 | 459 | [[package]] 460 | name = "windows_i686_msvc" 461 | version = "0.48.5" 462 | source = "registry+https://github.com/rust-lang/crates.io-index" 463 | checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" 464 | 465 | [[package]] 466 | name = "windows_x86_64_gnu" 467 | version = "0.48.5" 468 | source = "registry+https://github.com/rust-lang/crates.io-index" 469 | checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" 470 | 471 | [[package]] 472 | name = "windows_x86_64_gnullvm" 473 | version = "0.48.5" 474 | source = "registry+https://github.com/rust-lang/crates.io-index" 475 | checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" 476 | 477 | [[package]] 478 | name = "windows_x86_64_msvc" 479 | version = "0.48.5" 480 | source = "registry+https://github.com/rust-lang/crates.io-index" 481 | checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" 482 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "krunvm" 3 | version = "0.2.3" 4 | authors = ["Sergio Lopez "] 5 | description = "Create microVMs from OCI images" 6 | repository = "https://github.com/containers/krunvm" 7 | license = "Apache-2.0" 8 | edition = "2018" 9 | build = "build.rs" 10 | 11 | [dependencies] 12 | clap = {version = "4.4.6", features = ["derive"]} 13 | confy = "0.4.0" 14 | libc = "0.2.82" 15 | serde = "1.0.120" 16 | serde_derive = "1.0.120" 17 | text_io = "0.1.8" 18 | nix = {version = "0.27.1", features = ["socket", "fs"]} 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | OS = $(shell uname -s) 2 | KRUNVM_RELEASE = target/release/krunvm 3 | KRUNVM_DEBUG = target/debug/krunvm 4 | 5 | ifeq ($(PREFIX),) 6 | PREFIX := /usr/local 7 | endif 8 | 9 | .PHONY: install clean 10 | 11 | all: $(KRUNVM_RELEASE) 12 | 13 | debug: $(KRUNVM_DEBUG) 14 | 15 | $(KRUNVM_RELEASE): 16 | cargo build --release 17 | ifeq ($(OS),Darwin) 18 | codesign --entitlements krunvm.entitlements --force -s - $@ 19 | endif 20 | 21 | $(KRUNVM_DEBUG): 22 | cargo build --debug 23 | 24 | install: $(KRUNVM_RELEASE) 25 | install -d $(DESTDIR)$(PREFIX)/bin 26 | install -m 755 $(KRUNVM_RELEASE) $(DESTDIR)$(PREFIX)/bin 27 | 28 | clean: 29 | cargo clean 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # krunvm 2 | 3 | ```krunvm``` is a CLI-based utility for creating microVMs from OCI images, using [libkrun](https://github.com/containers/libkrun) and [buildah](https://github.com/containers/buildah). 4 | 5 | ## Features 6 | 7 | * Minimal footprint 8 | * Fast boot time 9 | * Zero disk image maintenance 10 | * Zero network configuration 11 | * Support for mapping host volumes into the guest 12 | * Support for exposing guest ports to the host 13 | 14 | ## Demo 15 | 16 | [![asciicast](https://asciinema.org/a/CGtTS93VsdzWwUfkY1kqVnaik.svg)](https://asciinema.org/a/CGtTS93VsdzWwUfkY1kqVnaik) 17 | 18 | ## Supported platforms 19 | 20 | - Linux/KVM on x86_64. 21 | - Linux/KVM on AArch64. 22 | - macOS/Hypervisor.framework on ARM64. 23 | 24 | ## Installation 25 | 26 | ### macOS 27 | 28 | ``` 29 | brew tap slp/krun 30 | brew install krunvm 31 | ``` 32 | 33 | ### Fedora 34 | 35 | ``` 36 | dnf copr enable -y slp/libkrunfw 37 | dnf copr enable -y slp/libkrun 38 | dnf copr enable -y slp/krunvm 39 | dnf install -y krunvm 40 | ``` 41 | 42 | ### Building from sources 43 | 44 | #### Dependencies 45 | 46 | * Rust Toolchain 47 | * [libkrun](https://github.com/containers/libkrun) 48 | * [buildah](https://github.com/containers/buildah) 49 | * [asciidoctor](https://github.com/asciidoctor/asciidoctor) 50 | 51 | #### Building 52 | 53 | ``` 54 | cargo build --release 55 | ``` 56 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | ## Security and Disclosure Information Policy for the krunvm Project 2 | 3 | The krunvm Project follows the [Security and Disclosure Information Policy](https://github.com/containers/common/blob/master/SECURITY.md) for the Containers Projects. 4 | 5 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use std::{env, fs, io, process}; 3 | 4 | const COMMANDS: [&str; 7] = [ 5 | "krunvm", 6 | "krunvm-changevm", 7 | "krunvm-create", 8 | "krunvm-config", 9 | "krunvm-delete", 10 | "krunvm-list", 11 | "krunvm-start", 12 | ]; 13 | 14 | fn main() { 15 | let outdir = match env::var_os("OUT_DIR") { 16 | Some(outdir) => outdir, 17 | None => { 18 | panic!("OUT_DIR environment variable not defined."); 19 | } 20 | }; 21 | fs::create_dir_all(&outdir).unwrap(); 22 | 23 | for command in COMMANDS { 24 | if let Err(err) = generate_man_page(&outdir, command) { 25 | panic!("failed to generate man page: {}", err); 26 | } 27 | } 28 | 29 | #[cfg(target_os = "macos")] 30 | println!("cargo:rustc-link-search=/opt/homebrew/lib"); 31 | } 32 | 33 | fn generate_man_page>(outdir: P, command: &str) -> io::Result<()> { 34 | // If asciidoctor isn't installed, fallback to asciidoc. 35 | if let Err(err) = process::Command::new("asciidoctor").output() { 36 | eprintln!("Error from running 'asciidoctor': {}", err); 37 | return Err(err); 38 | } 39 | 40 | let outdir = outdir.as_ref(); 41 | let outfile = outdir.join(format!("{}.1", command)); 42 | let cwd = env::current_dir()?; 43 | let txt_path = cwd.join("docs").join(format!("{}.1.txt", command)); 44 | 45 | let result = process::Command::new("asciidoctor") 46 | .arg("--doctype") 47 | .arg("manpage") 48 | .arg("--backend") 49 | .arg("manpage") 50 | .arg("--out-file") 51 | .arg(&outfile) 52 | .arg(&txt_path) 53 | .spawn()? 54 | .wait()?; 55 | if !result.success() { 56 | let msg = format!("'asciidoctor' failed with exit code {:?}", result.code()); 57 | return Err(io::Error::new(io::ErrorKind::Other, msg)); 58 | } 59 | Ok(()) 60 | } 61 | -------------------------------------------------------------------------------- /docs/krunvm-changevm.1.txt: -------------------------------------------------------------------------------- 1 | krunvm-changevm(1) 2 | ================== 3 | 4 | NAME 5 | ---- 6 | krunvm-changevm - Change the configuration of a microVM 7 | 8 | 9 | SYNOPSIS 10 | -------- 11 | *krunvm changevm* [_OPTIONS_] _microVM_ 12 | 13 | 14 | DESCRIPTION 15 | ----------- 16 | *krunvm changevm* changes the configuration of an existing microVM. 17 | 18 | When run without any _OPTIONS_, it displays the current configuration 19 | of the microVM. 20 | 21 | 22 | OPTIONS 23 | ------- 24 | *--remove-ports*:: 25 | Removes all port mappings. 26 | 27 | *--remote-volumes*:: 28 | Removes all volume mappings. 29 | 30 | *--cpus* _NUM_:: 31 | Changes the number of vCPUs that will be created for this microVM. 32 | 33 | *--mem* _NUM_:: 34 | Changes the amount of RAM, in MiB, that will be available to this 35 | microVM. 36 | + 37 | The memory configured for the microVM will not be reserved 38 | immediately. Instead, it will be provided as the guest demands it, and 39 | both the guest and libkrun (acting as the Virtual Machine Monitor) 40 | will attempt to return as many pages as possible to the host. 41 | 42 | *--name* _NAME_:: 43 | Assigns a new name to the microVM. 44 | 45 | *-p, --port* _HOST_PORT:GUEST_PORT_:: 46 | Exposes a port in the guest running in the microVM through a port in the host. 47 | + 48 | This option can be specified multiple times to expose as many guest 49 | ports as desired. 50 | 51 | *-v, --volume* _HOST_PATH:GUEST_PATH_:: 52 | Makes _HOST_PATH_ visible in the guest running in the microVM through _GUEST_PATH_. 53 | + 54 | This option can be specified multiple times to make more paths in the 55 | host visible in the guest. 56 | 57 | *-w, --workdir* _GUEST_PATH_:: 58 | Configures _GUEST_PATH_ as the working directory for the first 59 | binary executed in the microVM. 60 | + 61 | An empty string ("") tells krunvm to not set a working directory 62 | explicitly, letting libkrun decide which one should be set. 63 | 64 | 65 | SEE ALSO 66 | -------- 67 | *krunvm(1)*, *krunvm-create(1)* 68 | -------------------------------------------------------------------------------- /docs/krunvm-config.1.txt: -------------------------------------------------------------------------------- 1 | krunvm-config(1) 2 | ================ 3 | 4 | NAME 5 | ---- 6 | krunvm-config - Configure default values 7 | 8 | 9 | SYNOPSIS 10 | -------- 11 | *krunvm config* [_OPTIONS_] 12 | 13 | 14 | DESCRIPTION 15 | ----------- 16 | *krunvm config* configures the default values that will be used for 17 | newly created microVMs when a explicit value has not been passed to 18 | *krunvm-create(1)* 19 | 20 | When run without any _OPTIONS_ it displays the current default values. 21 | 22 | 23 | OPTIONS 24 | ------- 25 | *--cpus* _NUM_:: 26 | Sets the default number of vCPUs that will be configured for newly 27 | created microVMs. 28 | 29 | *--dns* _IP_:: 30 | Sets the default IP that will be configured as DNS for newly created 31 | microVMs. 32 | 33 | *--mem* _NUM_:: 34 | Sets the default mount of RAM, in MiB, that will be configured for 35 | newly created microVMs. 36 | 37 | 38 | SEE ALSO 39 | -------- 40 | *krunvm(1)* 41 | -------------------------------------------------------------------------------- /docs/krunvm-create.1.txt: -------------------------------------------------------------------------------- 1 | krunvm-create(1) 2 | ================ 3 | 4 | NAME 5 | ---- 6 | krunvm-create - Create a new microVM from an OCI image 7 | 8 | 9 | SYNOPSIS 10 | -------- 11 | *krunvm create* [_OPTIONS_] _IMAGE_ 12 | 13 | 14 | DESCRIPTION 15 | ----------- 16 | *krunvm create* creates a new microVM from the OCI image specified by 17 | _IMAGE_. Please refer to buildah-from(1) for information about the 18 | format supported by the _IMAGE_ argument. 19 | 20 | 21 | OPTIONS 22 | ------- 23 | *--cpus* _NUM_:: 24 | The number of vCPUs that will be created for this microVM. 25 | 26 | *--mem* _NUM_:: 27 | The amount of RAM, in MiB, that will be available to this microVM. 28 | + 29 | The memory configured for the microVM will not be reserved 30 | immediately. Instead, it will be provided as the guest demands it, and 31 | both the guest and libkrun (acting as the Virtual Machine Monitor) 32 | will attempt to return as many pages as possible to the host. 33 | 34 | *--name* _NAME_:: 35 | The name to be assigned to this microVM. 36 | 37 | *-p, --port* _HOST_PORT:GUEST_PORT_:: 38 | Exposes a port in the guest running in the microVM through a port in the host. 39 | + 40 | This option can be specified multiple times to expose as many guest 41 | ports as desired. 42 | 43 | *-v, --volume* _HOST_PATH:GUEST_PATH_:: 44 | Makes _HOST_PATH_ visible in the guest running in the microVM through _GUEST_PATH_. 45 | + 46 | This option can be specified multiple times to make more paths in the 47 | host visible in the guest. 48 | 49 | *-w, --workdir* _GUEST_PATH_:: 50 | Configures _GUEST_PATH_ as the working directory for the first 51 | binary executed in the microVM. 52 | + 53 | An empty string ("") tells krunvm to not set a working directory 54 | explicitly, letting libkrun decide which one should be set. 55 | 56 | 57 | SEE ALSO 58 | -------- 59 | *buildah(1)*, *buildah-from(1)*, *krunvm(1)*, *krunvm-changevm(1)* 60 | -------------------------------------------------------------------------------- /docs/krunvm-delete.1.txt: -------------------------------------------------------------------------------- 1 | krunvm-delete(1) 2 | ================ 3 | 4 | NAME 5 | ---- 6 | krunvm-delete - Deletes an existing microVM 7 | 8 | 9 | SYNOPSIS 10 | -------- 11 | *krunvm delete* _microVM_ 12 | 13 | 14 | DESCRIPTION 15 | ----------- 16 | *krunvm delete* deletes an existing microVM configuration and requests 17 | to buildah(1) to unmount and remove the OCI image that was backing it. 18 | 19 | 20 | SEE ALSO 21 | -------- 22 | *buildah(1)*, *krunvm(1)* 23 | -------------------------------------------------------------------------------- /docs/krunvm-list.1.txt: -------------------------------------------------------------------------------- 1 | krunvm-list(1) 2 | ============== 3 | 4 | NAME 5 | ---- 6 | krunvm-list - Lists the existing microVMs 7 | 8 | 9 | SYNOPSIS 10 | -------- 11 | *krunvm list* 12 | 13 | 14 | DESCRIPTION 15 | ----------- 16 | *krunvm list* lists the microVMs created by *krunvm-create(1)* that 17 | have not been removed by *krunvm-delete(1)*. 18 | 19 | 20 | SEE ALSO 21 | -------- 22 | *krunvm(1)*, *krunvm-create(1)*, *krunvm-delete(1)* 23 | -------------------------------------------------------------------------------- /docs/krunvm-start.1.txt: -------------------------------------------------------------------------------- 1 | krunvm-start(1) 2 | =============== 3 | 4 | NAME 5 | ---- 6 | krunvm-start - Starts an existing microVM 7 | 8 | 9 | SYNOPSIS 10 | -------- 11 | *krunvm start* [_OPTIONS_] _microVM_ [_COMMAND_] [-- ARGS] 12 | 13 | 14 | DESCRIPTION 15 | ----------- 16 | *krunvm start* starts an existing microVM created by krunvm-create(1) 17 | and attaches stdin/stdout to its virtio-console providing a seamless 18 | experience for interacting with the guest running inside it. 19 | 20 | _COMMAND_ is the first binary to be executed in the microVM. If it's 21 | not present in the command line, krunvm-start(1) lets libkrun decide 22 | which binary will be executed. 23 | 24 | Additional arguments for _COMMAND_ can be specified in the command 25 | line by appending _--_ followed by _ARGS_. 26 | 27 | 28 | OPTIONS 29 | ------- 30 | *--cpus* _NUM_:: 31 | Override the number of vCPUs configured for this microVM. 32 | 33 | *--mem* _NUM_:: 34 | Override amount of RAM, in MiB, configured for this microVM. 35 | 36 | *--env* _KEY=VALUE_:: 37 | Set environment variable to be passed to the microVM. 38 | 39 | SEE ALSO 40 | -------- 41 | *krunvm(1)*, *krunvm-create(1)*, *krunvm-changevm(1)* 42 | -------------------------------------------------------------------------------- /docs/krunvm.1.txt: -------------------------------------------------------------------------------- 1 | krunvm(1) 2 | ========= 3 | 4 | NAME 5 | ---- 6 | krunvm - Create microVMs from OCI images 7 | 8 | 9 | SYNOPSIS 10 | -------- 11 | *krunvm* [_GLOBAL_OPTIONS_] *command* 12 | 13 | 14 | DESCRIPTION 15 | ----------- 16 | krunvm is a CLI utility to create, manage and start microVMs which are 17 | generated from OCI images, providing an interface that resembles 18 | operating on conventional containers. 19 | 20 | krunvm uses buildah(1) to download the OCI image and mount it into a 21 | local directory, and libkrun to launch the microVM. 22 | 23 | The local directory where the OCI image has been mounted is used as 24 | the root filesystem for the microVM, serviced by a virtio-fs 25 | device/server bundled into libkrun. 26 | 27 | krunvm supports mounting additional local directories into the 28 | microVM and exposing ports from the guest to the host (and the 29 | networks connected to it). 30 | 31 | Networking to the guest running in the microVM is provided by 32 | libkrun's TSI (Transparent Socket Impersonation), enabling a seamless 33 | experience that doesn't require network bridges nor other explicit 34 | network configuration. 35 | 36 | 37 | GLOBAL OPTIONS 38 | -------------- 39 | *-v* _NUM_:: 40 | Sets the verbosity level, from the lowest (0) to the highest (5). 41 | 42 | 43 | COMMANDS 44 | -------- 45 | |=== 46 | |Command | Description 47 | 48 | |krunvm-changevm(1) | Change the configuration of a microVM 49 | |krunvm-config(1) | Configure global values 50 | |krunvm-create(1) | Create a new microVM 51 | |krunvm-delete(1) | Delete an existing microVM 52 | |krunvm-list(1) | List the existing microVMs 53 | |krunvm-start(1) | Start an existing microVM 54 | |=== 55 | 56 | 57 | SEE ALSO 58 | -------- 59 | *buildah(1)* 60 | -------------------------------------------------------------------------------- /krunvm.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.hypervisor 6 | 7 | com.apple.security.cs.disable-library-validationr 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /src/bindings.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use libc::{c_char, c_int}; 5 | 6 | #[link(name = "krun")] 7 | extern "C" { 8 | pub fn krun_set_log_level(level: u32) -> i32; 9 | pub fn krun_create_ctx() -> i32; 10 | pub fn krun_free_ctx(ctx: u32) -> i32; 11 | pub fn krun_set_vm_config(ctx: u32, num_vcpus: u8, ram_mib: u32) -> i32; 12 | pub fn krun_set_root(ctx: u32, root_path: *const c_char) -> i32; 13 | pub fn krun_set_mapped_volumes(ctx: u32, mapped_volumes: *const *const c_char) -> i32; 14 | pub fn krun_set_port_map(ctx: u32, port_map: *const *const c_char) -> i32; 15 | pub fn krun_set_workdir(ctx: u32, workdir_path: *const c_char) -> i32; 16 | pub fn krun_set_exec( 17 | ctx: u32, 18 | exec_path: *const c_char, 19 | argv: *const *const c_char, 20 | envp: *const *const c_char, 21 | ) -> i32; 22 | pub fn krun_set_env(ctx: u32, envp: *const *const c_char) -> i32; 23 | pub fn krun_start_enter(ctx: u32) -> i32; 24 | } 25 | -------------------------------------------------------------------------------- /src/commands/changevm.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use clap::Args; 5 | use std::collections::HashMap; 6 | 7 | use crate::utils::{path_pairs_to_hash_map, port_pairs_to_hash_map, PathPair, PortPair}; 8 | use crate::{KrunvmConfig, APP_NAME}; 9 | 10 | use super::list::printvm; 11 | 12 | /// Change the configuration of a microVM 13 | #[derive(Args, Debug)] 14 | pub struct ChangeVmCmd { 15 | /// Name of the VM to be modified 16 | name: String, 17 | 18 | /// Assign a new name to the VM 19 | #[arg(long)] 20 | new_name: Option, 21 | 22 | /// Number of vCPUs 23 | #[arg(long)] 24 | cpus: Option, 25 | 26 | /// Amount of RAM in MiB 27 | #[arg(long)] 28 | mem: Option, 29 | 30 | /// Working directory inside the microVM 31 | #[arg(short, long)] 32 | workdir: Option, 33 | 34 | /// Remove all volume mappings 35 | #[arg(long)] 36 | remove_volumes: bool, 37 | 38 | /// Volume(s) in form "host_path:guest_path" to be exposed to the guest 39 | #[arg(short, long = "volume")] 40 | volumes: Vec, 41 | 42 | /// Remove all port mappings 43 | #[arg(long)] 44 | remove_ports: bool, 45 | 46 | /// Port(s) in format "host_port:guest_port" to be exposed to the host 47 | #[arg(long = "port")] 48 | ports: Vec, 49 | } 50 | 51 | impl ChangeVmCmd { 52 | pub fn run(self, cfg: &mut KrunvmConfig) { 53 | let mut cfg_changed = false; 54 | 55 | let vmcfg = if let Some(new_name) = &self.new_name { 56 | if cfg.vmconfig_map.contains_key(new_name) { 57 | println!("A VM with name {} already exists", new_name); 58 | std::process::exit(-1); 59 | } 60 | 61 | let mut vmcfg = match cfg.vmconfig_map.remove(&self.name) { 62 | None => { 63 | println!("No VM found with name {}", &self.name); 64 | std::process::exit(-1); 65 | } 66 | Some(vmcfg) => vmcfg, 67 | }; 68 | 69 | cfg_changed = true; 70 | let name = new_name.to_string(); 71 | vmcfg.name = name.clone(); 72 | cfg.vmconfig_map.insert(name.clone(), vmcfg); 73 | cfg.vmconfig_map.get_mut(&name).unwrap() 74 | } else { 75 | match cfg.vmconfig_map.get_mut(&self.name) { 76 | None => { 77 | println!("No VM found with name {}", self.name); 78 | std::process::exit(-1); 79 | } 80 | Some(vmcfg) => vmcfg, 81 | } 82 | }; 83 | 84 | if let Some(cpus) = self.cpus { 85 | if cpus > 8 { 86 | println!("Error: the maximum number of CPUs supported is 8"); 87 | } else { 88 | vmcfg.cpus = cpus; 89 | cfg_changed = true; 90 | } 91 | } 92 | 93 | if let Some(mem) = self.mem { 94 | if mem > 16384 { 95 | println!("Error: the maximum amount of RAM supported is 16384 MiB"); 96 | } else { 97 | vmcfg.mem = mem; 98 | cfg_changed = true; 99 | } 100 | } 101 | 102 | if self.remove_volumes { 103 | vmcfg.mapped_volumes = HashMap::new(); 104 | cfg_changed = true; 105 | } else { 106 | let mapped_volumes = path_pairs_to_hash_map(self.volumes); 107 | 108 | if !mapped_volumes.is_empty() { 109 | vmcfg.mapped_volumes = mapped_volumes; 110 | cfg_changed = true; 111 | } 112 | } 113 | // TODO: don't just silently ignore --volume args when --remove_volumes is specified 114 | 115 | if self.remove_ports { 116 | vmcfg.mapped_ports = HashMap::new(); 117 | cfg_changed = true; 118 | } else { 119 | let mapped_ports = port_pairs_to_hash_map(self.ports); 120 | 121 | if !mapped_ports.is_empty() { 122 | vmcfg.mapped_ports = mapped_ports; 123 | cfg_changed = true; 124 | } 125 | } 126 | // TODO: don't just silently ignore --port args when --remove_ports is specified 127 | 128 | if let Some(workdir) = self.workdir { 129 | vmcfg.workdir = workdir.to_string(); 130 | cfg_changed = true; 131 | } 132 | 133 | println!(); 134 | printvm(vmcfg); 135 | println!(); 136 | 137 | if cfg_changed { 138 | confy::store(APP_NAME, &cfg).unwrap(); 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/commands/config.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use crate::{KrunvmConfig, APP_NAME}; 5 | use clap::Args; 6 | 7 | /// Configure global values 8 | #[derive(Args, Debug)] 9 | pub struct ConfigCmd { 10 | // Default number of vCPUs for newly created VMs 11 | #[arg(long)] 12 | cpus: Option, 13 | 14 | ///Default amount of RAM in MiB for newly created VMs 15 | #[arg(long)] 16 | mem: Option, 17 | 18 | /// DNS server to use in the microVM 19 | #[arg(long)] 20 | dns: Option, 21 | } 22 | 23 | impl ConfigCmd { 24 | pub fn run(self, cfg: &mut KrunvmConfig) { 25 | let mut cfg_changed = false; 26 | 27 | if let Some(cpus) = self.cpus { 28 | if cpus > 8 { 29 | println!("Error: the maximum number of CPUs supported is 8"); 30 | } else { 31 | cfg.default_cpus = cpus; 32 | cfg_changed = true; 33 | } 34 | } 35 | 36 | if let Some(mem) = self.mem { 37 | if mem > 16384 { 38 | println!("Error: the maximum amount of RAM supported is 16384 MiB"); 39 | } else { 40 | cfg.default_mem = mem; 41 | cfg_changed = true; 42 | } 43 | } 44 | 45 | if let Some(dns) = self.dns { 46 | cfg.default_dns = dns; 47 | cfg_changed = true; 48 | } 49 | 50 | if cfg_changed { 51 | confy::store(APP_NAME, &cfg).unwrap(); 52 | } 53 | 54 | println!("Global configuration:"); 55 | println!( 56 | "Default number of CPUs for newly created VMs: {}", 57 | cfg.default_cpus 58 | ); 59 | println!( 60 | "Default amount of RAM (MiB) for newly created VMs: {}", 61 | cfg.default_mem 62 | ); 63 | println!( 64 | "Default DNS server for newly created VMs: {}", 65 | cfg.default_dns 66 | ); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/commands/create.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use clap::Args; 5 | use std::fs; 6 | use std::io::Write; 7 | #[cfg(target_os = "macos")] 8 | use std::path::Path; 9 | use std::process::Command; 10 | 11 | use crate::utils::{ 12 | get_buildah_args, mount_container, path_pairs_to_hash_map, port_pairs_to_hash_map, 13 | umount_container, BuildahCommand, PathPair, PortPair, 14 | }; 15 | use crate::{KrunvmConfig, VmConfig, APP_NAME}; 16 | 17 | #[cfg(target_os = "macos")] 18 | const KRUNVM_ROSETTA_FILE: &str = ".krunvm-rosetta"; 19 | 20 | /// Create a new microVM 21 | #[derive(Args, Debug)] 22 | pub struct CreateCmd { 23 | /// OCI image to use as template 24 | image: String, 25 | 26 | /// Assign a name to the VM 27 | #[arg(long)] 28 | name: Option, 29 | 30 | /// Number of vCPUs 31 | #[arg(long)] 32 | cpus: Option, 33 | 34 | /// Amount of RAM in MiB 35 | #[arg(long)] 36 | mem: Option, 37 | 38 | /// DNS server to use in the microVM 39 | #[arg(long)] 40 | dns: Option, 41 | 42 | /// Working directory inside the microVM 43 | #[arg(short, long, default_value = "")] 44 | workdir: String, 45 | 46 | /// Volume(s) in form "host_path:guest_path" to be exposed to the guest 47 | #[arg(short, long = "volume")] 48 | volumes: Vec, 49 | 50 | /// Port(s) in format "host_port:guest_port" to be exposed to the host 51 | #[arg(long = "port")] 52 | ports: Vec, 53 | 54 | /// Create a x86_64 microVM even on an Aarch64 host 55 | #[arg(short, long)] 56 | #[cfg(target_os = "macos")] 57 | x86: bool, 58 | } 59 | 60 | impl CreateCmd { 61 | pub fn run(self, cfg: &mut KrunvmConfig) { 62 | #[allow(unused_mut)] 63 | let mut cpus = self.cpus.unwrap_or(cfg.default_cpus); 64 | let mem = self.mem.unwrap_or(cfg.default_mem); 65 | let dns = self.dns.unwrap_or_else(|| cfg.default_dns.clone()); 66 | let workdir = self.workdir; 67 | let mapped_volumes = path_pairs_to_hash_map(self.volumes); 68 | let mapped_ports = port_pairs_to_hash_map(self.ports); 69 | let image = self.image; 70 | let name = self.name; 71 | 72 | if let Some(ref name) = name { 73 | if name.is_empty() { 74 | println!("Invalid name for VM"); 75 | std::process::exit(-1); 76 | } 77 | if cfg.vmconfig_map.contains_key(name) { 78 | println!("A VM with this name already exists"); 79 | std::process::exit(-1); 80 | } 81 | } 82 | 83 | let mut args = get_buildah_args(cfg, BuildahCommand::From); 84 | 85 | #[cfg(target_os = "macos")] 86 | let force_x86 = self.x86; 87 | 88 | #[cfg(target_os = "macos")] 89 | if force_x86 { 90 | let home = match std::env::var("HOME") { 91 | Err(e) => { 92 | println!("Error reading \"HOME\" enviroment variable: {}", e); 93 | std::process::exit(-1); 94 | } 95 | Ok(home) => home, 96 | }; 97 | 98 | let path = format!("{}/{}", home, KRUNVM_ROSETTA_FILE); 99 | if !Path::new(&path).is_file() { 100 | println!( 101 | " 102 | To use Rosetta for Linux you need to create the file... 103 | 104 | {} 105 | 106 | ...with the contents that the \"rosetta\" binary expects to be served from 107 | its specific ioctl. 108 | 109 | For more information, please refer to this post: 110 | https://threedots.ovh/blog/2022/06/quick-look-at-rosetta-on-linux/ 111 | ", 112 | path 113 | ); 114 | std::process::exit(-1); 115 | } 116 | 117 | if cpus != 1 { 118 | println!("x86 microVMs on Aarch64 are restricted to 1 CPU"); 119 | cpus = 1; 120 | } 121 | args.push("--arch".to_string()); 122 | args.push("x86_64".to_string()); 123 | } 124 | 125 | args.push(image.to_string()); 126 | 127 | let output = match Command::new("buildah") 128 | .args(&args) 129 | .stderr(std::process::Stdio::inherit()) 130 | .output() 131 | { 132 | Ok(output) => output, 133 | Err(err) => { 134 | if err.kind() == std::io::ErrorKind::NotFound { 135 | println!("{} requires buildah to manage the OCI images, and it wasn't found on this system.", APP_NAME); 136 | } else { 137 | println!("Error executing buildah: {}", err); 138 | } 139 | std::process::exit(-1); 140 | } 141 | }; 142 | 143 | let exit_code = output.status.code().unwrap_or(-1); 144 | if exit_code != 0 { 145 | println!( 146 | "buildah returned an error: {}", 147 | std::str::from_utf8(&output.stdout).unwrap() 148 | ); 149 | std::process::exit(-1); 150 | } 151 | 152 | let container = std::str::from_utf8(&output.stdout).unwrap().trim(); 153 | let name = if let Some(name) = name { 154 | name.to_string() 155 | } else { 156 | container.to_string() 157 | }; 158 | let vmcfg = VmConfig { 159 | name: name.clone(), 160 | cpus, 161 | mem, 162 | dns: dns.to_string(), 163 | container: container.to_string(), 164 | workdir: workdir.to_string(), 165 | mapped_volumes, 166 | mapped_ports, 167 | }; 168 | 169 | let rootfs = mount_container(cfg, &vmcfg).unwrap(); 170 | export_container_config(cfg, &rootfs, &image).unwrap(); 171 | fix_resolv_conf(&rootfs, &dns).unwrap(); 172 | #[cfg(target_os = "macos")] 173 | if force_x86 { 174 | _ = fs::create_dir(format!("{}/.rosetta", rootfs)); 175 | } 176 | umount_container(cfg, &vmcfg).unwrap(); 177 | 178 | cfg.vmconfig_map.insert(name.clone(), vmcfg); 179 | confy::store(APP_NAME, cfg).unwrap(); 180 | 181 | println!("microVM created with name: {}", name); 182 | } 183 | } 184 | 185 | fn fix_resolv_conf(rootfs: &str, dns: &str) -> Result<(), std::io::Error> { 186 | let resolvconf_dir = format!("{}/etc/", rootfs); 187 | fs::create_dir_all(resolvconf_dir)?; 188 | let resolvconf = format!("{}/etc/resolv.conf", rootfs); 189 | let mut file = fs::File::create(resolvconf)?; 190 | file.write_all(b"options use-vc\nnameserver ")?; 191 | file.write_all(dns.as_bytes())?; 192 | file.write_all(b"\n")?; 193 | Ok(()) 194 | } 195 | 196 | fn export_container_config( 197 | cfg: &KrunvmConfig, 198 | rootfs: &str, 199 | image: &str, 200 | ) -> Result<(), std::io::Error> { 201 | let mut args = get_buildah_args(cfg, BuildahCommand::Inspect); 202 | args.push(image.to_string()); 203 | 204 | let output = match Command::new("buildah") 205 | .args(&args) 206 | .stderr(std::process::Stdio::inherit()) 207 | .output() 208 | { 209 | Ok(output) => output, 210 | Err(err) => { 211 | if err.kind() == std::io::ErrorKind::NotFound { 212 | println!("{} requires buildah to manage the OCI images, and it wasn't found on this system.", APP_NAME); 213 | } else { 214 | println!("Error executing buildah: {}", err); 215 | } 216 | std::process::exit(-1); 217 | } 218 | }; 219 | 220 | let exit_code = output.status.code().unwrap_or(-1); 221 | if exit_code != 0 { 222 | println!( 223 | "buildah returned an error: {}", 224 | std::str::from_utf8(&output.stdout).unwrap() 225 | ); 226 | std::process::exit(-1); 227 | } 228 | 229 | let mut file = fs::File::create(format!("{}/.krun_config.json", rootfs))?; 230 | file.write_all(&output.stdout)?; 231 | 232 | Ok(()) 233 | } 234 | -------------------------------------------------------------------------------- /src/commands/delete.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use crate::{KrunvmConfig, APP_NAME}; 5 | use clap::Args; 6 | 7 | use crate::utils::{remove_container, umount_container}; 8 | 9 | /// Delete an existing microVM 10 | #[derive(Args, Debug)] 11 | pub struct DeleteCmd { 12 | /// Name of the microVM to be deleted 13 | name: String, 14 | } 15 | 16 | impl DeleteCmd { 17 | pub fn run(self, cfg: &mut KrunvmConfig) { 18 | let vmcfg = match cfg.vmconfig_map.remove(&self.name) { 19 | None => { 20 | println!("No VM found with that name"); 21 | std::process::exit(-1); 22 | } 23 | Some(vmcfg) => vmcfg, 24 | }; 25 | 26 | umount_container(cfg, &vmcfg).unwrap(); 27 | remove_container(cfg, &vmcfg).unwrap(); 28 | 29 | confy::store(APP_NAME, &cfg).unwrap(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/commands/inspect.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use std::process::Command; 5 | 6 | use crate::{ 7 | utils::{get_buildah_args, BuildahCommand}, 8 | KrunvmConfig, 9 | }; 10 | use clap::Args; 11 | 12 | /// Run `buildah inspect` on an existing microVM 13 | #[derive(Args, Debug)] 14 | pub struct InspectCmd { 15 | /// Name of the microVM to be inspected 16 | name: String, 17 | } 18 | 19 | impl InspectCmd { 20 | pub fn run(self, cfg: &mut KrunvmConfig) { 21 | let vmcfg = match cfg.vmconfig_map.get(&self.name) { 22 | None => { 23 | println!("No VM found with that name"); 24 | std::process::exit(-1); 25 | } 26 | Some(vmcfg) => vmcfg, 27 | }; 28 | 29 | let mut args = get_buildah_args(cfg, BuildahCommand::Inspect); 30 | args.push(vmcfg.container.clone()); 31 | 32 | let output = Command::new("buildah") 33 | .args(&args) 34 | .stderr(std::process::Stdio::inherit()) 35 | .output(); 36 | 37 | if output.is_err() { 38 | println!("Failed to inspect VM"); 39 | std::process::exit(1); 40 | } 41 | 42 | let output = match String::from_utf8(output.unwrap().stdout) { 43 | Err(err) => { 44 | println!("Failed to parse `buildah inspect` output: #{err}."); 45 | std::process::exit(1); 46 | } 47 | Ok(output) => output, 48 | }; 49 | 50 | println!("{output}"); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/commands/list.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use crate::{KrunvmConfig, VmConfig}; 5 | use clap::Args; 6 | 7 | /// List microVMs 8 | #[derive(Args, Debug)] 9 | pub struct ListCmd { 10 | /// Print debug information verbosely 11 | #[arg(short)] 12 | pub debug: bool, //TODO: implement or remove this 13 | } 14 | 15 | impl ListCmd { 16 | pub fn run(self, cfg: &KrunvmConfig) { 17 | if cfg.vmconfig_map.is_empty() { 18 | println!("No microVMs found"); 19 | } else { 20 | for (_name, vm) in cfg.vmconfig_map.iter() { 21 | println!(); 22 | printvm(vm); 23 | } 24 | println!(); 25 | } 26 | } 27 | } 28 | 29 | pub fn printvm(vm: &VmConfig) { 30 | println!("{}", vm.name); 31 | println!(" CPUs: {}", vm.cpus); 32 | println!(" RAM (MiB): {}", vm.mem); 33 | println!(" DNS server: {}", vm.dns); 34 | println!(" Buildah container: {}", vm.container); 35 | println!(" Workdir: {}", vm.workdir); 36 | println!(" Mapped volumes: {:?}", vm.mapped_volumes); 37 | println!(" Mapped ports: {:?}", vm.mapped_ports); 38 | } 39 | -------------------------------------------------------------------------------- /src/commands/mod.rs: -------------------------------------------------------------------------------- 1 | mod changevm; 2 | mod config; 3 | mod create; 4 | mod delete; 5 | mod inspect; 6 | mod list; 7 | mod start; 8 | 9 | pub use changevm::ChangeVmCmd; 10 | pub use config::ConfigCmd; 11 | pub use create::CreateCmd; 12 | pub use delete::DeleteCmd; 13 | pub use inspect::InspectCmd; 14 | pub use list::ListCmd; 15 | pub use start::StartCmd; 16 | -------------------------------------------------------------------------------- /src/commands/start.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use clap::Args; 5 | use libc::c_char; 6 | use std::ffi::CString; 7 | use std::fs::File; 8 | #[cfg(target_os = "linux")] 9 | use std::io::{Error, ErrorKind}; 10 | use std::os::unix::io::AsRawFd; 11 | #[cfg(target_os = "macos")] 12 | use std::path::Path; 13 | 14 | use crate::bindings; 15 | use crate::utils::{mount_container, umount_container}; 16 | use crate::{KrunvmConfig, VmConfig}; 17 | 18 | #[derive(Args, Debug)] 19 | /// Start an existing microVM 20 | pub struct StartCmd { 21 | /// Name of the microVM 22 | name: String, 23 | 24 | /// Command to run inside the VM 25 | command: Option, 26 | 27 | /// Arguments to be passed to the command executed in the VM 28 | args: Vec, 29 | 30 | /// Number of vCPUs 31 | #[arg(long)] 32 | cpus: Option, // TODO: implement or remove this 33 | 34 | /// Amount of RAM in MiB 35 | #[arg(long)] 36 | mem: Option, // TODO: implement or remove this 37 | 38 | /// env(s) in format "key=value" to be exposed to the VM 39 | #[arg(long = "env")] 40 | envs: Option>, 41 | } 42 | 43 | impl StartCmd { 44 | pub fn run(self, cfg: &KrunvmConfig) { 45 | let vmcfg = match cfg.vmconfig_map.get(&self.name) { 46 | None => { 47 | println!("No VM found with name {}", self.name); 48 | std::process::exit(-1); 49 | } 50 | Some(vmcfg) => vmcfg, 51 | }; 52 | 53 | umount_container(cfg, vmcfg).expect("Error unmounting container"); 54 | let rootfs = mount_container(cfg, vmcfg).expect("Error mounting container"); 55 | 56 | let vm_args: Vec = if self.command.is_some() { 57 | self.args 58 | .into_iter() 59 | .map(|val| CString::new(val).unwrap()) 60 | .collect() 61 | } else { 62 | Vec::new() 63 | }; 64 | 65 | let env_pairs: Vec = if self.envs.is_some() { 66 | self.envs 67 | .unwrap() 68 | .into_iter() 69 | .map(|val| CString::new(val).unwrap()) 70 | .collect() 71 | } else { 72 | Vec::new() 73 | }; 74 | 75 | set_rlimits(); 76 | 77 | let _file = set_lock(&rootfs); 78 | 79 | unsafe { exec_vm(vmcfg, &rootfs, self.command.as_deref(), vm_args, env_pairs) }; 80 | 81 | umount_container(cfg, vmcfg).expect("Error unmounting container"); 82 | } 83 | } 84 | 85 | #[cfg(target_os = "linux")] 86 | fn map_volumes(_ctx: u32, vmcfg: &VmConfig, rootfs: &str) { 87 | for (host_path, guest_path) in vmcfg.mapped_volumes.iter() { 88 | let host_dir = CString::new(host_path.to_string()).unwrap(); 89 | let guest_dir = CString::new(format!("{}{}", rootfs, guest_path)).unwrap(); 90 | 91 | let ret = unsafe { libc::mkdir(guest_dir.as_ptr(), 0o755) }; 92 | if ret < 0 && Error::last_os_error().kind() != ErrorKind::AlreadyExists { 93 | println!("Error creating directory {:?}", guest_dir); 94 | std::process::exit(-1); 95 | } 96 | unsafe { libc::umount(guest_dir.as_ptr()) }; 97 | let ret = unsafe { 98 | libc::mount( 99 | host_dir.as_ptr(), 100 | guest_dir.as_ptr(), 101 | std::ptr::null(), 102 | libc::MS_BIND | libc::MS_REC, 103 | std::ptr::null(), 104 | ) 105 | }; 106 | if ret < 0 { 107 | println!("Error mounting volume {}", guest_path); 108 | std::process::exit(-1); 109 | } 110 | } 111 | } 112 | 113 | #[cfg(target_os = "macos")] 114 | fn map_volumes(ctx: u32, vmcfg: &VmConfig, rootfs: &str) { 115 | let mut volumes = Vec::new(); 116 | for (host_path, guest_path) in vmcfg.mapped_volumes.iter() { 117 | let full_guest = format!("{}{}", &rootfs, guest_path); 118 | let full_guest_path = Path::new(&full_guest); 119 | if !full_guest_path.exists() { 120 | std::fs::create_dir(full_guest_path) 121 | .expect("Couldn't create guest_path for mapped volume"); 122 | } 123 | let map = format!("{}:{}", host_path, guest_path); 124 | volumes.push(CString::new(map).unwrap()); 125 | } 126 | let mut vols: Vec<*const i8> = Vec::new(); 127 | for vol in volumes.iter() { 128 | vols.push(vol.as_ptr()); 129 | } 130 | vols.push(std::ptr::null()); 131 | let ret = unsafe { bindings::krun_set_mapped_volumes(ctx, vols.as_ptr()) }; 132 | if ret < 0 { 133 | println!("Error setting VM mapped volumes"); 134 | std::process::exit(-1); 135 | } 136 | } 137 | 138 | unsafe fn exec_vm( 139 | vmcfg: &VmConfig, 140 | rootfs: &str, 141 | cmd: Option<&str>, 142 | args: Vec, 143 | env_pairs: Vec, 144 | ) { 145 | //bindings::krun_set_log_level(9); 146 | 147 | let ctx = bindings::krun_create_ctx() as u32; 148 | 149 | let ret = bindings::krun_set_vm_config(ctx, vmcfg.cpus as u8, vmcfg.mem); 150 | if ret < 0 { 151 | println!("Error setting VM config"); 152 | std::process::exit(-1); 153 | } 154 | 155 | let c_rootfs = CString::new(rootfs).unwrap(); 156 | let ret = bindings::krun_set_root(ctx, c_rootfs.as_ptr()); 157 | if ret < 0 { 158 | println!("Error setting VM rootfs"); 159 | std::process::exit(-1); 160 | } 161 | 162 | map_volumes(ctx, vmcfg, rootfs); 163 | 164 | let mut ports = Vec::new(); 165 | for (host_port, guest_port) in vmcfg.mapped_ports.iter() { 166 | let map = format!("{}:{}", host_port, guest_port); 167 | ports.push(CString::new(map).unwrap()); 168 | } 169 | let mut ps: Vec<*const c_char> = Vec::new(); 170 | for port in ports.iter() { 171 | ps.push(port.as_ptr()); 172 | } 173 | ps.push(std::ptr::null()); 174 | 175 | let ret = bindings::krun_set_port_map(ctx, ps.as_ptr()); 176 | if ret < 0 { 177 | println!("Error setting VM port map"); 178 | std::process::exit(-1); 179 | } 180 | 181 | if !vmcfg.workdir.is_empty() { 182 | let c_workdir = CString::new(vmcfg.workdir.clone()).unwrap(); 183 | let ret = bindings::krun_set_workdir(ctx, c_workdir.as_ptr()); 184 | if ret < 0 { 185 | println!("Error setting VM workdir"); 186 | std::process::exit(-1); 187 | } 188 | } 189 | 190 | let hostname = CString::new(format!("HOSTNAME={}", vmcfg.name)).unwrap(); 191 | let home = CString::new("HOME=/root").unwrap(); 192 | 193 | let mut env: Vec<*const c_char> = Vec::new(); 194 | env.push(hostname.as_ptr()); 195 | env.push(home.as_ptr()); 196 | for value in env_pairs.iter() { 197 | env.push(value.as_ptr()); 198 | } 199 | env.push(std::ptr::null()); 200 | 201 | if let Some(cmd) = cmd { 202 | let mut argv: Vec<*const c_char> = Vec::new(); 203 | for a in args.iter() { 204 | argv.push(a.as_ptr()); 205 | } 206 | argv.push(std::ptr::null()); 207 | 208 | let c_cmd = CString::new(cmd).unwrap(); 209 | let ret = bindings::krun_set_exec(ctx, c_cmd.as_ptr(), argv.as_ptr(), env.as_ptr()); 210 | if ret < 0 { 211 | println!("Error setting VM config"); 212 | std::process::exit(-1); 213 | } 214 | } else { 215 | let ret = bindings::krun_set_env(ctx, env.as_ptr()); 216 | if ret < 0 { 217 | println!("Error setting VM environment variables"); 218 | std::process::exit(-1); 219 | } 220 | } 221 | 222 | let ret = bindings::krun_start_enter(ctx); 223 | if ret < 0 { 224 | println!("Error starting VM"); 225 | std::process::exit(-1); 226 | } 227 | } 228 | 229 | fn set_rlimits() { 230 | let mut limit = libc::rlimit { 231 | rlim_cur: 0, 232 | rlim_max: 0, 233 | }; 234 | 235 | let ret = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &mut limit) }; 236 | if ret < 0 { 237 | panic!("Couldn't get RLIMIT_NOFILE value"); 238 | } 239 | 240 | limit.rlim_cur = limit.rlim_max; 241 | let ret = unsafe { libc::setrlimit(libc::RLIMIT_NOFILE, &limit) }; 242 | if ret < 0 { 243 | panic!("Couldn't set RLIMIT_NOFILE value"); 244 | } 245 | } 246 | 247 | fn set_lock(rootfs: &str) -> File { 248 | let lock_path = format!("{}/.krunvm.lock", rootfs); 249 | let file = File::create(lock_path).expect("Couldn't create lock file"); 250 | 251 | let ret = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; 252 | if ret < 0 { 253 | println!("Couldn't acquire lock file. Is another instance of this VM already running?"); 254 | std::process::exit(-1); 255 | } 256 | 257 | file 258 | } 259 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use std::collections::HashMap; 5 | #[cfg(target_os = "macos")] 6 | use std::fs::File; 7 | #[cfg(target_os = "macos")] 8 | use std::io::{self, Read, Write}; 9 | 10 | use crate::commands::{ 11 | ChangeVmCmd, ConfigCmd, CreateCmd, DeleteCmd, InspectCmd, ListCmd, StartCmd, 12 | }; 13 | use clap::{Parser, Subcommand}; 14 | use serde_derive::{Deserialize, Serialize}; 15 | #[cfg(target_os = "macos")] 16 | use text_io::read; 17 | 18 | #[allow(unused)] 19 | mod bindings; 20 | mod commands; 21 | mod utils; 22 | 23 | const APP_NAME: &str = "krunvm"; 24 | 25 | #[derive(Default, Debug, Serialize, Deserialize)] 26 | pub struct VmConfig { 27 | name: String, 28 | cpus: u32, 29 | mem: u32, 30 | container: String, 31 | workdir: String, 32 | dns: String, 33 | mapped_volumes: HashMap, 34 | mapped_ports: HashMap, 35 | } 36 | 37 | #[derive(Debug, Serialize, Deserialize)] 38 | pub struct KrunvmConfig { 39 | version: u8, 40 | default_cpus: u32, 41 | default_mem: u32, 42 | default_dns: String, 43 | storage_volume: String, 44 | vmconfig_map: HashMap, 45 | } 46 | 47 | impl Default for KrunvmConfig { 48 | fn default() -> KrunvmConfig { 49 | KrunvmConfig { 50 | version: 1, 51 | default_cpus: 2, 52 | default_mem: 1024, 53 | default_dns: "1.1.1.1".to_string(), 54 | storage_volume: String::new(), 55 | vmconfig_map: HashMap::new(), 56 | } 57 | } 58 | } 59 | 60 | #[cfg(target_os = "macos")] 61 | fn check_case_sensitivity(volume: &str) -> Result { 62 | let first_path = format!("{}/krunvm_test", volume); 63 | let second_path = format!("{}/krunVM_test", volume); 64 | { 65 | let mut first = File::create(&first_path)?; 66 | first.write_all(b"first")?; 67 | } 68 | { 69 | let mut second = File::create(&second_path)?; 70 | second.write_all(b"second")?; 71 | } 72 | let mut data = String::new(); 73 | { 74 | let mut test = File::open(&first_path)?; 75 | 76 | test.read_to_string(&mut data)?; 77 | } 78 | if data == "first" { 79 | let _ = std::fs::remove_file(first_path); 80 | let _ = std::fs::remove_file(second_path); 81 | Ok(true) 82 | } else { 83 | let _ = std::fs::remove_file(first_path); 84 | Ok(false) 85 | } 86 | } 87 | 88 | #[cfg(target_os = "macos")] 89 | fn check_volume(cfg: &mut KrunvmConfig) { 90 | if !cfg.storage_volume.is_empty() { 91 | return; 92 | } 93 | 94 | println!( 95 | " 96 | On macOS, krunvm requires a dedicated, case-sensitive volume. 97 | You can easily create such volume by executing something like 98 | this on another terminal: 99 | 100 | diskutil apfs addVolume disk3 \"Case-sensitive APFS\" krunvm 101 | 102 | NOTE: APFS volume creation is a non-destructive action that 103 | doesn't require a dedicated disk nor \"sudo\" privileges. The 104 | new volume will share the disk space with the main container 105 | volume. 106 | " 107 | ); 108 | loop { 109 | print!("Please enter the mountpoint for this volume [/Volumes/krunvm]: "); 110 | io::stdout().flush().unwrap(); 111 | let answer: String = read!("{}\n"); 112 | 113 | let volume = if answer.is_empty() { 114 | "/Volumes/krunvm".to_string() 115 | } else { 116 | answer.to_string() 117 | }; 118 | 119 | print!("Checking volume... "); 120 | match check_case_sensitivity(&volume) { 121 | Ok(res) => { 122 | if res { 123 | println!("success."); 124 | println!("The volume has been configured. Please execute krunvm again"); 125 | cfg.storage_volume = volume; 126 | confy::store(APP_NAME, cfg).unwrap(); 127 | std::process::exit(-1); 128 | } else { 129 | println!("failed."); 130 | println!("This volume failed the case sensitivity test."); 131 | } 132 | } 133 | Err(err) => { 134 | println!("error."); 135 | println!("There was an error running the test: {}", err); 136 | } 137 | } 138 | } 139 | } 140 | 141 | #[cfg(target_os = "linux")] 142 | fn check_unshare() { 143 | let uid = unsafe { libc::getuid() }; 144 | if uid != 0 && !std::env::vars().any(|(key, _)| key == "BUILDAH_ISOLATION") { 145 | println!("Please re-run krunvm inside a \"buildah unshare\" session"); 146 | std::process::exit(-1); 147 | } 148 | } 149 | 150 | #[derive(Parser, Debug)] 151 | #[command(author, version, about)] 152 | struct Cli { 153 | /// Sets the level of verbosity 154 | #[arg(short)] 155 | verbosity: Option, //TODO: implement or remove this 156 | #[command(subcommand)] 157 | command: Command, 158 | } 159 | 160 | #[derive(Subcommand, Debug)] 161 | enum Command { 162 | Start(StartCmd), 163 | Create(CreateCmd), 164 | Inspect(InspectCmd), 165 | List(ListCmd), 166 | Delete(DeleteCmd), 167 | #[command(name = "changevm")] 168 | ChangeVm(ChangeVmCmd), 169 | Config(ConfigCmd), 170 | } 171 | 172 | fn main() { 173 | let mut cfg: KrunvmConfig = confy::load(APP_NAME).unwrap(); 174 | let cli_args = Cli::parse(); 175 | 176 | #[cfg(target_os = "macos")] 177 | check_volume(&mut cfg); 178 | #[cfg(target_os = "linux")] 179 | check_unshare(); 180 | 181 | match cli_args.command { 182 | Command::Inspect(cmd) => cmd.run(&mut cfg), 183 | Command::Start(cmd) => cmd.run(&cfg), 184 | Command::Create(cmd) => cmd.run(&mut cfg), 185 | Command::List(cmd) => cmd.run(&cfg), 186 | Command::Delete(cmd) => cmd.run(&mut cfg), 187 | Command::ChangeVm(cmd) => cmd.run(&mut cfg), 188 | Command::Config(cmd) => cmd.run(&mut cfg), 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Red Hat, Inc. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | use std::collections::HashMap; 5 | use std::path::Path; 6 | use std::process::Command; 7 | use std::str::FromStr; 8 | 9 | use crate::{KrunvmConfig, VmConfig, APP_NAME}; 10 | 11 | pub enum BuildahCommand { 12 | From, 13 | Inspect, 14 | Mount, 15 | Unmount, 16 | Remove, 17 | } 18 | 19 | #[cfg(target_os = "linux")] 20 | pub fn get_buildah_args(_cfg: &KrunvmConfig, cmd: BuildahCommand) -> Vec { 21 | match cmd { 22 | BuildahCommand::From => vec!["from".to_string()], 23 | BuildahCommand::Inspect => vec!["inspect".to_string()], 24 | BuildahCommand::Mount => vec!["mount".to_string()], 25 | BuildahCommand::Unmount => vec!["umount".to_string()], 26 | BuildahCommand::Remove => vec!["rm".to_string()], 27 | } 28 | } 29 | 30 | #[cfg(target_os = "macos")] 31 | pub fn get_buildah_args(cfg: &KrunvmConfig, cmd: BuildahCommand) -> Vec { 32 | let mut hbpath = std::env::current_exe().unwrap(); 33 | hbpath.pop(); 34 | hbpath.pop(); 35 | let hbpath = hbpath.as_path().display(); 36 | let policy_json = format!("{}/etc/containers/policy.json", hbpath); 37 | let registries_json = format!("{}/etc/containers/registries.conf", hbpath); 38 | let storage_root = format!("{}/root", cfg.storage_volume); 39 | let storage_runroot = format!("{}/runroot", cfg.storage_volume); 40 | 41 | let mut args = vec![ 42 | "--root".to_string(), 43 | storage_root, 44 | "--runroot".to_string(), 45 | storage_runroot, 46 | ]; 47 | 48 | match cmd { 49 | BuildahCommand::From => { 50 | args.push("--signature-policy".to_string()); 51 | args.push(policy_json); 52 | args.push("--registries-conf".to_string()); 53 | args.push(registries_json); 54 | 55 | args.push("from".to_string()); 56 | args.push("--os".to_string()); 57 | args.push("linux".to_string()); 58 | } 59 | BuildahCommand::Inspect => { 60 | args.push("inspect".to_string()); 61 | } 62 | BuildahCommand::Mount => { 63 | args.push("mount".to_string()); 64 | } 65 | BuildahCommand::Unmount => { 66 | args.push("umount".to_string()); 67 | } 68 | BuildahCommand::Remove => { 69 | args.push("rm".to_string()); 70 | } 71 | } 72 | args 73 | } 74 | 75 | #[derive(Debug, Clone)] 76 | pub struct PortPair { 77 | pub host_port: String, 78 | pub guest_port: String, 79 | } 80 | 81 | pub fn port_pairs_to_hash_map( 82 | port_pairs: impl IntoIterator, 83 | ) -> HashMap { 84 | port_pairs 85 | .into_iter() 86 | .map(|pair: PortPair| (pair.host_port, pair.guest_port)) 87 | .collect() 88 | } 89 | 90 | impl FromStr for PortPair { 91 | type Err = &'static str; 92 | 93 | fn from_str(input: &str) -> Result { 94 | let vtuple: Vec<&str> = input.split(':').collect(); 95 | if vtuple.len() != 2 { 96 | return Err("Too many ':' separators"); 97 | } 98 | let host_port: u16 = match vtuple[0].parse() { 99 | Ok(p) => p, 100 | Err(_) => { 101 | return Err("Invalid host port"); 102 | } 103 | }; 104 | let guest_port: u16 = match vtuple[1].parse() { 105 | Ok(p) => p, 106 | Err(_) => { 107 | return Err("Invalid guest port"); 108 | } 109 | }; 110 | Ok(PortPair { 111 | host_port: host_port.to_string(), 112 | guest_port: guest_port.to_string(), 113 | }) 114 | } 115 | } 116 | 117 | #[derive(Debug, Clone)] 118 | pub struct PathPair { 119 | pub host_path: String, 120 | pub guest_path: String, 121 | } 122 | 123 | pub fn path_pairs_to_hash_map( 124 | volume_pairs: impl IntoIterator, 125 | ) -> HashMap { 126 | volume_pairs 127 | .into_iter() 128 | .map(|pair: PathPair| (pair.host_path, pair.guest_path)) 129 | .collect() 130 | } 131 | 132 | impl FromStr for PathPair { 133 | type Err = &'static str; 134 | 135 | fn from_str(input: &str) -> Result { 136 | let vtuple: Vec<&str> = input.split(':').collect(); 137 | if vtuple.len() != 2 { 138 | return Err("Too many ':' separators"); 139 | } 140 | 141 | let host_path = Path::new(vtuple[0]); 142 | if !host_path.is_absolute() { 143 | return Err("Invalid volume, host_path is not an absolute path"); 144 | } 145 | if !host_path.exists() { 146 | return Err("Invalid volume, host_path does not exists"); 147 | } 148 | let guest_path = Path::new(vtuple[1]); 149 | if !guest_path.is_absolute() { 150 | return Err("Invalid volume, guest_path is not an absolute path"); 151 | } 152 | if guest_path.components().count() != 2 { 153 | return Err( 154 | "Invalid volume, only single direct root children are supported as guest_path", 155 | ); 156 | } 157 | Ok(Self { 158 | host_path: vtuple[0].to_string(), 159 | guest_path: vtuple[1].to_string(), 160 | }) 161 | } 162 | } 163 | 164 | #[cfg(target_os = "macos")] 165 | fn fix_root_mode(rootfs: &str) { 166 | let mut args = vec!["-w", "user.containers.override_stat", "0:0:0555"]; 167 | args.push(rootfs); 168 | 169 | let output = match Command::new("xattr") 170 | .args(&args) 171 | .stderr(std::process::Stdio::inherit()) 172 | .output() 173 | { 174 | Ok(output) => output, 175 | Err(err) => { 176 | if err.kind() == std::io::ErrorKind::NotFound { 177 | println!("{} requires xattr to manage the OCI images, and it wasn't found on this system.", APP_NAME); 178 | } else { 179 | println!("Error executing xattr: {}", err); 180 | } 181 | std::process::exit(-1); 182 | } 183 | }; 184 | 185 | let exit_code = output.status.code().unwrap_or(-1); 186 | if exit_code != 0 { 187 | println!("xattr returned an error: {}", exit_code); 188 | std::process::exit(-1); 189 | } 190 | } 191 | 192 | #[allow(unused_variables)] 193 | pub fn mount_container(cfg: &KrunvmConfig, vmcfg: &VmConfig) -> Result { 194 | let mut args = get_buildah_args(cfg, BuildahCommand::Mount); 195 | args.push(vmcfg.container.clone()); 196 | 197 | let output = match Command::new("buildah") 198 | .args(&args) 199 | .stderr(std::process::Stdio::inherit()) 200 | .output() 201 | { 202 | Ok(output) => output, 203 | Err(err) => { 204 | if err.kind() == std::io::ErrorKind::NotFound { 205 | println!("{} requires buildah to manage the OCI images, and it wasn't found on this system.", APP_NAME); 206 | } else { 207 | println!("Error executing buildah: {}", err); 208 | } 209 | std::process::exit(-1); 210 | } 211 | }; 212 | 213 | let exit_code = output.status.code().unwrap_or(-1); 214 | if exit_code != 0 { 215 | println!( 216 | "buildah returned an error: {}", 217 | std::str::from_utf8(&output.stdout).unwrap() 218 | ); 219 | std::process::exit(-1); 220 | } 221 | 222 | let rootfs = std::str::from_utf8(&output.stdout).unwrap().trim(); 223 | 224 | #[cfg(target_os = "macos")] 225 | fix_root_mode(rootfs); 226 | 227 | Ok(rootfs.to_string()) 228 | } 229 | 230 | #[allow(unused_variables)] 231 | pub fn umount_container(cfg: &KrunvmConfig, vmcfg: &VmConfig) -> Result<(), std::io::Error> { 232 | let mut args = get_buildah_args(cfg, BuildahCommand::Unmount); 233 | args.push(vmcfg.container.clone()); 234 | 235 | let output = match Command::new("buildah") 236 | .args(&args) 237 | .stderr(std::process::Stdio::inherit()) 238 | .output() 239 | { 240 | Ok(output) => output, 241 | Err(err) => { 242 | if err.kind() == std::io::ErrorKind::NotFound { 243 | println!("{} requires buildah to manage the OCI images, and it wasn't found on this system.", APP_NAME); 244 | } else { 245 | println!("Error executing buildah: {}", err); 246 | } 247 | std::process::exit(-1); 248 | } 249 | }; 250 | 251 | let exit_code = output.status.code().unwrap_or(-1); 252 | if exit_code != 0 { 253 | println!( 254 | "buildah returned an error: {}", 255 | std::str::from_utf8(&output.stdout).unwrap() 256 | ); 257 | std::process::exit(-1); 258 | } 259 | 260 | Ok(()) 261 | } 262 | 263 | #[allow(unused_variables)] 264 | pub fn remove_container(cfg: &KrunvmConfig, vmcfg: &VmConfig) -> Result<(), std::io::Error> { 265 | let mut args = get_buildah_args(cfg, BuildahCommand::Remove); 266 | args.push(vmcfg.container.clone()); 267 | 268 | let output = match Command::new("buildah") 269 | .args(&args) 270 | .stderr(std::process::Stdio::inherit()) 271 | .output() 272 | { 273 | Ok(output) => output, 274 | Err(err) => { 275 | if err.kind() == std::io::ErrorKind::NotFound { 276 | println!("{} requires buildah to manage the OCI images, and it wasn't found on this system.", APP_NAME); 277 | } else { 278 | println!("Error executing buildah: {}", err); 279 | } 280 | std::process::exit(-1); 281 | } 282 | }; 283 | 284 | let exit_code = output.status.code().unwrap_or(-1); 285 | if exit_code != 0 { 286 | println!( 287 | "buildah returned an error: {}", 288 | std::str::from_utf8(&output.stdout).unwrap() 289 | ); 290 | std::process::exit(-1); 291 | } 292 | 293 | Ok(()) 294 | } 295 | --------------------------------------------------------------------------------