Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions crates/berth-api/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1643,6 +1643,38 @@ pub struct Applied {
pub plugins: Vec<AppliedPlugin>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub offers: Vec<Offer>,
/// The host's device on the tailnet, as its Tailscale client saw it at
/// the end of the apply, when it is on one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub tailnet: Option<TailnetDevice>,
}

/// A host's device on the tailnet, from `tailscale status --json`. It
/// holds public values only, which the control server's API finds it by.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct TailnetDevice {
/// The device's stable id: Tailscale's `nodeId`, or the number of
/// Headscale's node.
pub id: String,
/// Its MagicDNS name, such as `studio.example.ts.net`, without the final dot.
#[serde(default)]
pub dns_name: String,
/// The machine's own hostname, as the client reports it.
#[serde(default)]
pub host_name: String,
/// Its addresses on the tailnet.
#[serde(default)]
pub addresses: Vec<String>,
/// The tailnet's name, when the client knows it.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub tailnet: String,
}

impl TailnetDevice {
/// The first label of its MagicDNS name: its name on the tailnet.
pub fn name(&self) -> &str {
self.dns_name.split('.').next().unwrap_or_default()
}
}

/// Provisioners a feature of a host offers, as its tasks found them: berth
Expand Down
32 changes: 32 additions & 0 deletions crates/berth-core/src/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,9 @@ pub fn settle_with(paths: &Paths, host: &Host, out: &mut dyn Write) -> Result<()
let _ = writeln!(out, "! {error}");
}
}
for line in settle_tailnet(paths, host) {
let _ = writeln!(out, "{line}");
}
let Some(mut profile) = host.place.load(paths)? else {
return Ok(());
};
Expand All @@ -385,6 +388,35 @@ pub fn settle_with(paths: &Paths, host: &Host, out: &mut dyn Write) -> Result<()
Ok(())
}

/// After a successful apply of a host that joins the tailnet: record its
/// device, and rename it when a rename asked for that. Only with the API
/// key, as berth does nothing with the device without it; a host applied
/// before the key was set is looked up by its address or hostname instead.
fn settle_tailnet(paths: &Paths, host: &Host) -> Vec<String> {
if !berth_api::profile::joins_tailnet(&host.config)
|| crate::tailnet::Control::configured(paths)
.device_problem()
.is_some()
{
return vec![];
}
let reported = match crate::node::applied(paths, host) {
Ok(applied) => applied.and_then(|applied| applied.tailnet),
Err(error) => {
return vec![format!(
"! {} did not say which device it is on the tailnet, so berth has not recorded it: {error}",
host.name
)];
}
};
crate::tailnet::after_apply(paths, host, reported).unwrap_or_else(|error| {
vec![format!(
"! berth did not record {}'s device on the tailnet: {error}",
host.name
)]
})
}

/// After a successful apply of a node: register the provisioners its
/// features offer, and forget those they no longer do. Says what it did, a
/// line each.
Expand Down
2 changes: 1 addition & 1 deletion crates/berth-core/src/host_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ pub fn rename_action() -> Action {
berth_api::Argument {
name: "hostname".into(),
label: "Hostname too".into(),
help: "Make the new name the profile's hostname as well. The machine takes it at its next apply.".into(),
help: "Make the new name the profile's hostname as well. The machine takes it at its next apply, and so does its device on the tailnet.".into(),
default: "no".into(),
values: vec!["no".into(), "yes".into()],
..Default::default()
Expand Down
15 changes: 9 additions & 6 deletions crates/berth-core/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,14 @@ pub fn rename(paths: &Paths, old: &str, new: &str) -> Result<()> {
/// What the node `host` reported at the end of its last apply, asked of its
/// controller until it answers: the provisioners its features offer.
pub fn reported(paths: &Paths, host: &Host) -> Result<Vec<Offer>> {
Ok(applied(paths, host)?
.map(|applied| applied.offers)
.unwrap_or_default())
}

/// The record the last apply left on `host`, asked of its controller until
/// it answers, as the controller may restart at the end of an apply.
pub fn applied(paths: &Paths, host: &Host) -> Result<Option<berth_api::Applied>> {
let password = host.kept_sudo_password(paths);
let link = crate::link::Link::new(host.link(paths, password.as_deref())?);
let runtime = crate::link::runtime()?;
Expand All @@ -662,12 +670,7 @@ pub fn reported(paths: &Paths, host: &Host) -> Result<Vec<Offer>> {
tokio::time::timeout(std::time::Duration::from_secs(15), link.version()).await
});
match asked {
Ok(Ok(version)) => {
return Ok(version
.applied
.map(|applied| applied.offers)
.unwrap_or_default());
}
Ok(Ok(version)) => return Ok(version.applied),
Ok(Err(error)) if started.elapsed() >= patience => {
return Err(error.to_string().into());
}
Expand Down
29 changes: 23 additions & 6 deletions crates/berth-core/src/profiles.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,9 @@ pub fn list(paths: &Paths, scope: &str) -> Result<Vec<(String, Value)>> {
}

/// Forget a host: its profile, its generated passwords, the record of a
/// machine of it that was never made, what berth knows of its SSH and the passwords it keeps for
/// logging in, in one change. A profile in a file is removed with the file.
/// machine of it that was never made, what berth knows of its SSH and of its
/// device on the tailnet, and the passwords it keeps for logging in, in one
/// change. The device stays on the tailnet. A profile in a file is removed with the file.
pub fn remove(paths: &Paths, place: &Place) -> Result<()> {
let (scope, name) = place.side();
// The provisioners a node offers go with it, unless they still hold resources.
Expand All @@ -215,6 +216,7 @@ pub fn remove(paths: &Paths, place: &Place) -> Result<()> {
let mut removals = vec![
(kind::CREDENTIALS, scope.as_str(), name.as_str()),
(kind::ACCESS, scope.as_str(), name.as_str()),
(kind::TAILNET, scope.as_str(), name.as_str()),
];
if !machine.is_empty() {
removals.push((kind::RESOURCE, scope.as_str(), machine.as_str()));
Expand Down Expand Up @@ -255,10 +257,11 @@ pub fn hostname_allowed(name: &str, profile: &Value) -> Result<()> {

/// Give a saved host another name in its scope: its profile, its generated
/// passwords, what berth knows of its SSH, the passwords it keeps for logging
/// in and the resources that belong to it, in one change. A host of this
/// installation's own takes its messages and jobs along. The machine stays as
/// it is, and so does its hostname unless `hostname` asks for the profile's to
/// be the new name, which an apply then gives the machine. Returns the new place.
/// in, its device on the tailnet and the resources that belong to it, in one
/// change. A host of this installation's own takes its messages and jobs
/// along. The machine stays as it is, and so does its hostname unless
/// `hostname` asks for the profile's to be the new name, which an apply then
/// gives the machine and its device on the tailnet. Returns the new place.
pub fn rename(paths: &Paths, from: &Place, to: &str, hostname: bool) -> Result<Place> {
let Place::Stored { scope, name: old } = from else {
return Err("A profile in a file is renamed by moving the file".into());
Expand Down Expand Up @@ -294,6 +297,7 @@ pub fn rename(paths: &Paths, from: &Place, to: &str, hostname: bool) -> Result<P
let mut moved = vec![
(kind::CREDENTIALS, scope.clone(), old.clone(), to.to_owned()),
(kind::ACCESS, scope.clone(), old.clone(), to.to_owned()),
(kind::TAILNET, scope.clone(), old.clone(), to.to_owned()),
];
if scope == OWN {
for secret in [crate::keys::password_secret, crate::keys::sudo_secret] {
Expand All @@ -306,6 +310,19 @@ pub fn rename(paths: &Paths, from: &Place, to: &str, hostname: bool) -> Result<P
removals.push((kind, scope.as_str(), old.as_str()));
}
}
// The device on the tailnet takes the new hostname at the next apply,
// when the machine has it too.
if hostname && berth_api::profile::joins_tailnet(&profile) {
let mut kept = crate::tailnet::Kept::read(&store, scope, old)?;
kept.rename = Some(to.to_owned());
writes.retain(|(kind, ..)| *kind != kind::TAILNET);
writes.push((
kind::TAILNET,
scope.as_str(),
to,
serde_json::to_vec(&kept)?,
));
}
// A resource keeps its id and its name at the provisioner; only the host
// it belongs to is named anew.
let mut resources = vec![];
Expand Down
3 changes: 3 additions & 0 deletions crates/berth-core/src/store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ pub mod kind {
pub const KEY: &str = "key";
/// What berth knows of a host's SSH: its host keys and the keys it trusts.
pub const ACCESS: &str = "access";
/// What berth knows of a host's device on the tailnet, and a new name
/// it is to take.
pub const TAILNET: &str = "tailnet";
pub const TOKEN: &str = "token";
pub const PLUGIN: &str = "plugin";
pub const MIRROR: &str = "mirror";
Expand Down
Loading
Loading