<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[15117] CalendarServer/trunk/contrib/tools/readStats.py</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.calendarserver.org//changeset/15117">15117</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2015-09-10 09:15:53 -0700 (Thu, 10 Sep 2015)</dd>
</dl>

<h3>Log Message</h3>
<pre>Add ability to generate terminal/bell sounds when certain values exceed a threshold.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#CalendarServertrunkcontribtoolsreadStatspy">CalendarServer/trunk/contrib/tools/readStats.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="CalendarServertrunkcontribtoolsreadStatspy"></a>
<div class="modfile"><h4>Modified: CalendarServer/trunk/contrib/tools/readStats.py (15116 => 15117)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/contrib/tools/readStats.py        2015-09-10 16:07:24 UTC (rev 15116)
+++ CalendarServer/trunk/contrib/tools/readStats.py        2015-09-10 16:15:53 UTC (rev 15117)
</span><span class="lines">@@ -35,7 +35,9 @@
</span><span class="cx">     return value * factor / total if total else 0
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+SummaryValues = collections.namedtuple(&quot;SummaryValues&quot;, (&quot;requests&quot;, &quot;response&quot;, &quot;slots&quot;, &quot;cpu&quot;, &quot;errors&quot;))
</ins><span class="cx"> 
</span><ins>+
</ins><span class="cx"> def readSock(sockname, useTCP):
</span><span class="cx">     try:
</span><span class="cx">         s = socket.socket(socket.AF_INET if useTCP else socket.AF_UNIX, socket.SOCK_STREAM)
</span><span class="lines">@@ -69,16 +71,18 @@
</span><span class="cx">             printFailedStats(stats[0][&quot;Failed&quot;])
</span><span class="cx">         else:
</span><span class="cx">             try:
</span><del>-                printStat(stats[0], multimode[0], showMethods, topUsers, showAgents)
</del><ins>+                summary = printStat(stats[0], multimode[0], showMethods, topUsers, showAgents)
</ins><span class="cx">             except KeyError, e:
</span><span class="cx">                 printFailedStats(&quot;Unable to find key '%s' in statistics from server socket&quot; % (e,))
</span><span class="cx">                 sys.exit(1)
</span><span class="cx"> 
</span><span class="cx">     else:
</span><del>-        printMultipleStats(stats, multimode, showMethods, topUsers, showAgents)
</del><ins>+        summary = printMultipleStats(stats, multimode, showMethods, topUsers, showAgents)
</ins><span class="cx"> 
</span><ins>+    return summary
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> def printStat(stats, index, showMethods, topUsers, showAgents):
</span><span class="cx"> 
</span><span class="cx">     print(&quot;- &quot; * 40)
</span><span class="lines">@@ -99,7 +103,7 @@
</span><span class="cx">         print(&quot;Current CPU: Unavailable&quot;)
</span><span class="cx">         print(&quot;Current Memory Used: Unavailable&quot;)
</span><span class="cx">     print
</span><del>-    printRequestSummary(stats)
</del><ins>+    summary = printRequestSummary(stats)
</ins><span class="cx">     printHistogramSummary(stats[index], index)
</span><span class="cx">     if showMethods:
</span><span class="cx">         printMethodCounts(stats[index])
</span><span class="lines">@@ -108,8 +112,10 @@
</span><span class="cx">     if showAgents:
</span><span class="cx">         printAgentCounts(stats[index])
</span><span class="cx"> 
</span><ins>+    return summary
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> def printMultipleStats(stats, multimode, showMethods, topUsers, showAgents):
</span><span class="cx"> 
</span><span class="cx">     labels = serverLabels(stats)
</span><span class="lines">@@ -135,7 +141,7 @@
</span><span class="cx">             cpus.append(-1)
</span><span class="cx">             memories.append(-1)
</span><span class="cx"> 
</span><del>-    printMultiRequestSummary(stats, cpus, memories, times, labels, multimode)
</del><ins>+    summary = printMultiRequestSummary(stats, cpus, memories, times, labels, multimode)
</ins><span class="cx">     printMultiHistogramSummary(stats, multimode[0])
</span><span class="cx">     if showMethods:
</span><span class="cx">         printMultiMethodCounts(stats, multimode[0])
</span><span class="lines">@@ -144,8 +150,10 @@
</span><span class="cx">     if showAgents:
</span><span class="cx">         printMultiAgentCounts(stats, multimode[0])
</span><span class="cx"> 
</span><ins>+    return summary
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> def serverLabels(stats):
</span><span class="cx">     servers = [stat[&quot;server&quot;] for stat in stats]
</span><span class="cx">     if isinstance(servers[0], tuple):
</span><span class="lines">@@ -220,8 +228,17 @@
</span><span class="cx">     table.printTable(os=os)
</span><span class="cx">     print(os.getvalue())
</span><span class="cx"> 
</span><ins>+    stat = stats[&quot;1m&quot;]
+    return SummaryValues(
+        requests=safeDivision(float(stat[&quot;requests&quot;]), seconds),
+        response=safeDivision(stat[&quot;t&quot;], stat[&quot;requests&quot;]),
+        slots=safeDivision(float(stat[&quot;slots&quot;]), stat[&quot;requests&quot;]),
+        cpu=safeDivision(stat[&quot;cpu&quot;], stat[&quot;requests&quot;]),
+        errors=stat[&quot;500&quot;],
+    )
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> def printMultiRequestSummary(stats, cpus, memories, times, labels, index):
</span><span class="cx"> 
</span><span class="cx">     key, seconds = index
</span><span class="lines">@@ -285,8 +302,16 @@
</span><span class="cx">     table.printTable(os=os)
</span><span class="cx">     print(os.getvalue())
</span><span class="cx"> 
</span><ins>+    return SummaryValues(
+        requests=totals[2],
+        response=totals[3],
+        slots=totals[6],
+        cpu=totals[7],
+        errors=totals[10],
+    )
</ins><span class="cx"> 
</span><span class="cx"> 
</span><ins>+
</ins><span class="cx"> def printHistogramSummary(stat, index):
</span><span class="cx"> 
</span><span class="cx">     print(&quot;%s average response histogram&quot; % (index,))
</span><span class="lines">@@ -484,6 +509,32 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+def alert(summary, alerts):
+
+    alert = []
+    for attr, description in (
+        (&quot;requests&quot;, &quot;Request count&quot;,),
+        (&quot;response&quot;, &quot;Response time&quot;,),
+        (&quot;slots&quot;, &quot;Slot count&quot;,),
+        (&quot;cpu&quot;, &quot;CPU time&quot;,),
+        (&quot;errors&quot;, &quot;Error count&quot;,),
+    ):
+        threshold = getattr(alerts, attr)
+        value = getattr(summary, attr)
+        if threshold is not None and value &gt; threshold:
+            if isinstance(value, float):
+                value = &quot;{:.1f}&quot;.format(value)
+            alert.append(&quot;{} threshold exceeded: {}&quot;.format(description, value))
+
+    if alert:
+        for _ignore in range(10):
+            print('\a', end='')
+            sys.stdout.flush()
+            time.sleep(0.15)
+        print(&quot;\n&quot;.join(alert))
+
+
+
</ins><span class="cx"> def usage(error_msg=None):
</span><span class="cx">     if error_msg:
</span><span class="cx">         print(error_msg)
</span><span class="lines">@@ -503,6 +554,17 @@
</span><span class="cx">     --agents      Include details about HTTP User-Agent usage
</span><span class="cx">     --dump FILE   File to dump JSON data to
</span><span class="cx"> 
</span><ins>+    --alert-requests N     Generate an alert if the overall request
+                            count exceeds a threshold [INT]
+    --alert-response N     Generate an alert if the overall average
+                            response time exceeds a threshold [INT]
+    --alert-slots N        Generate an alert if the overall slot
+                            count exceeds a threshold [FLOAT]
+    --alert-cpu N          Generate an alert if the overall average
+                            cpu percent use exceeds a threshold [INT]
+    --alert-errors N       Generate an alert if the overall error
+                            count exceeds a threshold [INT]
+
</ins><span class="cx"> Description:
</span><span class="cx">     This utility will print a summary of statistics read from a
</span><span class="cx">     server continuously with the specified delay.
</span><span class="lines">@@ -524,11 +586,21 @@
</span><span class="cx">     topUsers = 0
</span><span class="cx">     showAgents = False
</span><span class="cx">     dumpFile = None
</span><ins>+    alerts = SummaryValues(
+        requests=None,
+        response=None,
+        slots=None,
+        cpu=None,
+        errors=None,
+    )
</ins><span class="cx"> 
</span><span class="cx">     multimodes = ((&quot;current&quot;, 60,), (&quot;1m&quot;, 60,), (&quot;5m&quot;, 5 * 60,), (&quot;1h&quot;, 60 * 60,),)
</span><span class="cx">     multimode = multimodes[2]
</span><span class="cx"> 
</span><del>-    options, args = getopt.getopt(sys.argv[1:], &quot;hs:t:&quot;, [&quot;tcp=&quot;, &quot;0&quot;, &quot;1&quot;, &quot;5&quot;, &quot;60&quot;, &quot;methods&quot;, &quot;users=&quot;, &quot;agents&quot;, &quot;dump=&quot;])
</del><ins>+    options, args = getopt.getopt(sys.argv[1:], &quot;hs:t:&quot;, [
+        &quot;tcp=&quot;, &quot;0&quot;, &quot;1&quot;, &quot;5&quot;, &quot;60&quot;, &quot;methods&quot;, &quot;users=&quot;, &quot;agents&quot;, &quot;dump=&quot;,
+        &quot;alert-requests=&quot;, &quot;alert-response=&quot;, &quot;alert-slots=&quot;, &quot;alert-cpu=&quot;, &quot;alert-errors=&quot;,
+    ])
</ins><span class="cx"> 
</span><span class="cx">     for option, value in options:
</span><span class="cx">         if option == &quot;-h&quot;:
</span><span class="lines">@@ -556,14 +628,26 @@
</span><span class="cx">             showAgents = True
</span><span class="cx">         elif option == &quot;--dump&quot;:
</span><span class="cx">             dumpFile = value
</span><ins>+        elif option == &quot;--alert-requests&quot;:
+            alerts = alerts._replace(requests=int(value))
+        elif option == &quot;--alert-response&quot;:
+            alerts = alerts._replace(response=int(value))
+        elif option == &quot;--alert-slots&quot;:
+            alerts = alerts._replace(slots=float(value))
+        elif option == &quot;--alert-cpu&quot;:
+            alerts = alerts._replace(cpu=int(value))
+        elif option == &quot;--alert-errors&quot;:
+            alerts = alerts._replace(errors=int(value))
</ins><span class="cx"> 
</span><span class="cx">     while True:
</span><ins>+        now = time.time()
</ins><span class="cx">         stats = [readSock(server, useTCP) for server in servers]
</span><del>-        printStats(stats, multimode, showMethods, topUsers, showAgents, dumpFile)
</del><ins>+        summary = printStats(stats, multimode, showMethods, topUsers, showAgents, dumpFile)
</ins><span class="cx">         if dumpFile is not None:
</span><span class="cx">             stats = dict([(&quot;{}:{}&quot;.format(*servers[ctr]), stat) for ctr, stat in enumerate(stats)])
</span><span class="cx">             stats[&quot;timestamp&quot;] = datetime.datetime.now().strftime(&quot;%Y-%m-%dT%H:%M:%S&quot;)
</span><span class="cx">             with open(dumpFile, &quot;a&quot;) as f:
</span><span class="cx">                 f.write(json.dumps(stats))
</span><span class="cx">                 f.write(&quot;\n&quot;)
</span><del>-        time.sleep(delay)
</del><ins>+        alert(summary, alerts)
+        time.sleep(delay - (time.time() - now))
</ins></span></pre>
</div>
</div>

</body>
</html>