Last active
December 11, 2015 00:59
-
-
Save wookietreiber/4520393 to your computer and use it in GitHub Desktop.
linux swap per process command line printer based on /proc
This file contains 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
#!/bin/sh | |
exec scala "$0" "$@" | |
!# | |
import java.io.{ File, FilenameFilter, FileNotFoundException } | |
import scala.util.control.Exception._ | |
if (List("-h", "-?", "-help", "--help") exists argv.contains) { | |
Console.println(""" | |
|Print swap usage per process. | |
| | |
| -h | -? | -help | --help Print this help. | |
| -s | --sort-by-size Sort by used swap size. | |
""".stripMargin) | |
sys exit 0 | |
} | |
val pids = new File("/proc") list new FilenameFilter { | |
def accept(dir: File, name: String) = name.matches("""^\d+$""") | |
} | |
val data = pids.view flatMap { pid ⇒ | |
val optLines = catching(classOf[FileNotFoundException]) opt { | |
io.Source.fromFile(s"/proc/$pid/status").getLines().toSeq | |
} | |
optLines.toList flatMap { lines ⇒ | |
val optName = lines collectFirst { case Regex.NameRE(name) ⇒ name } | |
val optSwap = lines collectFirst { case Regex.SwapRE(swapKiB) if swapKiB != "0" ⇒ swapKiB } | |
optName.toList flatMap { name ⇒ | |
optSwap collect { case swapKiB ⇒ (name,pid,swapKiB.toDouble) } | |
} | |
} | |
} | |
val sorted = if (List("-s", "--sort-by-size") exists argv.contains) data sortBy { - _._3 } else data | |
sorted foreach { case (name,pid,swapKiB) ⇒ | |
val (swap,unit) = HumanizeKiB(swapKiB.toDouble) | |
Console.println(f"$pid%5s $name%15s ${swap.round}%4d $unit") | |
} | |
object Regex { | |
lazy val NameRE = """Name:\s+(.+)""".r | |
lazy val SwapRE = """VmSwap:\s+(.+) .+""".r | |
} | |
object HumanizeKiB { | |
lazy val k = math.pow(2,10) | |
lazy val m = math.pow(2,20) | |
lazy val g = math.pow(2,30) | |
lazy val t = math.pow(2,40) | |
lazy val p = math.pow(2,50) | |
lazy val e = math.pow(2,60) | |
lazy val z = math.pow(2,70) | |
def apply(kib: Double): (Double,String) = kib match { | |
case _ if kib < k ⇒ (kib, "KiB") | |
case _ if kib < m ⇒ (kib / k, "MiB") | |
case _ if kib < g ⇒ (kib / m, "GiB") | |
case _ if kib < t ⇒ (kib / g, "TiB") | |
case _ if kib < p ⇒ (kib / t, "PiB") | |
case _ if kib < e ⇒ (kib / p, "EiB") | |
case _ if kib < z ⇒ (kib / e, "ZiB") | |
case _ ⇒ (kib / z, "YiB") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment