Skip to content

Commit 34cdf9e

Browse files
committed
feat: have a meaningull default for instance.id
Signed-off-by: jeluard <jeluard@users.noreply.github.com>
1 parent 63e9520 commit 34cdf9e

File tree

4 files changed

+57
-10
lines changed

4 files changed

+57
-10
lines changed

crates/amaru/src/bin/amaru/cmd/run.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,12 @@ pub struct Args {
130130
pid_file: Option<PathBuf>,
131131
}
132132

133+
impl Args {
134+
pub fn listen_address(&self) -> &str {
135+
&self.listen_address
136+
}
137+
}
138+
133139
pub async fn run(args: Args, meter_provider: Option<SdkMeterProvider>) -> Result<(), Box<dyn std::error::Error>> {
134140
with_optional_pid_file(args.pid_file.clone(), async |_pid_file| {
135141
let config = parse_args(args)?;

crates/amaru/src/bin/amaru/main.rs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
use std::sync::LazyLock;
1616

1717
use amaru::{
18-
observability::{Color, setup_observability},
18+
observability::{Color, ObservabilityHints, setup_observability},
1919
panic::panic_handler,
2020
};
2121
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
@@ -116,6 +116,15 @@ enum Command {
116116
Run(cmd::run::Args),
117117
}
118118

119+
impl ObservabilityHints for Command {
120+
fn listen_address(&self) -> Option<&str> {
121+
match self {
122+
Command::Run(args) => Some(args.listen_address()),
123+
_ => None,
124+
}
125+
}
126+
}
127+
119128
#[derive(Debug, Parser)]
120129
#[clap(name = "Amaru")]
121130
#[clap(bin_name = "amaru")]
@@ -151,8 +160,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
151160
let (metrics, teardown) = if skip_logging {
152161
(None, Box::new(|| Ok(())) as Box<dyn FnOnce() -> Result<(), Box<dyn std::error::Error>>>)
153162
} else {
154-
let (m, t) =
155-
setup_observability(args.with_open_telemetry, args.with_json_traces, Color::is_enabled(args.color));
163+
let (m, t) = setup_observability(
164+
args.with_open_telemetry,
165+
args.with_json_traces,
166+
Color::is_enabled(args.color),
167+
&args.command,
168+
);
156169
(Some(m), t)
157170
};
158171

crates/amaru/src/bin/ledger/main.rs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
// limitations under the License.
1414

1515
use amaru::{
16-
observability::{Color, setup_observability},
16+
observability::{Color, ObservabilityHints, setup_observability},
1717
panic::panic_handler,
1818
};
1919
use clap::{Parser, Subcommand};
@@ -31,6 +31,13 @@ enum Command {
3131
#[cfg(feature = "mithril")]
3232
Mithril(cmd::mithril::Args),
3333
}
34+
35+
impl ObservabilityHints for Command {
36+
fn listen_address(&self) -> Option<&str> {
37+
None
38+
}
39+
}
40+
3441
#[derive(Debug, Parser)]
3542
#[clap(name = "Amaru Ledger")]
3643
#[clap(bin_name = "amaru-ledger")]
@@ -62,7 +69,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
6269
);
6370

6471
let (_metrics, teardown) =
65-
setup_observability(args.with_open_telemetry, args.with_json_traces, Color::is_enabled(args.color));
72+
setup_observability(args.with_open_telemetry, args.with_json_traces, Color::is_enabled(args.color), &args.command);
6673

6774
let result = match args.command {
6875
Command::Sync(args) => cmd::sync::run(args).await,

crates/amaru/src/observability.rs

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -270,17 +270,37 @@ impl Default for OpenTelemetryHandle {
270270
const DEFAULT_OTLP_SERVICE_NAME: &str = "amaru";
271271
const DEFAULT_OTLP_METRIC_URL: &str = "http://localhost:4318/v1/metrics";
272272

273+
/// Context hints supplied by the caller to refine observability defaults.
274+
pub trait ObservabilityHints {
275+
/// The address the node will listen on, if known at this point.
276+
/// Used to build the default `service.instance.id` resource attribute.
277+
fn listen_address(&self) -> Option<&str>;
278+
}
279+
280+
273281
#[expect(clippy::panic)]
274-
pub fn setup_open_telemetry(subscriber: &mut TracingSubscriber<Registry>) -> (OpenTelemetryHandle, DelayedWarning) {
282+
pub fn setup_open_telemetry(
283+
subscriber: &mut TracingSubscriber<Registry>,
284+
hints: &impl ObservabilityHints,
285+
) -> (OpenTelemetryHandle, DelayedWarning) {
275286
use opentelemetry::KeyValue;
276287
use opentelemetry_sdk::{Resource, metrics::Temporality};
277288

278289
let service_name =
279290
var("OTEL_SERVICE_NAME").unwrap_or_else(|_| DEFAULT_OTLP_SERVICE_NAME.to_string()).trim().to_string();
280-
let service_instance_id = var("OTEL_SERVICE_INSTANCE_ID").ok();
291+
let service_instance_id: Option<String> = var("OTEL_SERVICE_INSTANCE_ID")
292+
.ok()
293+
.map(|v| v.trim().to_string())
294+
.filter(|v| !v.is_empty())
295+
.or_else(|| {
296+
let listen_addr = hints.listen_address()?;
297+
let hostname = sysinfo::System::host_name().unwrap_or_else(|| "localhost".to_string());
298+
let port = listen_addr.trim().rsplit(':').next()?;
299+
Some(format!("{hostname}:{port}"))
300+
});
281301
let mut attributes = vec![KeyValue::new(SERVICE_NAME, service_name.clone())];
282-
if let Some(id) = service_instance_id.filter(|value| !value.trim().is_empty()) {
283-
attributes.push(KeyValue::new(SERVICE_INSTANCE_ID, id));
302+
if let Some(instance_id) = service_instance_id {
303+
attributes.push(KeyValue::new(SERVICE_INSTANCE_ID, instance_id));
284304
}
285305
let resource = Resource::builder().with_attributes(attributes).build();
286306

@@ -465,11 +485,12 @@ pub fn setup_observability(
465485
with_open_telemetry: bool,
466486
with_json_traces: bool,
467487
color: bool,
488+
hints: &impl ObservabilityHints,
468489
) -> (Option<SdkMeterProvider>, Box<dyn FnOnce() -> Result<(), Box<dyn std::error::Error>>>) {
469490
let mut subscriber = TracingSubscriber::new();
470491

471492
let (OpenTelemetryHandle { metrics, teardown }, warning_otlp) = if with_open_telemetry {
472-
setup_open_telemetry(&mut subscriber)
493+
setup_open_telemetry(&mut subscriber, hints)
473494
} else {
474495
(OpenTelemetryHandle::default(), None)
475496
};

0 commit comments

Comments
 (0)