Skip to content

Instantly share code, notes, and snippets.

@davejsmith
Last active February 11, 2016 05:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davejsmith/0c79ab3818efc6b2b830 to your computer and use it in GitHub Desktop.
Save davejsmith/0c79ab3818efc6b2b830 to your computer and use it in GitHub Desktop.
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