Skip to content

Commit

Permalink
Create memoryBalancing.R
Browse files Browse the repository at this point in the history
  • Loading branch information
Cecilsingh authored Sep 24, 2024
1 parent bfeaff6 commit ed3e2e7
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions loadBalancing/memoryBalancing.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#!/usr/bin/Rscript

get_nodes <- function(nodes = Sys.getenv("RSTUDIO_NODES")) {
unlist(strsplit(nodes, ",", fixed = TRUE))
}

get_health_check <- function(node_address) {
con <- url(sprintf("http://%s/health-check", node_address))
on.exit(close(con))
readLines(con)
}

parse_health_check <- function(health_check) {
fields <- unlist(strsplit(health_check, "\n|,"))

keys <- sub(
":",
"",
regmatches(fields, regexpr("^[a-z\\-]+:", fields))
)

values <- sub(
": ",
"",
regmatches(fields, regexpr(":.+$", fields))
)
data.frame(keys, values, stringsAsFactors = FALSE)
}

get_value <- function(hc_table, hc_value) {
as.double(hc_table[hc_table[["keys"]] == hc_value, "values"])
}

main <- function() {
nodes <- get_nodes()
named_hc <- setNames(lapply(nodes, get_health_check), nodes)
parsed_hc <- lapply(named_hc, parse_health_check)
mem_percent <- lapply(parsed_hc, get_value, "memory-percent")
least_mem <- names(which.min(unlist(mem_percent)))

least_mem
}

cat(main())

0 comments on commit ed3e2e7

Please sign in to comment.