Skip to content

Commit fe325e8

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

File tree

4 files changed

+59
-11
lines changed

4 files changed

+59
-11
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: 17 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,16 @@ enum Command {
116116
Run(cmd::run::Args),
117117
}
118118

119+
impl ObservabilityHints for Command {
120+
fn listen_address(&self) -> Option<&str> {
121+
#[allow(clippy::wildcard_enum_match_arm)]
122+
match self {
123+
Command::Run(args) => Some(args.listen_address()),
124+
_ => None,
125+
}
126+
}
127+
}
128+
119129
#[derive(Debug, Parser)]
120130
#[clap(name = "Amaru")]
121131
#[clap(bin_name = "amaru")]
@@ -151,8 +161,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
151161
let (metrics, teardown) = if skip_logging {
152162
(None, Box::new(|| Ok(())) as Box<dyn FnOnce() -> Result<(), Box<dyn std::error::Error>>>)
153163
} else {
154-
let (m, t) =
155-
setup_observability(args.with_open_telemetry, args.with_json_traces, Color::is_enabled(args.color));
164+
let (m, t) = setup_observability(
165+
args.with_open_telemetry,
166+
args.with_json_traces,
167+
Color::is_enabled(args.color),
168+
&args.command,
169+
);
156170
(Some(m), t)
157171
};
158172

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

Lines changed: 14 additions & 3 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")]
@@ -61,8 +68,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
6168
"Started with global arguments"
6269
);
6370

64-
let (_metrics, teardown) =
65-
setup_observability(args.with_open_telemetry, args.with_json_traces, Color::is_enabled(args.color));
71+
let (_metrics, teardown) = setup_observability(
72+
args.with_open_telemetry,
73+
args.with_json_traces,
74+
Color::is_enabled(args.color),
75+
&args.command,
76+
);
6677

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

crates/amaru/src/observability.rs

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -270,17 +270,33 @@ 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+
273280
#[expect(clippy::panic)]
274-
pub fn setup_open_telemetry(subscriber: &mut TracingSubscriber<Registry>) -> (OpenTelemetryHandle, DelayedWarning) {
281+
pub fn setup_open_telemetry(
282+
subscriber: &mut TracingSubscriber<Registry>,
283+
hints: &impl ObservabilityHints,
284+
) -> (OpenTelemetryHandle, DelayedWarning) {
275285
use opentelemetry::KeyValue;
276286
use opentelemetry_sdk::{Resource, metrics::Temporality};
277287

278288
let service_name =
279289
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();
290+
let service_instance_id: Option<String> =
291+
var("OTEL_SERVICE_INSTANCE_ID").ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty()).or_else(|| {
292+
let listen_addr = hints.listen_address()?;
293+
let hostname = sysinfo::System::host_name().unwrap_or_else(|| "localhost".to_string());
294+
let port = listen_addr.trim().rsplit(':').next()?;
295+
Some(format!("{hostname}:{port}"))
296+
});
281297
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));
298+
if let Some(instance_id) = service_instance_id {
299+
attributes.push(KeyValue::new(SERVICE_INSTANCE_ID, instance_id));
284300
}
285301
let resource = Resource::builder().with_attributes(attributes).build();
286302

@@ -465,11 +481,12 @@ pub fn setup_observability(
465481
with_open_telemetry: bool,
466482
with_json_traces: bool,
467483
color: bool,
484+
hints: &impl ObservabilityHints,
468485
) -> (Option<SdkMeterProvider>, Box<dyn FnOnce() -> Result<(), Box<dyn std::error::Error>>>) {
469486
let mut subscriber = TracingSubscriber::new();
470487

471488
let (OpenTelemetryHandle { metrics, teardown }, warning_otlp) = if with_open_telemetry {
472-
setup_open_telemetry(&mut subscriber)
489+
setup_open_telemetry(&mut subscriber, hints)
473490
} else {
474491
(OpenTelemetryHandle::default(), None)
475492
};

0 commit comments

Comments
 (0)