<!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>[13779] CalendarServer/trunk/contrib/tools</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/13779">13779</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2014-07-21 12:28:13 -0700 (Mon, 21 Jul 2014)</dd>
</dl>

<h3>Log Message</h3>
<pre>Add option to write stats JSON data to a file. Enable stats analysis plotting tool to read the JSON data.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#CalendarServertrunkcontribtoolsreadStatspy">CalendarServer/trunk/contrib/tools/readStats.py</a></li>
<li><a href="#CalendarServertrunkcontribtoolsstatsanalysispy">CalendarServer/trunk/contrib/tools/statsanalysis.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 (13778 => 13779)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/contrib/tools/readStats.py        2014-07-21 19:26:20 UTC (rev 13778)
+++ CalendarServer/trunk/contrib/tools/readStats.py        2014-07-21 19:28:13 UTC (rev 13779)
</span><span class="lines">@@ -63,7 +63,7 @@
</span><span class="cx"> 
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-def printStats(stats, multimode, showMethods, topUsers, showAgents):
</del><ins>+def printStats(stats, multimode, showMethods, topUsers, showAgents, dumpFile):
</ins><span class="cx">     if len(stats) == 1:
</span><span class="cx">         if &quot;Failed&quot; in stats[0]:
</span><span class="cx">             printFailedStats(stats[0][&quot;Failed&quot;])
</span><span class="lines">@@ -501,6 +501,7 @@
</span><span class="cx">     --methods     Include details about HTTP method usage
</span><span class="cx">     --users N     Include details about top N users
</span><span class="cx">     --agents      Include details about HTTP User-Agent usage
</span><ins>+    --dump FILE   File to dump JSON data to
</ins><span class="cx"> 
</span><span class="cx"> Description:
</span><span class="cx">     This utility will print a summary of statistics read from a
</span><span class="lines">@@ -522,11 +523,12 @@
</span><span class="cx">     showMethods = False
</span><span class="cx">     topUsers = 0
</span><span class="cx">     showAgents = False
</span><ins>+    dumpFile = 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;])
</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;])
</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">@@ -552,7 +554,16 @@
</span><span class="cx">             topUsers = int(value)
</span><span class="cx">         elif option == &quot;--agents&quot;:
</span><span class="cx">             showAgents = True
</span><ins>+        elif option == &quot;--dump&quot;:
+            dumpFile = value
</ins><span class="cx"> 
</span><span class="cx">     while True:
</span><del>-        printStats([readSock(server, useTCP) for server in servers], multimode, showMethods, topUsers, showAgents)
</del><ins>+        stats = [readSock(server, useTCP) for server in servers]
+        printStats(stats, multimode, showMethods, topUsers, showAgents, dumpFile)
+        if dumpFile is not None:
+            stats = dict([(&quot;{}:{}&quot;.format(*servers[ctr]), stat) for ctr, stat in enumerate(stats)])
+            stats[&quot;timestamp&quot;] = datetime.datetime.now().strftime(&quot;%Y-%m-%dT%H:%M:%S&quot;)
+            with open(dumpFile, &quot;a&quot;) as f:
+                f.write(json.dumps(stats))
+                f.write(&quot;\n&quot;)
</ins><span class="cx">         time.sleep(delay)
</span></span></pre></div>
<a id="CalendarServertrunkcontribtoolsstatsanalysispy"></a>
<div class="modfile"><h4>Modified: CalendarServer/trunk/contrib/tools/statsanalysis.py (13778 => 13779)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/contrib/tools/statsanalysis.py        2014-07-21 19:26:20 UTC (rev 13778)
+++ CalendarServer/trunk/contrib/tools/statsanalysis.py        2014-07-21 19:28:13 UTC (rev 13779)
</span><span class="lines">@@ -16,6 +16,9 @@
</span><span class="cx"> ##
</span><span class="cx"> from __future__ import print_function
</span><span class="cx"> 
</span><ins>+from json import dumps, loads
+from matplotlib.ticker import AutoMinorLocator
+import collections
</ins><span class="cx"> import getopt
</span><span class="cx"> import matplotlib.pyplot as plt
</span><span class="cx"> import os
</span><span class="lines">@@ -23,6 +26,9 @@
</span><span class="cx"> 
</span><span class="cx"> dataset = {}
</span><span class="cx"> 
</span><ins>+def safeDivision(value, total, factor=1):
+    return value * factor / total if total else 0
+
</ins><span class="cx"> def analyze(fpath, title):
</span><span class="cx">     &quot;&quot;&quot;
</span><span class="cx">     Analyze a readStats data file.
</span><span class="lines">@@ -34,17 +40,46 @@
</span><span class="cx">     &quot;&quot;&quot;
</span><span class="cx"> 
</span><span class="cx">     print(&quot;Analyzing data for %s&quot; % (title,))
</span><del>-    dataset[title] = {}
-    with open(fpath) as f:
-        for line in f:
</del><ins>+    fpath_cached = fpath + &quot;.cached&quot;
+    if os.path.exists(fpath_cached):
+        with open(fpath_cached) as f:
+            d = loads(f.read())
+        dataset[title] = dict([(int(k), v) for k, v in d.items()])
+    else:
+        dataset[title] = {}
+        json = False
+        with open(fpath) as f:
+            line = f.next()
</ins><span class="cx">             if line.startswith(&quot;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -&quot;):
</span><del>-                analyzeRecord(f, title)
</del><ins>+                analyzeTableFormat(f, title)
+            elif line.startswith(&quot;{&quot;):
+                analyzeJSONFormat(f, line, title)
+                json = True
</ins><span class="cx"> 
</span><ins>+        if not json:
+            with open(fpath_cached, &quot;w&quot;) as f:
+                f.write(dumps(dataset[title]))
+
</ins><span class="cx">     print(&quot;Read %d data points\n&quot; % (len(dataset[title]),))
</span><span class="cx"> 
</span><span class="cx"> 
</span><del>-def analyzeRecord(liter, title):
</del><ins>+def analyzeTableFormat(f, title):
</ins><span class="cx">     &quot;&quot;&quot;
</span><ins>+    Analyze a &quot;table&quot; format output file. First line has already been tested.
+
+    @param f: file object to read
+    @type f: L{File}
+    @param title: title to use for data set
+    @type title: L{str}
+    &quot;&quot;&quot;
+    analyzeTableRecord(f, title)
+    for line in f:
+        if line.startswith(&quot;- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -&quot;):
+            analyzeTableRecord(f, title)
+
+
+def analyzeTableRecord(liter, title):
+    &quot;&quot;&quot;
</ins><span class="cx">     Analyze one entry from the readStats data file.
</span><span class="cx"> 
</span><span class="cx">     @param liter: iterator over lines in the file
</span><span class="lines">@@ -125,6 +160,114 @@
</span><span class="cx">     return methods
</span><span class="cx"> 
</span><span class="cx"> 
</span><ins>+def analyzeJSONFormat(f, first, title):
+    &quot;&quot;&quot;
+    Analyze a JSON format output file. First line has already been tested.
+
+    @param f: file object to read
+    @type f: L{File}
+    @param title: title to use for data set
+    @type title: L{str}
+    &quot;&quot;&quot;
+    analyzeJSONRecord(first, title)
+    for line in f:
+        if line:
+            analyzeJSONRecord(line, title)
+
+
+def analyzeJSONRecord(line, title):
+    &quot;&quot;&quot;
+    Analyze a JSON record.
+    
+    @param line: line of JSON data to parse
+    @type line: L{str}
+    @param title: title to use for data set
+    @type title: L{str}
+    &quot;&quot;&quot;
+
+    j = loads(line)
+
+    time = j[&quot;timestamp&quot;][11:]
+    seconds = 60 * (60 * int(time[0:2]) + int(time[3:5])) + int(time[6:8])
+    dataset[title][seconds] = {}
+
+    allstats = [stat for server, stat in j.items() if server != &quot;timestamp&quot;]
+
+    analyzeJSONStatsSummary(allstats, title, seconds)
+    analyzeJSONStatsMethods(allstats, title, seconds)
+
+
+def analyzeJSONStatsSummary(allstats, title, seconds):
+    &quot;&quot;&quot;
+    Analyze all server JSON summary stats.
+
+    @param allstats: set of JSON stats to analyze
+    @type allstats: L{dict}
+    @param title: title to use for data set
+    @type title: L{str}
+    @param seconds: timestamp for stats record
+    @type seconds: L{int}
+    &quot;&quot;&quot;
+
+    results = collections.defaultdict(list)
+    for stats in allstats:
+        stat = stats[&quot;1m&quot;]
+
+        results[&quot;Requests&quot;].append(stat[&quot;requests&quot;])
+        results[&quot;Av. Requests per second&quot;].append(safeDivision(float(stat[&quot;requests&quot;]), 60.0))
+        results[&quot;Av. Response&quot;].append(safeDivision(stat[&quot;t&quot;], stat[&quot;requests&quot;]))
+        results[&quot;Av. Response no write&quot;].append(safeDivision(stat[&quot;t&quot;] - stat[&quot;t-resp-wr&quot;], stat[&quot;requests&quot;]))
+        results[&quot;Max. Response&quot;].append(stat[&quot;T-MAX&quot;])
+        results[&quot;Slot Average&quot;].append(safeDivision(float(stat[&quot;slots&quot;]), stat[&quot;requests&quot;]))
+        results[&quot;CPU Average&quot;].append(safeDivision(stat[&quot;cpu&quot;], stat[&quot;requests&quot;]))
+        results[&quot;CPU Current&quot;].append(stats[&quot;system&quot;][&quot;cpu use&quot;])
+        results[&quot;Memory Current&quot;].append(stats[&quot;system&quot;][&quot;memory percent&quot;])
+        results[&quot;500's&quot;].append(stat[&quot;500&quot;])
+
+    for key in (&quot;Requests&quot;, &quot;Av. Requests per second&quot;, &quot;500's&quot;,):
+        dataset[title][seconds][&quot;Overall:{}&quot;.format(key)] = sum(results[key])
+
+    for key in (&quot;Av. Response&quot;, &quot;Av. Response no write&quot;, &quot;Slot Average&quot;, &quot;CPU Average&quot;, &quot;CPU Current&quot;, &quot;Memory Current&quot;,):
+        dataset[title][seconds][&quot;Overall:{}&quot;.format(key)] = sum(results[key]) / len(allstats)
+
+    dataset[title][seconds][&quot;Overall:Max. Response&quot;] = max(results[&quot;Max. Response&quot;])
+
+
+def analyzeJSONStatsMethods(allstats, title, seconds):
+    &quot;&quot;&quot;
+    Analyze all server JSON method stats.
+
+    @param allstats: set of JSON stats to analyze
+    @type allstats: L{dict}
+    @param title: title to use for data set
+    @type title: L{str}
+    @param seconds: timestamp for stats record
+    @type seconds: L{int}
+    &quot;&quot;&quot;
+
+    methods = collections.defaultdict(int)
+    method_times = collections.defaultdict(float)
+    response_average = {}
+    for stat in allstats:
+        for method in stat[&quot;1m&quot;][&quot;method&quot;]:
+            methods[method] += stat[&quot;1m&quot;][&quot;method&quot;][method]
+        if &quot;method-t&quot; in stat[&quot;1m&quot;]:
+            for method_time in stat[&quot;1m&quot;][&quot;method-t&quot;]:
+                method_times[method_time] += stat[&quot;1m&quot;][&quot;method-t&quot;][method_time]
+                response_average[method_time] = method_times[method_time] / methods[method_time]
+
+    total_count = sum(methods.values())
+    total_avresponse = sum(response_average.values())
+    total_response = sum(method_times.values())
+
+    for method, count in methods.items():
+        dataset[title][seconds][&quot;Method:{}:Count&quot;.format(method)] = count
+        dataset[title][seconds][&quot;Method:{}:Count %&quot;.format(method)] = safeDivision(methods[method], total_count, 100.0)
+        dataset[title][seconds][&quot;Method:{}:Av. Response&quot;.format(method)] = response_average[method]
+        dataset[title][seconds][&quot;Method:{}:Av. Response %&quot;.format(method)] = safeDivision(response_average[method], total_avresponse, 100.0)
+        dataset[title][seconds][&quot;Method:{}:Total Resp. %&quot;.format(method)] = safeDivision(method_times[method], total_response, 100.0)
+
+
</ins><span class="cx"> def plotSeries(key, ymin=None, ymax=None):
</span><span class="cx">     &quot;&quot;&quot;
</span><span class="cx">     Plot the chosen dataset key for each scanned data file.
</span><span class="lines">@@ -155,6 +298,10 @@
</span><span class="cx">         (1, 4, 7, 10, 13, 16, 19, 22,),
</span><span class="cx">         (18, 21, 0, 3, 6, 9, 12, 15,),
</span><span class="cx">     )
</span><ins>+    plt.minorticks_on()
+    plt.gca().xaxis.set_minor_locator(AutoMinorLocator(n=3))
+    plt.grid(True, &quot;major&quot;, &quot;x&quot;, alpha=0.5, linewidth=0.5)
+    plt.grid(True, &quot;minor&quot;, &quot;x&quot;, alpha=0.5, linewidth=0.5)
</ins><span class="cx">     plt.legend(titles, 'upper left', shadow=True, fancybox=True)
</span><span class="cx">     plt.show()
</span><span class="cx"> 
</span><span class="lines">@@ -202,7 +349,7 @@
</span><span class="cx">     fnames = os.listdir(scanDir)
</span><span class="cx">     count = 1
</span><span class="cx">     for name in fnames:
</span><del>-        if name.startswith(&quot;stats_all.log&quot;):
</del><ins>+        if name.startswith(&quot;stats_all.log&quot;) and not name.endswith(&quot;.cached&quot;):
</ins><span class="cx">             print(&quot;Found file: %s&quot; % (os.path.join(scanDir, name),))
</span><span class="cx">             trailer = name[len(&quot;stats_all.log&quot;):]
</span><span class="cx">             if trailer.startswith(&quot;-&quot;):
</span></span></pre>
</div>
</div>

</body>
</html>