-
Notifications
You must be signed in to change notification settings - Fork 10
Add github actions runner collector #15
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
Merged
pietroalbini
merged 8 commits into
rust-lang:master
from
njasm:add_gha_runner_collector
May 12, 2021
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
4334f94
added github actions runner collector
njasm 0454065
cargo fmt fixes
njasm c4c2def
rebase
njasm 08c655d
changed env var to GITHUB_TOKEN
njasm c4d7604
added ratelimit-remaining guard and pagination with parse_link_header…
njasm cde1547
added http client to gh runners collector
njasm 22cc3ed
injecting http client on collector registration added. fix bugs and a…
njasm a612b79
update toolchain, and addressed clippy `manual_map` lint
njasm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,205 @@ | ||
use super::default_headers; | ||
use crate::Config; | ||
use anyhow::{Context, Result}; | ||
use log::{debug, error}; | ||
use prometheus::core::AtomicI64; | ||
use prometheus::core::{Desc, GenericGauge}; | ||
use prometheus::proto::MetricFamily; | ||
use prometheus::{core::Collector, IntGauge, Opts}; | ||
use reqwest::header::{HeaderValue, LINK}; | ||
use reqwest::{Client, Response}; | ||
use std::collections::HashMap; | ||
use std::sync::{Arc, RwLock}; | ||
use tokio::time::Duration; | ||
|
||
const GH_RUNNERS_ENDPOINT: &str = | ||
"https://api.github.com/repos/{owner_repo}/actions/runners?per_page=100"; | ||
|
||
#[derive(Debug, serde::Deserialize)] | ||
struct ApiResponse { | ||
total_count: usize, | ||
runners: Vec<Runner>, | ||
} | ||
|
||
#[derive(Debug, serde::Deserialize)] | ||
struct Runner { | ||
id: usize, | ||
name: String, | ||
os: String, | ||
status: String, | ||
busy: bool, | ||
} | ||
|
||
#[derive(Clone)] | ||
pub struct GithubRunners { | ||
//api token to use | ||
token: String, | ||
// repos to track gha runners | ||
repos: Vec<String>, | ||
// actual metrics | ||
metrics: Arc<RwLock<Vec<IntGauge>>>, | ||
// default metric description | ||
desc: Desc, | ||
http: Client, | ||
} | ||
|
||
impl GithubRunners { | ||
pub async fn new(config: &Config, http: Client) -> Result<Self> { | ||
let token = config.github_token.to_string(); | ||
let repos: Vec<String> = config | ||
.gha_runners_repos | ||
.split(',') | ||
.map(|v| v.trim().to_string()) | ||
.collect(); | ||
|
||
let rv = Self { | ||
token, | ||
repos, | ||
http, | ||
metrics: Arc::new(RwLock::new(Vec::new())), | ||
desc: Desc::new( | ||
String::from("gha_runner"), | ||
String::from("GHA runner's status"), | ||
Vec::new(), | ||
HashMap::new(), | ||
) | ||
.unwrap(), | ||
}; | ||
|
||
let refresh_rate = config.gha_runners_cache_refresh; | ||
let mut rv2 = rv.clone(); | ||
tokio::spawn(async move { | ||
loop { | ||
if let Err(e) = rv2.update_stats().await { | ||
error!("{:#?}", e); | ||
} | ||
|
||
tokio::time::delay_for(Duration::from_secs(refresh_rate)).await; | ||
} | ||
}); | ||
|
||
Ok(rv) | ||
} | ||
|
||
async fn update_stats(&mut self) -> Result<()> { | ||
let mut gauges = Vec::with_capacity(self.repos.len() * 2); | ||
for repo in self.repos.iter() { | ||
let mut url: Option<String> = String::from(GH_RUNNERS_ENDPOINT) | ||
.replace("{owner_repo}", repo) | ||
.into(); | ||
|
||
debug!("Updating runner's stats"); | ||
|
||
while let Some(endpoint) = url.take() { | ||
let response = self | ||
.http | ||
.get(&endpoint) | ||
.headers(default_headers(&self.token)) | ||
pietroalbini marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.send() | ||
.await?; | ||
|
||
url = guard_rate_limited(&response)? | ||
.error_for_status_ref() | ||
.map(|res| next_uri(res.headers().get(LINK)))?; | ||
|
||
let resp = response.json::<ApiResponse>().await?; | ||
|
||
for runner in resp.runners.iter() { | ||
let online = metric_factory( | ||
"online", | ||
"runner is online", | ||
&self.desc.fq_name, | ||
&repo, | ||
&runner.name, | ||
); | ||
online.set(if runner.status == "online" { 1 } else { 0 }); | ||
gauges.push(online); | ||
|
||
let busy = metric_factory( | ||
"busy", | ||
"runner is busy", | ||
&self.desc.fq_name, | ||
&repo, | ||
&runner.name, | ||
); | ||
busy.set(if runner.busy { 1 } else { 0 }); | ||
gauges.push(busy); | ||
} | ||
} | ||
} | ||
|
||
// lock and replace old data | ||
let mut guard = self.metrics.write().unwrap(); | ||
*guard = gauges; | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
impl Collector for GithubRunners { | ||
fn desc(&self) -> Vec<&Desc> { | ||
vec![&self.desc] | ||
} | ||
|
||
fn collect(&self) -> Vec<MetricFamily> { | ||
self.metrics.read().map_or_else( | ||
|e| { | ||
error!("Unable to collect: {:#?}", e); | ||
Vec::with_capacity(0) | ||
}, | ||
|guard| { | ||
guard.iter().fold(Vec::new(), |mut acc, item| { | ||
acc.extend(item.collect()); | ||
acc | ||
}) | ||
}, | ||
) | ||
} | ||
} | ||
|
||
fn guard_rate_limited(response: &Response) -> Result<&Response> { | ||
let rate_limited = match response.headers().get("x-ratelimit-remaining") { | ||
Some(rl) => rl.to_str()?.parse::<usize>()? == 0, | ||
None => unreachable!(), | ||
}; | ||
|
||
if rate_limited { | ||
return response | ||
.error_for_status_ref() | ||
.context("We've hit the rate limit"); | ||
} | ||
|
||
Ok(response) | ||
} | ||
|
||
fn next_uri(header: Option<&HeaderValue>) -> Option<String> { | ||
if let Some(header) = header { | ||
return match header.to_str() { | ||
Ok(header_str) => match parse_link_header::parse(header_str) { | ||
Ok(links) => links | ||
.get(&Some("next".to_string())) | ||
.map(|next| next.uri.to_string()), | ||
_ => None, | ||
}, | ||
_ => None, | ||
}; | ||
} | ||
|
||
None | ||
} | ||
|
||
fn metric_factory<S: Into<String>>( | ||
name: S, | ||
help: S, | ||
ns: S, | ||
repo: S, | ||
runner: S, | ||
) -> GenericGauge<AtomicI64> { | ||
IntGauge::with_opts( | ||
Opts::new(name, help) | ||
.namespace(ns) | ||
.const_label("repo", repo) | ||
.const_label("runner", runner), | ||
) | ||
.unwrap() | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,43 @@ | ||
mod github_rate_limit; | ||
mod github_runners; | ||
|
||
pub use crate::collectors::github_rate_limit::GitHubRateLimit; | ||
pub use crate::collectors::github_runners::GithubRunners; | ||
|
||
use crate::MetricProvider; | ||
use anyhow::{Error, Result}; | ||
use futures::TryFutureExt; | ||
use log::info; | ||
use reqwest::header::{HeaderMap, ACCEPT, AUTHORIZATION}; | ||
use reqwest::ClientBuilder; | ||
|
||
// register collectors for metrics gathering | ||
pub async fn register_collectors(p: &MetricProvider) -> Result<(), Error> { | ||
let http = ClientBuilder::new() | ||
.user_agent("https://github.com/rust-lang/monitorbot ([email protected])") | ||
.build()?; | ||
|
||
GitHubRateLimit::new(&p.config) | ||
.and_then(|rl| async { | ||
info!("Registering GitHubRateLimit collector"); | ||
p.register_collector(rl) | ||
}) | ||
.await?; | ||
|
||
GithubRunners::new(&p.config, http) | ||
.and_then(|gr| async { | ||
info!("Registering GitHubActionsRunners collector"); | ||
p.register_collector(gr) | ||
}) | ||
.await | ||
} | ||
|
||
fn default_headers(token: &str) -> HeaderMap { | ||
let mut headers = HeaderMap::new(); | ||
headers.insert( | ||
AUTHORIZATION, | ||
format!("{} {}", "token", token).parse().unwrap(), | ||
); | ||
headers.insert(ACCEPT, "application/vnd.github.v3+json".parse().unwrap()); | ||
headers | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.