Skip to content

Commit

Permalink
[antlir2][image_test] add hostname option
Browse files Browse the repository at this point in the history
Summary: Small missing feature

Test Plan:
```
❯ buck2 test fbcode//antlir/antlir2/testing/tests:test-hostname fbcode//antlir/antlir2/testing/tests:test-hostname-booted
Buck UI: https://www.internalfb.com/buck2/cd5d357f-4089-45b9-a221-f827d14d229c
Test UI: https://www.internalfb.com/intern/testinfra/testrun/17169973583492924
Network: Up: 32MiB  Down: 209MiB  (reSessionID-8184c46f-74df-4daa-a8ba-2270c0d778ca)
Jobs completed: 267. Time elapsed: 1:05.6s.
Cache hits: 0%. Commands: 169 (cached: 0, remote: 1, local: 168). Fallback: 1/169
Tests finished: Pass 2. Fail 0. Fatal 0. Skip 0. Build failure 0
```

Reviewed By: r1mikey

Differential Revision: D49756197

fbshipit-source-id: d45001c530d6ed35e799660da373deaf5fa12551
  • Loading branch information
vmagro authored and facebook-github-bot committed Sep 29, 2023
1 parent 2132de3 commit e15b743
Show file tree
Hide file tree
Showing 7 changed files with 61 additions and 1 deletion.
9 changes: 9 additions & 0 deletions antlir/antlir2/antlir2_isolate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ pub struct IsolationContext<'a> {
ephemeral: bool,
/// See [IsolationContextBuilder::tmpfs]
tmpfs: BTreeSet<Cow<'a, Path>>,
/// See [IsolationContextBuilder::hostname]
hostname: Option<Cow<'a, str>>,
}

/// Controls how the container is spawned and how console is configured for the
Expand Down Expand Up @@ -104,6 +106,7 @@ impl<'a> IsolationContext<'a> {
user: Cow::Borrowed("root"),
ephemeral: true,
tmpfs: Default::default(),
hostname: None,
},
}
}
Expand Down Expand Up @@ -188,6 +191,12 @@ impl<'a> IsolationContextBuilder<'a> {
self
}

/// Set the hostname in the container
pub fn hostname<S: Into<Cow<'a, str>>>(&mut self, hostname: S) -> &mut Self {
self.ctx.hostname = Some(hostname.into());
self
}

/// Finalize the IsolationContext
pub fn build(&mut self) -> IsolationContext<'a> {
self.ctx.clone()
Expand Down
7 changes: 6 additions & 1 deletion antlir/antlir2/antlir2_isolate/src/sys/bwrap/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub fn bwrap(ctx: IsolationContext, bwrap: Option<&OsStr>) -> Result<IsolatedCon
user,
ephemeral,
tmpfs,
hostname,
} = ctx;
assert_eq!(user, "root", "user != root unimplemented");
assert!(!register, "register unimplemented");
Expand Down Expand Up @@ -67,7 +68,11 @@ pub fn bwrap(ctx: IsolationContext, bwrap: Option<&OsStr>) -> Result<IsolatedCon
// detach from this process's controlling terminal
bwrap_args.push("--new-session".into());
bwrap_args.push("--hostname".into());
bwrap_args.push("antlir2".into());
if let Some(hostname) = hostname {
bwrap_args.push(hostname.as_ref().into());
} else {
bwrap_args.push(Uuid::new_v4().simple().to_string().into());
}

// our containers are for isolation, not security, so having all the caps of
// the parent is desirable when we need to do things like btrfs snapshots
Expand Down
5 changes: 5 additions & 0 deletions antlir/antlir2/antlir2_isolate/src/sys/nspawn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ pub fn nspawn(ctx: IsolationContext) -> Result<IsolatedContext> {
user,
ephemeral,
tmpfs,
hostname,
} = ctx;
let mut nspawn_args = Vec::<OsString>::new();
let mut env = HashMap::new();
Expand All @@ -88,6 +89,10 @@ pub fn nspawn(ctx: IsolationContext) -> Result<IsolatedContext> {
nspawn_args.push("--private-network".into());
nspawn_args.push("--user".into());
nspawn_args.push(user.as_ref().into());
if let Some(hostname) = hostname {
nspawn_args.push("--hostname".into());
nspawn_args.push(hostname.as_ref().into());
}
// keep whatever timezone was in the image, not on the host
nspawn_args.push("--timezone=off".into());
// Don't pollute the host's /var/log/journal
Expand Down
4 changes: 4 additions & 0 deletions antlir/antlir2/testing/image_test.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def _impl(ctx: AnalysisContext) -> list[Provider]:
ctx.attrs.image_test[RunInfo],
cmd_args(ctx.attrs.layer[LayerInfo].subvol_symlink, format = "--layer={}"),
cmd_args(ctx.attrs.run_as_user, format = "--user={}"),
cmd_args(ctx.attrs.hostname, format = "--hostname={}") if ctx.attrs.hostname else cmd_args(),
cmd_args("--boot") if ctx.attrs.boot else cmd_args(),
cmd_args(boot_requires_units, format = "--requires-unit={}") if ctx.attrs.boot else cmd_args(),
cmd_args(boot_after_units, format = "--after-unit={}") if ctx.attrs.boot else cmd_args(),
Expand Down Expand Up @@ -93,6 +94,7 @@ _image_test = rule(
default = None,
doc = "Add a Requires= and After= requirement on these units to the test",
),
"hostname": attrs.option(attrs.string(), default = None),
"image_test": attrs.default_only(attrs.exec_dep(default = "//antlir/antlir2/testing/image_test:image-test")),
"labels": attrs.list(attrs.string(), default = []),
"layer": attrs.dep(providers = [LayerInfo]),
Expand All @@ -116,6 +118,7 @@ def _implicit_image_test(
boot: bool = False,
boot_requires_units: [list[str], None] = None,
boot_after_units: [list[str], None] = None,
hostname: str | None = None,
_add_outer_labels: list[str] = [],
**kwargs):
test_rule(
Expand Down Expand Up @@ -152,6 +155,7 @@ def _implicit_image_test(
boot = boot,
boot_requires_units = boot_requires_units,
boot_after_units = boot_after_units,
hostname = hostname,
)

image_cpp_test = partial(
Expand Down
7 changes: 7 additions & 0 deletions antlir/antlir2/testing/image_test/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ struct Args {
/// Run the test as this user
user: String,
#[clap(long)]
/// Set container hostname
hostname: Option<String>,
#[clap(long)]
/// Boot the container with /init as pid1 before running the test
boot: bool,
#[clap(long = "requires-unit", requires = "boot")]
Expand Down Expand Up @@ -148,6 +151,10 @@ fn main() -> Result<()> {
ctx.outputs([Path::new("/dev/fuse")]);
}

if let Some(hostname) = args.hostname {
ctx.hostname(hostname);
}

if args.boot {
let container_stdout = container_stdout_file()?;
let (mut test_stdout, mut test_stderr) = make_log_files("test")?;
Expand Down
15 changes: 15 additions & 0 deletions antlir/antlir2/testing/tests/BUCK
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,21 @@ image.layer(
]
]

image_python_test(
name = "test-hostname",
srcs = ["test_hostname.py"],
hostname = "antlir2-test-hostname",
layer = ":base",
)

image_python_test(
name = "test-hostname-booted",
srcs = ["test_hostname.py"],
boot = True,
hostname = "antlir2-test-hostname",
layer = ":base",
)

image.layer(
name = "foo-rpms",
dnf_available_repos = "//antlir/antlir2/test_images/rpms:test-repo-set",
Expand Down
15 changes: 15 additions & 0 deletions antlir/antlir2/testing/tests/test_hostname.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import socket
import unittest


class TestHostname(unittest.TestCase):
def setUp(self) -> None:
super().setUp()

def test_hostname(self) -> None:
self.assertEqual(socket.gethostname(), "antlir2-test-hostname")

0 comments on commit e15b743

Please sign in to comment.