Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Groovy Script to total active sessions from one or more Tomcat contexts with option to stall until zero sessions
#!/usr/bin/env groovy
package devops
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("list", "**********".toCharArray());
}
})
servers = []
context = ''
list = false
wait = false
def cli = new CliBuilder(usage: 'tomcatsessions [options] -c context {server}...')
cli.w('wait for zero sessions')
cli.c(args: 1, "context")
cli.l('list')
cli.h('help')
def options = cli.parse(args)
if (options.h) {
cli.usage()
System.exit(0)
}
if (options.w) {
wait = true
} else {
list = true
}
if (options.l) { list = true }
if (options.arguments()) {
servers = options.arguments().collect { it.trim() }
}
if (options.c) {
context = options.c
}
def total = getTotal()
while (wait && total) {
println "waiting for sessions on $servers$context: $total remaining"
Thread.sleep(10 * 1000)
total = getTotal()
}
def getTotal() {
def counts = getSessionCounts()
if (list) {
println "session counts for $context:\n "
counts.each { k, v ->
println String.format("%20s:%4d", k, v)
}
println String.format("\n%20s:%4d", "Total", counts.collect { it.value }.sum(0))
}
return counts.collect { it.value }.sum(0)
}
def getSessionCounts() {
servers.collectEntries { s ->
def lines = "http://${s}:8080/manager/text/sessions?path=${context}".toURL().readLines()
if (!lines[0].startsWith('OK')) {
return [(s): "failed: " + lines.join('\n')]
}
[(s): lines.findAll { it.contains(":") }.collect { it.split(':')[1].trim().split(' ')[0].toInteger() }.sum(0)]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment