<!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 "Failed" in stats[0]:
</span><span class="cx"> printFailedStats(stats[0]["Failed"])
</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 = (("current", 60,), ("1m", 60,), ("5m", 5 * 60,), ("1h", 60 * 60,),)
</span><span class="cx"> multimode = multimodes[2]
</span><span class="cx">
</span><del>- options, args = getopt.getopt(sys.argv[1:], "hs:t:", ["tcp=", "0", "1", "5", "60", "methods", "users=", "agents"])
</del><ins>+ options, args = getopt.getopt(sys.argv[1:], "hs:t:", ["tcp=", "0", "1", "5", "60", "methods", "users=", "agents", "dump="])
</ins><span class="cx">
</span><span class="cx"> for option, value in options:
</span><span class="cx"> if option == "-h":
</span><span class="lines">@@ -552,7 +554,16 @@
</span><span class="cx"> topUsers = int(value)
</span><span class="cx"> elif option == "--agents":
</span><span class="cx"> showAgents = True
</span><ins>+ elif option == "--dump":
+ 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([("{}:{}".format(*servers[ctr]), stat) for ctr, stat in enumerate(stats)])
+ stats["timestamp"] = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
+ with open(dumpFile, "a") as f:
+ f.write(json.dumps(stats))
+ f.write("\n")
</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"> """
</span><span class="cx"> Analyze a readStats data file.
</span><span class="lines">@@ -34,17 +40,46 @@
</span><span class="cx"> """
</span><span class="cx">
</span><span class="cx"> print("Analyzing data for %s" % (title,))
</span><del>- dataset[title] = {}
- with open(fpath) as f:
- for line in f:
</del><ins>+ fpath_cached = fpath + ".cached"
+ 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("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"):
</span><del>- analyzeRecord(f, title)
</del><ins>+ analyzeTableFormat(f, title)
+ elif line.startswith("{"):
+ analyzeJSONFormat(f, line, title)
+ json = True
</ins><span class="cx">
</span><ins>+ if not json:
+ with open(fpath_cached, "w") as f:
+ f.write(dumps(dataset[title]))
+
</ins><span class="cx"> print("Read %d data points\n" % (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"> """
</span><ins>+ Analyze a "table" 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}
+ """
+ analyzeTableRecord(f, title)
+ for line in f:
+ if line.startswith("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -"):
+ analyzeTableRecord(f, title)
+
+
+def analyzeTableRecord(liter, title):
+ """
</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):
+ """
+ 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}
+ """
+ analyzeJSONRecord(first, title)
+ for line in f:
+ if line:
+ analyzeJSONRecord(line, title)
+
+
+def analyzeJSONRecord(line, title):
+ """
+ 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}
+ """
+
+ j = loads(line)
+
+ time = j["timestamp"][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 != "timestamp"]
+
+ analyzeJSONStatsSummary(allstats, title, seconds)
+ analyzeJSONStatsMethods(allstats, title, seconds)
+
+
+def analyzeJSONStatsSummary(allstats, title, seconds):
+ """
+ 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}
+ """
+
+ results = collections.defaultdict(list)
+ for stats in allstats:
+ stat = stats["1m"]
+
+ results["Requests"].append(stat["requests"])
+ results["Av. Requests per second"].append(safeDivision(float(stat["requests"]), 60.0))
+ results["Av. Response"].append(safeDivision(stat["t"], stat["requests"]))
+ results["Av. Response no write"].append(safeDivision(stat["t"] - stat["t-resp-wr"], stat["requests"]))
+ results["Max. Response"].append(stat["T-MAX"])
+ results["Slot Average"].append(safeDivision(float(stat["slots"]), stat["requests"]))
+ results["CPU Average"].append(safeDivision(stat["cpu"], stat["requests"]))
+ results["CPU Current"].append(stats["system"]["cpu use"])
+ results["Memory Current"].append(stats["system"]["memory percent"])
+ results["500's"].append(stat["500"])
+
+ for key in ("Requests", "Av. Requests per second", "500's",):
+ dataset[title][seconds]["Overall:{}".format(key)] = sum(results[key])
+
+ for key in ("Av. Response", "Av. Response no write", "Slot Average", "CPU Average", "CPU Current", "Memory Current",):
+ dataset[title][seconds]["Overall:{}".format(key)] = sum(results[key]) / len(allstats)
+
+ dataset[title][seconds]["Overall:Max. Response"] = max(results["Max. Response"])
+
+
+def analyzeJSONStatsMethods(allstats, title, seconds):
+ """
+ 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}
+ """
+
+ methods = collections.defaultdict(int)
+ method_times = collections.defaultdict(float)
+ response_average = {}
+ for stat in allstats:
+ for method in stat["1m"]["method"]:
+ methods[method] += stat["1m"]["method"][method]
+ if "method-t" in stat["1m"]:
+ for method_time in stat["1m"]["method-t"]:
+ method_times[method_time] += stat["1m"]["method-t"][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]["Method:{}:Count".format(method)] = count
+ dataset[title][seconds]["Method:{}:Count %".format(method)] = safeDivision(methods[method], total_count, 100.0)
+ dataset[title][seconds]["Method:{}:Av. Response".format(method)] = response_average[method]
+ dataset[title][seconds]["Method:{}:Av. Response %".format(method)] = safeDivision(response_average[method], total_avresponse, 100.0)
+ dataset[title][seconds]["Method:{}:Total Resp. %".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"> """
</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, "major", "x", alpha=0.5, linewidth=0.5)
+ plt.grid(True, "minor", "x", 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("stats_all.log"):
</del><ins>+ if name.startswith("stats_all.log") and not name.endswith(".cached"):
</ins><span class="cx"> print("Found file: %s" % (os.path.join(scanDir, name),))
</span><span class="cx"> trailer = name[len("stats_all.log"):]
</span><span class="cx"> if trailer.startswith("-"):
</span></span></pre>
</div>
</div>
</body>
</html>