Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use gen_all_metrics() for Riemann exporter #194

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
11 changes: 6 additions & 5 deletions src/exporters/prometheus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use clap::{Arg, ArgMatches};
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Request, Response, Server};
use std::convert::Infallible;
use std::fmt::Write;
use std::{
collections::HashMap,
net::{IpAddr, SocketAddr},
Expand Down Expand Up @@ -194,12 +195,12 @@ fn format_metric(key: &str, value: &str, labels: Option<&HashMap<String, String>
if let Some(labels) = labels {
result.push('{');
for (k, v) in labels.iter() {
result.push_str(&format!("{}=\"{}\",", k, v.replace('\"', "_")));
write!(result, "{}=\"{}\",", k, v.replace('\"', "_")).unwrap();
}
result.remove(result.len() - 1);
result.push('}');
}
result.push_str(&format!(" {}\n", value));
writeln!(result, " {}", value).unwrap();
result
}

Expand All @@ -211,8 +212,8 @@ fn push_metric(
metric_name: String,
metric_line: String,
) -> String {
body.push_str(&format!("# HELP {} {}", metric_name, help));
body.push_str(&format!("\n# TYPE {} {}\n", metric_name, metric_type));
write!(body, "# HELP {} {}", metric_name, help).unwrap();
writeln!(body, "\n# TYPE {} {}", metric_name, metric_type).unwrap();
body.push_str(&metric_line);
body
}
Expand Down Expand Up @@ -272,7 +273,7 @@ async fn show_metrics(
);
}
} else {
body.push_str(&format!("<a href=\"https://github.com/hubblo-org/scaphandre/\">Scaphandre's</a> prometheus exporter here. Metrics available on <a href=\"/{}\">/{}</a>", suffix, suffix));
write!(body,"<a href=\"https://github.com/hubblo-org/scaphandre/\">Scaphandre's</a> prometheus exporter here. Metrics available on <a href=\"/{}\">/{}</a>", suffix, suffix).unwrap();
}
Ok(Response::new(body.into()))
}
Expand Down
87 changes: 27 additions & 60 deletions src/exporters/riemann.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use clap::Arg;
use riemann_client::proto::Attribute;
use riemann_client::proto::Event;
use riemann_client::Client;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
Expand Down Expand Up @@ -138,9 +137,8 @@ impl Exporter for RiemannExporter {
println!("Press CTRL-C to stop scaphandre");
println!("Measurement step is: {}s", dispatch_duration);

let topology = self.sensor.get_topology().unwrap();
let mut metric_generator = MetricGenerator::new(
topology,
self.sensor.get_topology().unwrap(),
hostname,
parameters.is_present("qemu"),
parameters.is_present("containers"),
Expand All @@ -164,66 +162,27 @@ impl Exporter for RiemannExporter {
metric_generator.topology.refresh();

info!("{}: Refresh data", Utc::now().format("%Y-%m-%dT%H:%M:%S"));
// Here we need a specific behavior for process metrics, so we call each gen function
// and then implement that specific behavior (we don't use gen_all_metrics).
metric_generator.gen_self_metrics();
metric_generator.gen_host_metrics();
metric_generator.gen_socket_metrics();
metric_generator.gen_all_metrics();

let mut data = vec![];
let processes_tracker = &metric_generator.topology.proc_tracker;

for pid in processes_tracker.get_alive_pids() {
let exe = processes_tracker.get_process_name(pid);
let cmdline = processes_tracker.get_process_cmdline(pid);

let mut attributes = HashMap::new();
attributes.insert("pid".to_string(), pid.to_string());

attributes.insert("exe".to_string(), exe.clone());

if let Some(cmdline_str) = cmdline {
attributes.insert("cmdline".to_string(), cmdline_str.replace('\"', "\\\""));

if parameters.is_present("qemu") {
if let Some(vmname) = utils::filter_qemu_cmdline(&cmdline_str) {
attributes.insert("vmname".to_string(), vmname);
}
}
}

// Here we define a metric name with pid + exe string suffix as riemann needs
// to differentiate services/metrics
let metric_name = format!(
"{}_{}_{}",
"scaph_process_power_consumption_microwatts", pid, exe
);
if let Some(power) = metric_generator
.topology
.get_process_power_consumption_microwatts(pid)
{
data.push(Metric {
name: metric_name,
metric_type: String::from("gauge"),
ttl: 60.0,
hostname: get_hostname(),
timestamp: power.timestamp,
state: String::from("ok"),
tags: vec!["scaphandre".to_string()],
attributes,
description: String::from("Power consumption due to the process, measured on at the topology level, in microwatts"),
metric_value: MetricValueType::Text(power.value),
});
}
}
// Send all data
info!("{}: Send data", Utc::now().format("%Y-%m-%dT%H:%M:%S"));
for metric in metric_generator.pop_metrics() {
rclient.send_metric(&metric);
}
for metric in data {
rclient.send_metric(&metric);
}
metric_generator
.pop_metrics()
.iter_mut()
.map(|mut metric| {
// Here we define a metric name with pid + exe string suffix as riemann needs
// to differentiate services/metrics
if metric.name == "scaph_process_power_consumption_microwatts" {
metric.name = format!(
"{}_{}_{}",
"scaph_process_power_consumption_microwatts",
metric.attributes.get("pid").unwrap(),
metric.attributes.get("exe").unwrap()
)
}
metric
})
.for_each(|metric| rclient.send_metric(metric));

thread::sleep(Duration::new(dispatch_duration, 0));
}
Expand Down Expand Up @@ -267,6 +226,13 @@ impl Exporter for RiemannExporter {
.takes_value(false);
options.push(arg);

let arg = Arg::with_name("containers")
.help("Monitor and apply labels for processes running as containers")
.long("containers")
.required(false)
.takes_value(false);
options.push(arg);

let arg = Arg::with_name("mtls")
.help("Connect to a Riemann server using mTLS. Parameters address, ca, cert and key must be defined.")
.long("mtls")
Expand Down Expand Up @@ -319,3 +285,4 @@ impl Exporter for RiemannExporter {
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
7 changes: 5 additions & 2 deletions src/exporters/stdout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::exporters::*;
use crate::sensors::Sensor;
use colored::*;
use regex::Regex;
use std::fmt::Write;
use std::thread;
use std::time::{Duration, Instant};

Expand Down Expand Up @@ -211,15 +212,17 @@ impl StdoutExporter {
}
false
}) {
to_print.push_str(&format!(
write!(
to_print,
"{} W\t",
current_domain
.metric_value
.to_string()
.parse::<f32>()
.unwrap()
/ 1000000.0
));
)
.unwrap()
} else {
to_print.push_str("---");
}
Expand Down