<!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>[15374] CalendarServer/trunk/calendarserver/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/15374">15374</a></dd>
<dt>Author</dt> <dd>cdaboo@apple.com</dd>
<dt>Date</dt> <dd>2015-12-09 18:38:53 -0800 (Wed, 09 Dec 2015)</dd>
</dl>

<h3>Log Message</h3>
<pre>New set of dashboard tools that implement a multi-pod/multi-server stats aggregator and service and a curses based tool to view the aggregator data.</pre>

<h3>Added Paths</h3>
<ul>
<li><a href="#CalendarServertrunkcalendarservertoolsdashcollectpy">CalendarServer/trunk/calendarserver/tools/dashcollect.py</a></li>
<li><a href="#CalendarServertrunkcalendarservertoolsdashviewpy">CalendarServer/trunk/calendarserver/tools/dashview.py</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="CalendarServertrunkcalendarservertoolsdashcollectpy"></a>
<div class="addfile"><h4>Added: CalendarServer/trunk/calendarserver/tools/dashcollect.py (0 => 15374)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/calendarserver/tools/dashcollect.py                                (rev 0)
+++ CalendarServer/trunk/calendarserver/tools/dashcollect.py        2015-12-10 02:38:53 UTC (rev 15374)
</span><span class="lines">@@ -0,0 +1,373 @@
</span><ins>+#!/usr/bin/env python
+##
+# Copyright (c) 2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+from collections import OrderedDict
+from datetime import datetime, date
+from threading import Thread
+import SocketServer
+import argparse
+import errno
+import json
+import os
+import sched
+import socket
+import sys
+import time
+
+&quot;&quot;&quot;
+A service that logs dashboard data from multiple hosts and stores them in
+log files. It can also, optionally, make the most recent data available
+for retrieval via a simple TCP socket read on a specific port.
+&quot;&quot;&quot;
+
+&quot;&quot;&quot;
+JSON schema for servers file:
+
+; root object
+OBJECT (title, pods)
+
+; Title/description of this config
+MEMBER title &quot;title&quot; : STRING
+
+; pods - set of pods to monitor
+MEMBER pods &quot;pod&quot; : Object (
+    *pod
+)
+
+; An event type
+MEMBER pod &quot;&quot; : Object(
+    ?description, servers
+)
+
+; The description of a pod
+MEMBER description &quot;description&quot; : STRING
+
+; Servers associated with a pod
+; Server names are either &quot;host:port&quot;, or &quot;unix:path&quot;
+MEMBER servers &quot;servers&quot; : ARRAY STRING
+
+Example:
+{
+    &quot;title&quot;: &quot;My CalDAV service&quot;,
+    &quot;pods&quot;: {
+        &quot;podA&quot;: {
+            &quot;description&quot;: &quot;Main pod&quot;,
+            &quot;servers&quot;: [
+                &quot;podAhost1.example.com:8100&quot;,
+                &quot;podAhost2.example.com:8100&quot;
+            ]
+        },
+        &quot;podB&quot;: {
+            &quot;description&quot;: &quot;Development pod&quot;,
+            &quot;servers&quot;: [
+                &quot;podBhost1.example.com:8100&quot;,
+                &quot;podBhost2.example.com:8100&quot;
+            ]
+        }
+    }
+}
+&quot;&quot;&quot;
+
+verbose = False
+def _verbose(log):
+    if verbose:
+        print(log)
+
+
+
+def main():
+    parser = argparse.ArgumentParser(description=&quot;Dashboard service for CalendarServer.&quot;)
+    parser.add_argument(&quot;-f&quot;, help=&quot;Server config file&quot;)
+    parser.add_argument(&quot;-l&quot;, help=&quot;Log file directory&quot;)
+    parser.add_argument(&quot;-n&quot;, action=&quot;store_true&quot;, help=&quot;New log file&quot;)
+    parser.add_argument(&quot;-s&quot;, type=int, help=&quot;Run the dash_thread service on the specified port&quot;)
+    parser.add_argument(&quot;-v&quot;, action=&quot;store_true&quot;, help=&quot;Verbose&quot;)
+    args = parser.parse_args()
+    if args.v:
+        global verbose
+        verbose = True
+
+    config = Config()
+    try:
+        config.loadFromFile(args.f)
+    except:
+        parser.print_usage()
+        sys.exit(1)
+
+    # Remove any existing logfile is asked
+    if args.n:
+        logfile = DashboardCollector.logfile(args.l)
+        if os.path.exists(logfile):
+            os.remove(logfile)
+
+    print(&quot;Running DashboardCollector...&quot;)
+    dash = DashboardCollector(config, args.l)
+    dash_thread = Thread(target=dash.run)
+    dash_thread.start()
+
+    if args.s:
+        print(&quot;Running the CollectorService...&quot;)
+        server = CollectorService((&quot;localhost&quot;, args.s), CollectorRequestHandler)
+        server.dashboard = dash
+        server_thread = Thread(target=server.serve_forever)
+        server_thread.daemon = True
+        server_thread.start()
+
+    dash_thread.join()
+
+
+
+class Config(object):
+    &quot;&quot;&quot;
+    Loads the config and creates a list of L{Pod}'s.
+    &quot;&quot;&quot;
+
+    def loadFromFile(self, path):
+        _verbose(&quot;Loading config file {}&quot;.format(path))
+        with open(path) as f:
+            try:
+                jsondata = json.loads(f.read(), object_pairs_hook=OrderedDict)
+            except Exception:
+                raise RuntimeError(&quot;Could not read JSON data from {}&quot;.format(path))
+
+        try:
+            self.title = jsondata[&quot;title&quot;]
+            _verbose(&quot;Config '{}'&quot;.format(self.title))
+            self.pods = [Pod(podname, data) for podname, data in jsondata[&quot;pods&quot;].items()]
+        except Exception:
+            raise RuntimeError(&quot;No valid JSON data in {}&quot;.format(path))
+
+
+
+class Pod(object):
+    &quot;&quot;&quot;
+    Model object that represents an L{Pod}.
+    &quot;&quot;&quot;
+
+    def __init__(self, title, jsondata):
+        &quot;&quot;&quot;
+        Parse the pod details from the JSON data and create the list of L{Server}'s.
+        &quot;&quot;&quot;
+        self.title = title
+        self.description = jsondata.get(&quot;description&quot;, &quot;&quot;)
+        _verbose(&quot;  Pod '{}': {}&quot;.format(self.title, self.description))
+        self.servers = [Server(data) for data in jsondata.get(&quot;servers&quot;, [])]
+
+        # Setup each L{Server} with the set of stats items they need to read
+        for ctr, server in enumerate(self.servers):
+            _verbose(&quot;    Server: {}&quot;.format(server.sockname))
+            server.addItem(&quot;stats_system&quot;)
+            server.addItem(&quot;stats&quot;)
+            server.addItem(&quot;slots&quot;)
+            server.addItem(&quot;job_assignments&quot;)
+            server.addItem(&quot;jobcount&quot;)
+            server.addItem(&quot;directory&quot;)
+
+            # Only read this once as otherwise too much load
+            if ctr == 0:
+                server.addItem(&quot;jobs&quot;)
+
+
+    def update(self, data):
+        &quot;&quot;&quot;
+        Update the data for each L{Server} in this L{Pod}.
+        &quot;&quot;&quot;
+        _verbose(&quot;  Pod: {}&quot;.format(self.title))
+        data[self.title] = OrderedDict()
+        for server in self.servers:
+            server.update(data[self.title])
+
+
+
+class Server(object):
+    &quot;&quot;&quot;
+    Model object that represents a server in a pod.
+    &quot;&quot;&quot;
+    def __init__(self, host):
+        &quot;&quot;&quot;
+        Setup the appropriate socket connection details.
+        &quot;&quot;&quot;
+        self.host = host
+        self.socket = None
+        if host.startswith(&quot;unix:&quot;):
+            self.sockname = host[5:]
+            self.useTCP = False
+        else:
+            host = host.split(&quot;:&quot;)
+            if len(host) == 1:
+                host.append(8100)
+            else:
+                host[1] = int(host[1])
+            self.sockname = tuple(host)
+            self.useTCP = True
+        self.currentData = {}
+        self.items = []
+
+
+    def readSock(self, items):
+        &quot;&quot;&quot;
+        Open a socket, send the specified request, and retrieve the response. Keep the socket open.
+        &quot;&quot;&quot;
+        try:
+            if self.socket is None:
+                self.socket = socket.socket(socket.AF_INET if self.useTCP else socket.AF_UNIX, socket.SOCK_STREAM)
+                self.socket.connect(self.sockname)
+                self.socket.setblocking(0)
+            self.socket.sendall(json.dumps(items) + &quot;\r\n&quot;)
+            data = &quot;&quot;
+            t = time.time()
+            while not data.endswith(&quot;\n&quot;):
+                try:
+                    d = self.socket.recv(1024)
+                except socket.error as se:
+                    if se.args[0] != errno.EWOULDBLOCK:
+                        raise
+                    if time.time() - t &gt; 5:
+                        raise socket.error
+                    continue
+                if d:
+                    data += d
+                else:
+                    break
+            data = json.loads(data, object_pairs_hook=OrderedDict)
+        except socket.error:
+            data = {}
+            self.socket = None
+        except ValueError:
+            data = {}
+        return data
+
+
+    def update(self, data):
+        &quot;&quot;&quot;
+        Update the current data from the server.
+        &quot;&quot;&quot;
+
+        # Only read each item once
+        self.currentData = self.readSock(list(set(self.items)))
+        data[self.host] = self.currentData
+        _verbose(&quot;    Server: {}&quot;.format(self.host))
+        _verbose(&quot;      Data: {}&quot;.format(self.currentData))
+
+
+    def getOneItem(self, item):
+        &quot;&quot;&quot;
+        Update the current data from the server.
+        &quot;&quot;&quot;
+        data = self.readSock([item])
+        return data[item] if data else None
+
+
+    def addItem(self, item):
+        &quot;&quot;&quot;
+        Add a server data item to monitor.
+        &quot;&quot;&quot;
+        self.items.append(item)
+
+
+    def removeItem(self, item):
+        &quot;&quot;&quot;
+        No need to monitor this item.
+        &quot;&quot;&quot;
+        try:
+            self.items.remove(item)
+        except ValueError:
+            # Don't care if the item is not present
+            pass
+
+
+
+class DashboardCollector(object):
+    &quot;&quot;&quot;
+    Main dashboard controller. Use Python's L{sched} feature to schedule
+    updates.
+    &quot;&quot;&quot;
+
+    def __init__(self, config, logdir):
+        self.logdir = logdir
+        self.title = config.title
+        self.pods = config.pods
+        self.sched = sched.scheduler(time.time, time.sleep)
+        self.seconds = 1
+        self.lastData = {}
+
+
+    def run(self):
+        &quot;&quot;&quot;
+        Start the L{scheduler}.
+        &quot;&quot;&quot;
+        _verbose(&quot;Starting Dashboard&quot;)
+        self.sched.enter(self.seconds, 0, self.update, ())
+        self.sched.run()
+
+
+    @staticmethod
+    def logfile(logdir):
+        &quot;&quot;&quot;
+        Log file name based on current date so it rotates once a day.
+        &quot;&quot;&quot;
+        return os.path.join(logdir, &quot;dashboard-{}.log&quot;.format(date.today().isoformat()))
+
+
+    def update(self):
+        &quot;&quot;&quot;
+        Update data from each pod.
+        &quot;&quot;&quot;
+
+        _verbose(&quot;Update pods&quot;)
+        j = OrderedDict()
+        j[&quot;timestamp&quot;] = datetime.now().replace(microsecond=0).isoformat()
+        j[&quot;pods&quot;] = OrderedDict()
+
+        for pod in self.pods:
+            pod.update(j[&quot;pods&quot;])
+
+        # Append to log file
+        with open(self.logfile(self.logdir), &quot;a&quot;) as f:
+            f.write(&quot;\x1e{}\n&quot;.format(json.dumps(j)))
+
+        self.lastData = j
+
+        self.sched.enter(self.seconds, 0, self.update, ())
+
+
+
+class CollectorService(SocketServer.ThreadingTCPServer):
+    &quot;&quot;&quot;
+    L{ThreadingTCPServer} that sends out the current data from
+    the L{DashbordCollector}.
+    &quot;&quot;&quot;
+
+    def data(self):
+        if hasattr(self, &quot;dashboard&quot;):
+            return json.dumps(self.dashboard.lastData)
+        else:
+            return &quot;{}&quot;
+
+
+
+class CollectorRequestHandler(SocketServer.BaseRequestHandler):
+    &quot;&quot;&quot;
+    Request handler for L{CollectorService} that just sends back the current dat.
+    &quot;&quot;&quot;
+
+    def handle(self):
+        self.request.sendall(self.server.data())
+
+
+if __name__ == &quot;__main__&quot;:
+    main()
</ins><span class="cx">Property changes on: CalendarServer/trunk/calendarserver/tools/dashcollect.py
</span><span class="cx">___________________________________________________________________
</span></span></pre></div>
<a id="svnexecutable"></a>
<div class="addfile"><h4>Added: svn:executable</h4></div>
<a id="CalendarServertrunkcalendarservertoolsdashviewpy"></a>
<div class="addfile"><h4>Added: CalendarServer/trunk/calendarserver/tools/dashview.py (0 => 15374)</h4>
<pre class="diff"><span>
<span class="info">--- CalendarServer/trunk/calendarserver/tools/dashview.py                                (rev 0)
+++ CalendarServer/trunk/calendarserver/tools/dashview.py        2015-12-10 02:38:53 UTC (rev 15374)
</span><span class="lines">@@ -0,0 +1,1219 @@
</span><ins>+#!/usr/bin/env python
+##
+# Copyright (c) 2012-2015 Apple Inc. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+##
+
+&quot;&quot;&quot;
+A curses (or plain text) based dashboard for viewing various aspects of the
+server as exposed by the L{DashboardProtocol} stats socket.
+&quot;&quot;&quot;
+
+import argparse
+import collections
+import curses.panel
+import errno
+import fcntl
+import json
+import logging
+import sched
+import socket
+import struct
+import sys
+import termios
+import time
+
+LOG_FILENAME = 'db.log'
+#logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
+
+
+
+def main():
+    parser = argparse.ArgumentParser(description=&quot;Dashboard collector viewer service for CalendarServer.&quot;)
+    parser.add_argument(&quot;-s&quot;, default=[&quot;localhost:8200&quot;], help=&quot;Dashboard collector service host:port&quot;)
+    args = parser.parse_args()
+
+    #
+    # Get configuration
+    #
+    servers = []
+    for server in args.s:
+        if not server.startswith(&quot;unix:&quot;):
+            server = server.split(&quot;:&quot;)
+            if len(server) == 1:
+                server.append(8100)
+            else:
+                server[1] = int(server[1])
+            servers.append(tuple(server))
+        else:
+            servers.append(server)
+
+
+    def _wrapped(stdscrn):
+        curses.curs_set(0)
+        curses.use_default_colors()
+        curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)
+        d = Dashboard(servers, stdscrn)
+        d.run()
+    curses.wrapper(_wrapped)
+
+
+
+def safeDivision(value, total, factor=1):
+    return value * factor / total if total else 0
+
+
+
+def defaultIfNone(x, default):
+    return x if x is not None else default
+
+
+
+def terminal_size():
+    h, w, _ignore_hp, _ignore_wp = struct.unpack(
+        'HHHH',
+        fcntl.ioctl(
+            0, termios.TIOCGWINSZ,
+            struct.pack('HHHH', 0, 0, 0, 0)
+        )
+    )
+    return w, h
+
+
+
+class Dashboard(object):
+    &quot;&quot;&quot;
+    Main dashboard controller. Use Python's L{sched} feature to schedule
+    updates.
+    &quot;&quot;&quot;
+
+    screen = None
+    registered_windows = collections.OrderedDict()
+    registered_window_sets = {
+        &quot;H&quot;: (&quot;HTTP Panels&quot;, [],),
+        &quot;J&quot;: (&quot;Jobs Panels&quot;, [],),
+    }
+
+    def __init__(self, servers, screen):
+        self.screen = screen
+        self.paused = False
+        self.seconds = 1.0
+        self.sched = sched.scheduler(time.time, time.sleep)
+
+        self.servers = servers
+        self.selected_server = Point()
+        self.server_window = None
+
+        self.client = DashboardClient(servers[0])
+        self.client_error = False
+
+
+    @classmethod
+    def registerWindow(cls, wtype, keypress):
+        &quot;&quot;&quot;
+        Register a window type along with a key press action. This allows the
+        controller to select the appropriate window when its key is pressed,
+        and also provides help information to the L{HelpWindow} for each
+        available window type.
+        &quot;&quot;&quot;
+        cls.registered_windows[keypress] = wtype
+
+
+    @classmethod
+    def registerWindowSet(cls, wtype, keypress):
+        &quot;&quot;&quot;
+        Register a set of window types along with a key press action. This allows the
+        controller to select the appropriate set of windows when its key is pressed,
+        and also provides help information to the L{HelpWindow} for each
+        available window set type.
+        &quot;&quot;&quot;
+        cls.registered_window_sets[keypress][1].append(wtype)
+
+
+    def run(self):
+        &quot;&quot;&quot;
+        Create the initial window and run the L{scheduler}.
+        &quot;&quot;&quot;
+        self.windows = []
+        self.displayWindow(None)
+        self.sched.enter(self.seconds, 0, self.updateDisplay, ())
+        self.sched.run()
+
+
+    def displayWindow(self, wtype):
+        &quot;&quot;&quot;
+        Toggle the specified window, or reset to launch state if None.
+        &quot;&quot;&quot;
+
+        # Toggle a specific window on or off
+        if isinstance(wtype, type):
+            if wtype not in [type(w) for w in self.windows]:
+                self.windows.append(wtype(self).makeWindow())
+                self.windows[-1].activate()
+            else:
+                for window in self.windows:
+                    if type(window) == wtype:
+                        window.deactivate()
+                        self.windows.remove(window)
+                    if len(self.windows) == 0:
+                        self.displayWindow(self.registered_windows[&quot;h&quot;])
+
+            self.resetWindows()
+
+        # Reset the screen to the default config
+        else:
+            if self.windows:
+                for window in self.windows:
+                    window.deactivate()
+                self.windows = []
+            top = 0
+
+            self.server_window = ServersMenu(self).makeWindow()
+            self.windows.append(self.server_window)
+            self.windows[-1].activate()
+            top += self.windows[-1].nlines + 1
+            help_top = top
+
+            if wtype is None:
+                # All windows in registered order
+                ordered_windows = self.registered_windows.values()
+            else:
+                ordered_windows = list(wtype)
+            for wtype in filter(lambda x: x.all, ordered_windows):
+                new_win = wtype(self).makeWindow(top=top)
+                logging.debug('created %r at panel level %r' % (new_win, new_win.z_order))
+                self.windows.append(wtype(self).makeWindow(top=top))
+                self.windows[-1].activate()
+                top += self.windows[-1].nlines + 1
+
+            # Don't display help panel if the window is too narrow
+            term_w, term_h = terminal_size()
+            logging.debug(&quot;HelpWindow: rows: %s  cols: %s&quot; % (term_h, term_w))
+            if int(term_w) &gt; 100:
+                logging.debug('HelpWindow: term_w &gt; 100, making window with top at %d' % (top))
+                self.windows.append(HelpWindow(self).makeWindow(top=help_top))
+                self.windows[-1].activate()
+
+        curses.panel.update_panels()
+        self.updateDisplay(True)
+
+
+    def resetWindows(self):
+        &quot;&quot;&quot;
+        Reset the current set of windows.
+        &quot;&quot;&quot;
+        if self.windows:
+            logging.debug('resetting windows: %r' % (self.windows))
+            for window in self.windows:
+                window.deactivate()
+            old_windows = self.windows
+            self.windows = []
+            top = 0
+            for old in old_windows:
+                logging.debug('processing window of type %r' % (type(old)))
+                self.windows.append(old.__class__(self).makeWindow(top=top))
+                self.windows[-1].activate()
+                # Allow the help window to float on the right edge
+                if old.__class__.__name__ != &quot;HelpWindow&quot;:
+                    top += self.windows[-1].nlines + 1
+
+
+    def updateDisplay(self, initialUpdate=False):
+        &quot;&quot;&quot;
+        Periodic update of the current window and check for a key press.
+        &quot;&quot;&quot;
+        self.client.update()
+        client_error = len(self.client.currentData) == 0
+        if client_error ^ self.client_error:
+            self.client_error = client_error
+            self.resetWindows()
+        elif filter(lambda x: x.requiresReset(), self.windows):
+            self.resetWindows()
+
+        try:
+            if not self.paused or initialUpdate:
+                for window in filter(
+                    lambda x: x.requiresUpdate() or initialUpdate,
+                    self.windows
+                ):
+                    window.update()
+        except Exception as e:
+            logging.debug(&quot;updateDisplay failed: {}&quot;.format(e))
+            pass
+
+        # Check keystrokes
+        self.processKeys()
+
+        if not initialUpdate:
+            self.sched.enter(self.seconds, 0, self.updateDisplay, ())
+
+
+    def processKeys(self):
+        &quot;&quot;&quot;
+        Check for a key press.
+        &quot;&quot;&quot;
+        try:
+            self.windows[-1].window.keypad(1)
+            c = self.windows[-1].window.getkey()
+        except:
+            c = -1
+        if c == &quot;q&quot;:
+            sys.exit(0)
+        elif c == &quot; &quot;:
+            self.paused = not self.paused
+        elif c == &quot;t&quot;:
+            self.seconds = 1.0 if self.seconds == 0.1 else 0.1
+        elif c == &quot;a&quot;:
+            self.displayWindow(None)
+        elif c == &quot;n&quot;:
+            if self.windows:
+                for window in self.windows:
+                    window.deactivate()
+                self.windows = []
+                self.displayWindow(self.registered_windows[&quot;h&quot;])
+
+        elif c in self.registered_windows:
+            self.displayWindow(self.registered_windows[c])
+
+        elif c in self.registered_window_sets:
+            self.displayWindow(self.registered_window_sets[c][1])
+
+        elif c in (curses.keyname(curses.KEY_LEFT), curses.keyname(curses.KEY_RIGHT)) and self.server_window:
+            self.selected_server.xplus(-1 if c == curses.keyname(curses.KEY_LEFT) else 1)
+            if self.selected_server.x &lt; 0:
+                self.selected_server.x = 0
+            elif self.selected_server.x &gt;= len(self.serversForPod(self.pods()[self.selected_server.y])):
+                self.selected_server.x = len(self.serversForPod(self.pods()[self.selected_server.y])) - 1
+            self.resetWindows()
+
+        elif c in (curses.keyname(curses.KEY_UP), curses.keyname(curses.KEY_DOWN)) and self.server_window:
+            self.selected_server.yplus(-1 if c == curses.keyname(curses.KEY_UP) else 1)
+            if self.selected_server.y &lt; 0:
+                self.selected_server.y = 0
+            elif self.selected_server.y &gt;= len(self.pods()):
+                self.selected_server.y = len(self.pods()) - 1
+            if self.selected_server.x &gt;= len(self.serversForPod(self.pods()[self.selected_server.y])):
+                self.selected_server.x = len(self.serversForPod(self.pods()[self.selected_server.y])) - 1
+            self.resetWindows()
+
+
+    def dataForItem(self, item):
+        return self.client.getOneItem(
+            self.selectedPod(),
+            self.selectedServer(),
+            item,
+        )
+
+
+    def pods(self):
+        self.client.update()
+        return self.client.currentData[&quot;pods&quot;].keys()
+
+
+    def selectedPod(self):
+        return self.pods()[self.selected_server.y]
+
+
+    def serversForPod(self, pod):
+        self.client.update()
+        return self.client.currentData[&quot;pods&quot;][pod].keys()
+
+
+    def selectedServer(self):
+        return self.serversForPod(self.selectedPod())[self.selected_server.x]
+
+
+
+class DashboardClient(object):
+    &quot;&quot;&quot;
+    Client that connects to a server and fetches information.
+    &quot;&quot;&quot;
+
+    def __init__(self, sockname):
+        self.socket = None
+        if isinstance(sockname, str):
+            self.sockname = sockname[5:]
+            self.useTCP = False
+        else:
+            self.sockname = sockname
+            self.useTCP = True
+        self.currentData = {}
+
+
+    def readSock(self):
+        &quot;&quot;&quot;
+        Open a socket, send the specified request, and retrieve the response. The socket closes.
+        &quot;&quot;&quot;
+        try:
+            self.socket = socket.socket(socket.AF_INET if self.useTCP else socket.AF_UNIX, socket.SOCK_STREAM)
+            self.socket.connect(self.sockname)
+            self.socket.setblocking(0)
+            data = &quot;&quot;
+            t = time.time()
+            while not data.endswith(&quot;\n&quot;):
+                try:
+                    d = self.socket.recv(1024)
+                except socket.error as se:
+                    if se.args[0] != errno.EWOULDBLOCK:
+                        raise
+                    if time.time() - t &gt; 5:
+                        raise socket.error
+                    continue
+                if d:
+                    data += d
+                else:
+                    break
+            data = json.loads(data, object_pairs_hook=collections.OrderedDict)
+            logging.debug(&quot;data: {}&quot;.format(data))
+            self.socket.close()
+            self.socket = None
+        except socket.error:
+            data = {}
+            self.socket = None
+        except ValueError:
+            data = {}
+        return data
+
+
+    def update(self):
+        &quot;&quot;&quot;
+        Update the current data from the server.
+        &quot;&quot;&quot;
+
+        # Only read each item once
+        self.currentData = self.readSock()
+
+
+    def getOneItem(self, pod, server, item):
+        &quot;&quot;&quot;
+        Update the current data from the server.
+        &quot;&quot;&quot;
+        if len(self.currentData) == 0:
+            self.update()
+        return self.currentData[&quot;pods&quot;][pod][server][item]
+
+
+
+class Point(object):
+
+    def __init__(self, x=0, y=0):
+        self.x = x
+        self.y = y
+
+
+    def __eq__(self, other):
+        return self.x == other.x and self.y == other.y
+
+
+    def xplus(self, xdiff=1):
+        self.x += xdiff
+
+
+    def yplus(self, ydiff=1):
+        self.y += ydiff
+
+
+
+class BaseWindow(object):
+    &quot;&quot;&quot;
+    Common behavior for window types.
+    &quot;&quot;&quot;
+
+    help = &quot;Not Implemented&quot;
+    all = True
+    clientItem = None
+
+    windowTitle = &quot;&quot;
+    formatWidth = 0
+    additionalRows = 0
+
+    def __init__(self, dashboard):
+        self.dashboard = dashboard
+        self.rowCount = 0
+        self.needsReset = False
+        self.z_order = 'bottom'
+
+
+    def makeWindow(self, top=0, left=0):
+        self.updateRowCount()
+        self._createWindow(
+            self.windowTitle,
+            self.rowCount + self.additionalRows,
+            self.formatWidth,
+            begin_y=top, begin_x=left
+        )
+        return self
+
+
+    def updateRowCount(self):
+        &quot;&quot;&quot;
+        Update L{self.rowCount} based on the current data
+        &quot;&quot;&quot;
+        raise NotImplementedError()
+
+
+    def _createWindow(
+        self, title, nlines, ncols, begin_y=0, begin_x=0
+    ):
+        &quot;&quot;&quot;
+        Initialize a curses window based on the sizes required.
+        &quot;&quot;&quot;
+        self.window = curses.newwin(nlines, ncols, begin_y, begin_x)
+        self.window.nodelay(1)
+        self.panel = curses.panel.new_panel(self.window)
+        eval(&quot;self.panel.%s()&quot; % (self.z_order,))
+        self.title = title
+        self.nlines = nlines
+        self.ncols = ncols
+        self.iter = 0
+        self.lastResult = {}
+
+
+    def requiresUpdate(self):
+        &quot;&quot;&quot;
+        Indicates whether a window type has dynamic data that should be
+        refreshed on each update, or whether it is static data (e.g.,
+        L{HelpWindow}) that only needs to be drawn once.
+        &quot;&quot;&quot;
+        return True
+
+
+    def requiresReset(self):
+        &quot;&quot;&quot;
+        Indicates that the window needs a full reset, because e.g., the
+        number of items it displays has changed.
+        &quot;&quot;&quot;
+        return self.needsReset
+
+
+    def activate(self):
+        &quot;&quot;&quot;
+        About to start displaying.
+        &quot;&quot;&quot;
+        # Update once when activated
+        if not self.requiresUpdate():
+            self.update()
+
+
+    def deactivate(self):
+        &quot;&quot;&quot;
+        Clear any drawing done by the current window type.
+        &quot;&quot;&quot;
+        self.window.erase()
+        self.window.refresh()
+
+
+    def update(self):
+        &quot;&quot;&quot;
+        Periodic window update - redraw the window.
+        &quot;&quot;&quot;
+        raise NotImplementedError()
+
+
+    def tableHeader(self, hdrs, count):
+        &quot;&quot;&quot;
+        Generate the header rows.
+        &quot;&quot;&quot;
+        self.window.erase()
+        self.window.border()
+        self.window.addstr(
+            0, 2,
+            self.title + &quot; {} ({})&quot;.format(count, self.iter)
+        )
+
+        pt = Point(1, 1)
+
+        for hdr in hdrs:
+            self.window.addstr(pt.y, pt.x, hdr, curses.A_REVERSE)
+            pt.yplus()
+
+        return pt
+
+
+    def tableFooter(self, feet, pt):
+        &quot;&quot;&quot;
+        Generate the footer rows.
+        &quot;&quot;&quot;
+        self.window.hline(pt.y, pt.x, &quot;-&quot;, self.formatWidth - 2)
+        pt.yplus()
+        for footer in feet:
+            self.window.addstr(pt.y, pt.x, footer)
+            pt.yplus()
+
+
+    def tableRow(self, text, pt, style=curses.A_NORMAL):
+        &quot;&quot;&quot;
+        Generate a single row.
+        &quot;&quot;&quot;
+        try:
+            self.window.addstr(
+                pt.y, pt.x, text,
+                style
+            )
+        except curses.error:
+            pass
+        pt.yplus()
+
+
+    def clientData(self, item=None):
+        return self.dashboard.dataForItem(item if item else self.clientItem)
+
+
+
+class ServersMenu(BaseWindow):
+    &quot;&quot;&quot;
+    Top menu if multiple servers are present.
+    &quot;&quot;&quot;
+
+    help = &quot;servers help&quot;
+    all = False
+
+    windowTitle = &quot;Servers&quot;
+    formatWidth = 0
+    additionalRows = 0
+
+    def makeWindow(self, top=0, left=0):
+        term_w, _ignore_term_h = terminal_size()
+        self.formatWidth = term_w - 50
+        return super(ServersMenu, self).makeWindow(0, 0)
+
+
+    def updateRowCount(self):
+        self.rowCount = len(self.dashboard.pods())
+
+
+    def requiresUpdate(self):
+        return False
+
+
+    def update(self):
+
+        self.window.erase()
+
+        pods = self.dashboard.pods()
+        width = max(map(len, pods))
+
+        pt = Point()
+        for row, pod in enumerate(pods):
+            pt.x = 0
+
+            s = (&quot;Pod: {:&gt;&quot; + str(width) + &quot;} | Servers: |&quot;).format(pod)
+            self.window.addstr(pt.y, pt.x, s)
+            pt.xplus(len(s))
+
+            selected_server = None
+            for column, server in enumerate(self.dashboard.serversForPod(pod)):
+                cell = Point(column, row)
+                selected = cell == self.dashboard.selected_server
+                s = &quot; {:02d} &quot;.format(column + 1)
+                self.window.addstr(
+                    pt.y, pt.x, s,
+                    curses.A_REVERSE if selected else curses.A_NORMAL
+                )
+                pt.xplus(len(s))
+                self.window.addstr(pt.y, pt.x, &quot;|&quot;)
+                pt.xplus()
+                if selected:
+                    selected_server = server
+
+            self.window.addstr(pt.y, pt.x, &quot; {}&quot;.format(selected_server))
+            pt.yplus()
+
+        self.window.refresh()
+
+
+
+class HelpWindow(BaseWindow):
+    &quot;&quot;&quot;
+    Display help for the dashboard.
+    &quot;&quot;&quot;
+
+    help = &quot;Help&quot;
+    all = False
+    helpItems = (
+        &quot; a - All Panels&quot;,
+        &quot; n - No Panels&quot;,
+        &quot;&quot;,
+        &quot;   - (space) Pause&quot;,
+        &quot; t - Toggle Update Speed&quot;,
+        &quot;&quot;,
+        &quot; q - Quit&quot;,
+    )
+
+    windowTitle = &quot;Help&quot;
+    formatWidth = 28
+    additionalRows = 3
+
+    def makeWindow(self, top=0, left=0):
+        term_w, _ignore_term_h = terminal_size()
+        help_x_offset = term_w - self.formatWidth
+        return super(HelpWindow, self).makeWindow(0, help_x_offset)
+
+
+    def updateRowCount(self):
+        self.rowCount = len(self.helpItems) + len(filter(lambda x: len(x[1]) != 0, Dashboard.registered_window_sets.values())) + len(Dashboard.registered_windows)
+
+
+    def requiresUpdate(self):
+        return False
+
+
+    def update(self):
+
+        self.window.erase()
+        self.window.border()
+        self.window.addstr(0, 2, &quot;Hotkeys&quot;)
+
+        pt = Point(1, 1)
+
+        items = [&quot; {} - {}&quot;.format(keypress, wtype.help) for keypress, wtype in Dashboard.registered_windows.items()]
+        items.append(&quot;&quot;)
+        items.extend([&quot; {} - {}&quot;.format(key, value[0]) for key, value in Dashboard.registered_window_sets.items() if value[1]])
+        items.extend(self.helpItems)
+
+        for item in items:
+            self.tableRow(item, pt)
+
+        self.window.refresh()
+
+
+
+class SystemWindow(BaseWindow):
+    &quot;&quot;&quot;
+    Displays the system information provided by the server.
+    &quot;&quot;&quot;
+
+    help = &quot;System Status&quot;
+    clientItem = &quot;stats_system&quot;
+
+    windowTitle = &quot;System&quot;
+    formatWidth = 52
+    additionalRows = 3
+
+    def updateRowCount(self):
+        self.rowCount = len(defaultIfNone(self.clientData(), (1, 2, 3, 4,)))
+
+
+    def update(self):
+        records = defaultIfNone(self.clientData(), {
+            &quot;cpu use&quot;: 0.0,
+            &quot;memory percent&quot;: 0.0,
+            &quot;memory used&quot;: 0,
+            &quot;start time&quot;: time.time(),
+        })
+        if len(records) != self.rowCount:
+            self.needsReset = True
+            return
+        self.iter += 1
+
+        s = &quot; {:&lt;30}{:&gt;18} &quot;.format(&quot;Item&quot;, &quot;Value&quot;)
+        pt = self.tableHeader((s,), len(records))
+
+        records[&quot;cpu use&quot;] = &quot;{:.2f}&quot;.format(records[&quot;cpu use&quot;])
+        records[&quot;memory percent&quot;] = &quot;{:.1f}&quot;.format(records[&quot;memory percent&quot;])
+        records[&quot;memory used&quot;] = &quot;{:.2f} GB&quot;.format(
+            records[&quot;memory used&quot;] / (1000.0 * 1000.0 * 1000.0)
+        )
+        records[&quot;uptime&quot;] = int(time.time() - records[&quot;start time&quot;])
+        hours, mins = divmod(records[&quot;uptime&quot;] / 60, 60)
+        records[&quot;uptime&quot;] = &quot;{}:{:02d} hh:mm&quot;.format(hours, mins)
+        del records[&quot;start time&quot;]
+
+        for item, value in sorted(records.items(), key=lambda x: x[0]):
+            changed = (
+                item in self.lastResult and self.lastResult[item] != value
+            )
+            s = &quot; {:&lt;30}{:&gt;18} &quot;.format(item, value)
+            self.tableRow(
+                s, pt,
+                curses.A_REVERSE if changed else curses.A_NORMAL,
+            )
+
+        self.window.refresh()
+
+        self.lastResult = records
+
+
+
+class RequestStatsWindow(BaseWindow):
+    &quot;&quot;&quot;
+    Displays the status of the server's master process worker slave slots.
+    &quot;&quot;&quot;
+
+    help = &quot;HTTP Requests&quot;
+    clientItem = &quot;stats&quot;
+
+    windowTitle = &quot;Request Statistics&quot;
+    formatWidth = 84
+    additionalRows = 4
+
+    def updateRowCount(self):
+        self.rowCount = 4
+
+
+    def update(self):
+        records = defaultIfNone(self.clientData(), {})
+        self.iter += 1
+
+        s1 = &quot; {:&lt;8}{:&gt;8}{:&gt;10}{:&gt;10}{:&gt;10}{:&gt;10}{:&gt;8}{:&gt;8}{:&gt;8} &quot;.format(
+            &quot;Period&quot;, &quot;Reqs&quot;, &quot;Av-Reqs&quot;, &quot;Av-Resp&quot;, &quot;Av-NoWr&quot;, &quot;Max-Resp&quot;, &quot;Slot&quot;, &quot;CPU &quot;, &quot;500's&quot;
+        )
+        s2 = &quot; {:&lt;8}{:&gt;8}{:&gt;10}{:&gt;10}{:&gt;10}{:&gt;10}{:&gt;8}{:&gt;8}{:&gt;8} &quot;.format(
+            &quot;&quot;, &quot;&quot;, &quot;per sec&quot;, &quot;(ms)&quot;, &quot;(ms)&quot;, &quot;(ms)&quot;, &quot;Avg.&quot;, &quot;Avg.&quot;, &quot;&quot;
+        )
+        pt = self.tableHeader((s1, s2,), len(records))
+
+        for key, seconds in ((&quot;current&quot;, 60,), (&quot;1m&quot;, 60,), (&quot;5m&quot;, 5 * 60,), (&quot;1h&quot;, 60 * 60,),):
+            stat = records.get(key, {
+                &quot;requests&quot;: 0,
+                &quot;t&quot;: 0.0,
+                &quot;t-resp-wr&quot;: 0.0,
+                &quot;T-MAX&quot;: 0.0,
+                &quot;slots&quot;: 0,
+                &quot;cpu&quot;: 0.0,
+                &quot;500&quot;: 0,
+            })
+            s = &quot; {:&lt;8}{:&gt;8}{:&gt;10.1f}{:&gt;10.1f}{:&gt;10.1f}{:&gt;10.1f}{:&gt;8.2f}{:&gt;7.1f}%{:&gt;8} &quot;.format(
+                key,
+                stat[&quot;requests&quot;],
+                safeDivision(float(stat[&quot;requests&quot;]), seconds),
+                safeDivision(stat[&quot;t&quot;], stat[&quot;requests&quot;]),
+                safeDivision(stat[&quot;t&quot;] - stat[&quot;t-resp-wr&quot;], stat[&quot;requests&quot;]),
+                stat[&quot;T-MAX&quot;],
+                safeDivision(float(stat[&quot;slots&quot;]), stat[&quot;requests&quot;]),
+                safeDivision(stat[&quot;cpu&quot;], stat[&quot;requests&quot;]),
+                stat[&quot;500&quot;],
+            )
+            self.tableRow(s, pt)
+
+        self.window.refresh()
+
+        self.lastResult = records
+
+
+
+class HTTPSlotsWindow(BaseWindow):
+    &quot;&quot;&quot;
+    Displays the status of the server's master process worker slave slots.
+    &quot;&quot;&quot;
+
+    help = &quot;HTTP Slots&quot;
+    clientItem = &quot;slots&quot;
+
+    windowTitle = &quot;HTTP Slots&quot;
+    formatWidth = 72
+    additionalRows = 5
+
+    def updateRowCount(self):
+        self.rowCount = len(defaultIfNone(self.clientData(), {&quot;slots&quot;: ()})[&quot;slots&quot;])
+
+
+    def update(self):
+        data = defaultIfNone(self.clientData(), {&quot;slots&quot;: {}, &quot;overloaded&quot;: False})
+        records = data[&quot;slots&quot;]
+        if len(records) != self.rowCount:
+            self.needsReset = True
+            return
+        self.iter += 1
+
+        s = &quot; {:&gt;4}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8} &quot;.format(
+            &quot;Slot&quot;, &quot;unack&quot;, &quot;ack&quot;, &quot;uncls&quot;, &quot;total&quot;,
+            &quot;start&quot;, &quot;strting&quot;, &quot;stopped&quot;, &quot;abd&quot;
+        )
+        pt = self.tableHeader((s,), len(records))
+
+        for record in sorted(records, key=lambda x: x[&quot;slot&quot;]):
+            changed = (
+                record[&quot;slot&quot;] in self.lastResult and
+                self.lastResult[record[&quot;slot&quot;]] != record
+            )
+            s = &quot; {:&gt;4}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8}{:&gt;8} &quot;.format(
+                record[&quot;slot&quot;],
+                record[&quot;unacknowledged&quot;],
+                record[&quot;acknowledged&quot;],
+                record[&quot;unclosed&quot;],
+                record[&quot;total&quot;],
+                record[&quot;started&quot;],
+                record[&quot;starting&quot;],
+                record[&quot;stopped&quot;],
+                record[&quot;abandoned&quot;],
+            )
+            count = record[&quot;unacknowledged&quot;] + record[&quot;acknowledged&quot;]
+            self.tableRow(
+                s, pt,
+                curses.A_REVERSE if changed else (
+                    curses.A_BOLD if count else curses.A_NORMAL
+                ),
+            )
+
+        s = &quot; {:&lt;12}{:&gt;8}{:&gt;16}&quot;.format(
+            &quot;Total:&quot;,
+            sum(
+                [
+                    record[&quot;unacknowledged&quot;] + record[&quot;acknowledged&quot;]
+                    for record in records
+                ]
+            ),
+            sum([record[&quot;total&quot;] for record in records]),
+        )
+        if data[&quot;overloaded&quot;]:
+            s += &quot;    OVERLOADED&quot;
+        self.tableFooter((s,), pt)
+
+        self.window.refresh()
+
+        self.lastResult = records
+
+
+
+class MethodsWindow(BaseWindow):
+    &quot;&quot;&quot;
+    Display the status of the server's request methods.
+    &quot;&quot;&quot;
+
+    help = &quot;HTTP Methods&quot;
+    clientItem = &quot;stats&quot;
+    stats_keys = (&quot;current&quot;, &quot;1m&quot;, &quot;5m&quot;, &quot;1h&quot;,)
+
+    windowTitle = &quot;Methods&quot;
+    formatWidth = 116
+    additionalRows = 8
+
+    def updateRowCount(self):
+        stats = defaultIfNone(self.clientData(), {})
+        methods = set()
+        for key in self.stats_keys:
+            methods.update(stats.get(key, {}).get(&quot;method&quot;, {}).keys())
+        nlines = len(methods)
+        self.rowCount = nlines
+
+
+    def update(self):
+        stats = defaultIfNone(self.clientData(), {})
+        methods = set()
+        for key in self.stats_keys:
+            methods.update(stats.get(key, {}).get(&quot;method&quot;, {}).keys())
+        if len(methods) != self.rowCount:
+            self.needsReset = True
+            return
+
+        records = {}
+        records_t = {}
+        for key in self.stats_keys:
+            records[key] = defaultIfNone(self.clientData(), {}).get(key, {}).get(&quot;method&quot;, {})
+            records_t[key] = defaultIfNone(self.clientData(), {}).get(key, {}).get(&quot;method-t&quot;, {})
+        self.iter += 1
+
+        s1 = &quot; {:&lt;40}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10} &quot;.format(
+            &quot;&quot;, &quot;------&quot;, &quot;current---&quot;, &quot;------&quot;, &quot;1m--------&quot;, &quot;------&quot;, &quot;5m--------&quot;, &quot;------&quot;, &quot;1h--------&quot;,
+        )
+        s2 = &quot; {:&lt;40}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10} &quot;.format(
+            &quot;Method&quot;, &quot;Number&quot;, &quot;Av-Time&quot;, &quot;Number&quot;, &quot;Av-Time&quot;, &quot;Number&quot;, &quot;Av-Time&quot;, &quot;Number&quot;, &quot;Av-Time&quot;,
+        )
+        s3 = &quot; {:&lt;40}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10} &quot;.format(
+            &quot;&quot;, &quot;&quot;, &quot;(ms)&quot;, &quot;&quot;, &quot;(ms)&quot;, &quot;&quot;, &quot;(ms)&quot;, &quot;&quot;, &quot;(ms)&quot;,
+        )
+        pt = self.tableHeader((s1, s2, s3,), len(records))
+
+        total_methods = dict([(key, 0) for key in self.stats_keys])
+        total_time = dict([(key, 0.0) for key in self.stats_keys])
+        for method_type in sorted(methods):
+            for key in self.stats_keys:
+                total_methods[key] += records[key].get(method_type, 0)
+                total_time[key] += records_t[key].get(method_type, 0.0)
+            changed = self.lastResult.get(method_type, 0) != records[&quot;current&quot;].get(method_type, 0)
+            items = [method_type]
+            for key in self.stats_keys:
+                items.append(records[key].get(method_type, 0))
+                items.append(safeDivision(records_t[key].get(method_type, 0), records[key].get(method_type, 0)))
+            s = &quot; {:&lt;40}{:&gt;8}{:&gt;10.1f}{:&gt;8}{:&gt;10.1f}{:&gt;8}{:&gt;10.1f}{:&gt;8}{:&gt;10.1f} &quot;.format(
+                *items
+            )
+            self.tableRow(
+                s, pt,
+                curses.A_REVERSE if changed else curses.A_NORMAL,
+            )
+
+        items = [&quot;Total:&quot;]
+        for key in self.stats_keys:
+            items.append(total_methods[key])
+            items.append(safeDivision(total_time[key], total_methods[key]))
+        s1 = &quot; {:&lt;40}{:&gt;8}{:&gt;10.1f}{:&gt;8}{:&gt;10.1f}{:&gt;8}{:&gt;10.1f}{:&gt;8}{:&gt;10.1f} &quot;.format(
+            *items
+        )
+        items = [&quot;401s:&quot;]
+        for key in self.stats_keys:
+            items.append(defaultIfNone(self.clientData(), {}).get(key, {}).get(&quot;401&quot;, 0))
+            items.append(&quot;&quot;)
+        s2 = &quot; {:&lt;40}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;10} &quot;.format(
+            *items
+        )
+        self.tableFooter((s1, s2,), pt)
+
+        self.window.refresh()
+
+        self.lastResult = defaultIfNone(self.clientData(), {}).get(&quot;current&quot;, {}).get(&quot;method&quot;, {})
+
+
+
+class AssignmentsWindow(BaseWindow):
+    &quot;&quot;&quot;
+    Displays the status of the server's master process worker slave slots.
+    &quot;&quot;&quot;
+
+    help = &quot;Job Assignments&quot;
+    clientItem = &quot;job_assignments&quot;
+
+    windowTitle = &quot;Job Assignments&quot;
+    formatWidth = 40
+    additionalRows = 5
+
+    def updateRowCount(self):
+        self.rowCount = len(defaultIfNone(self.clientData(), {&quot;workers&quot;: ()})[&quot;workers&quot;])
+
+
+    def update(self):
+        data = defaultIfNone(self.clientData(), {&quot;workers&quot;: {}, &quot;level&quot;: 0})
+        records = data[&quot;workers&quot;]
+        if len(records) != self.rowCount:
+            self.needsReset = True
+            return
+        self.iter += 1
+
+        s = &quot; {:&gt;4}{:&gt;12}{:&gt;8}{:&gt;12} &quot;.format(
+            &quot;Slot&quot;, &quot;assigned&quot;, &quot;load&quot;, &quot;completed&quot;
+        )
+        pt = self.tableHeader((s,), len(records))
+
+        total_assigned = 0
+        total_completed = 0
+        for ctr, details in enumerate(records):
+            assigned, load, completed = details
+            total_assigned += assigned
+            total_completed += completed
+            changed = (
+                ctr in self.lastResult and
+                self.lastResult[ctr] != assigned
+            )
+            s = &quot; {:&gt;4}{:&gt;12}{:&gt;8}{:&gt;12} &quot;.format(
+                ctr,
+                assigned,
+                load,
+                completed,
+            )
+            self.tableRow(
+                s, pt,
+                curses.A_REVERSE if changed else curses.A_NORMAL,
+            )
+
+        s = &quot; {:&lt;6}{:&gt;10}{:&gt;8}{:&gt;12}&quot;.format(
+            &quot;Total:&quot;,
+            total_assigned,
+            &quot;{}%&quot;.format(data[&quot;level&quot;]),
+            total_completed,
+        )
+        self.tableFooter((s,), pt)
+
+        self.window.refresh()
+
+        self.lastResult = records
+
+
+
+class JobsWindow(BaseWindow):
+    &quot;&quot;&quot;
+    Display the status of the server's job queue.
+    &quot;&quot;&quot;
+
+    help = &quot;Job Activity&quot;
+    clientItem = &quot;jobs&quot;
+
+    windowTitle = &quot;Jobs&quot;
+    formatWidth = 98
+    additionalRows = 6
+
+    def updateRowCount(self):
+        self.rowCount = defaultIfNone(self.clientData(&quot;jobcount&quot;), 0)
+
+
+    def update(self):
+        records = defaultIfNone(self.clientData(), {})
+        if len(records) != self.rowCount:
+            self.needsReset = True
+            return
+        self.iter += 1
+
+        s1 = &quot; {:&lt;40}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;8}{:&gt;10}{:&gt;10} &quot;.format(
+            &quot;Work Type&quot;, &quot;Queued&quot;, &quot;Assigned&quot;, &quot;Late&quot;, &quot;Failed&quot;, &quot;Completed&quot;, &quot;Av-Time&quot;,
+        )
+        s2 = &quot; {:&lt;40}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;8}{:&gt;10}{:&gt;10} &quot;.format(
+            &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;(ms)&quot;,
+        )
+        pt = self.tableHeader((s1, s2,), len(records))
+
+        total_queued = 0
+        total_assigned = 0
+        total_late = 0
+        total_failed = 0
+        total_completed = 0
+        total_time = 0.0
+        for work_type, details in sorted(records.items(), key=lambda x: x[0]):
+            total_queued += details[&quot;queued&quot;]
+            total_assigned += details[&quot;assigned&quot;]
+            total_late += details[&quot;late&quot;]
+            total_failed += details[&quot;failed&quot;]
+            total_completed += details[&quot;completed&quot;]
+            total_time += details[&quot;time&quot;]
+            changed = (
+                work_type in self.lastResult and
+                self.lastResult[work_type][&quot;queued&quot;] != details[&quot;queued&quot;]
+            )
+            s = &quot;{}{:&lt;40}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;8}{:&gt;10}{:&gt;10.1f} &quot;.format(
+                &quot;&gt;&quot; if details[&quot;queued&quot;] else &quot; &quot;,
+                work_type,
+                details[&quot;queued&quot;],
+                details[&quot;assigned&quot;],
+                details[&quot;late&quot;],
+                details[&quot;failed&quot;],
+                details[&quot;completed&quot;],
+                safeDivision(details[&quot;time&quot;], details[&quot;completed&quot;], 1000.0)
+            )
+            self.tableRow(
+                s, pt,
+                curses.A_REVERSE if changed else (
+                    curses.A_BOLD if details[&quot;queued&quot;] else curses.A_NORMAL
+                ),
+            )
+
+        s = &quot; {:&lt;40}{:&gt;8}{:&gt;10}{:&gt;8}{:&gt;8}{:&gt;10}{:&gt;10.1f} &quot;.format(
+            &quot;Total:&quot;,
+            total_queued,
+            total_assigned,
+            total_late,
+            total_failed,
+            total_completed,
+            safeDivision(total_time, total_completed, 1000.0)
+        )
+        self.tableFooter((s,), pt)
+
+        self.window.refresh()
+
+        self.lastResult = records
+
+
+
+class DirectoryStatsWindow(BaseWindow):
+    &quot;&quot;&quot;
+    Displays the status of the server's directory service calls
+    &quot;&quot;&quot;
+
+    help = &quot;Directory Service&quot;
+    clientItem = &quot;directory&quot;
+
+    windowTitle = &quot;Directory Service&quot;
+    formatWidth = 89
+    additionalRows = 8
+
+    def updateRowCount(self):
+        self.rowCount = len(defaultIfNone(self.clientData(), {}))
+
+
+    def update(self):
+        records = defaultIfNone(self.clientData(), {})
+        if len(records) != self.rowCount:
+            self.needsReset = True
+            return
+
+        self.iter += 1
+
+        s1 = &quot; {:&lt;40}{:&gt;15}{:&gt;15}{:&gt;15} &quot;.format(
+            &quot;Method&quot;, &quot;Calls&quot;, &quot;Total&quot;, &quot;Average&quot;
+        )
+        s2 = &quot; {:&lt;40}{:&gt;15}{:&gt;15}{:&gt;15} &quot;.format(
+            &quot;&quot;, &quot;&quot;, &quot;(sec)&quot;, &quot;(ms)&quot;
+        )
+        pt = self.tableHeader((s1, s2,), len(records))
+
+        overallCount = 0
+        overallCountRatio = 0
+        overallCountCached = 0
+        overallCountUncached = 0
+        overallTimeSpent = 0.0
+
+        for methodName, result in sorted(records.items(), key=lambda x: x[0]):
+            if isinstance(result, int):
+                count, timeSpent = result, 0.0
+            else:
+                count, timeSpent = result
+            overallCount += count
+            if methodName.endswith(&quot;-hit&quot;):
+                overallCountRatio += count
+                overallCountCached += count
+            if methodName.endswith(&quot;-miss&quot;) or methodName.endswith(&quot;-expired&quot;):
+                overallCountRatio += count
+                overallCountUncached += count
+            overallTimeSpent += timeSpent
+
+            s = &quot; {:&lt;40}{:&gt;15d}{:&gt;15.1f}{:&gt;15.3f} &quot;.format(
+                methodName,
+                count,
+                timeSpent,
+                (1000.0 * timeSpent) / count,
+            )
+            self.tableRow(s, pt)
+
+        s = &quot; {:&lt;40}{:&gt;15d}{:&gt;15.1f}{:&gt;15.3f} &quot;.format(
+            &quot;Total:&quot;,
+            overallCount,
+            overallTimeSpent,
+            safeDivision(overallTimeSpent, overallCount, 1000.0)
+        )
+        s_cached = &quot; {:&lt;40}{:&gt;15d}{:&gt;14.1f}%{:&gt;15s} &quot;.format(
+            &quot;Total Cached:&quot;,
+            overallCountCached,
+            safeDivision(overallCountCached, overallCountRatio, 100.0),
+            &quot;&quot;,
+        )
+        s_uncached = &quot; {:&lt;40}{:&gt;15d}{:&gt;14.1f}%{:&gt;15s} &quot;.format(
+            &quot;Total Uncached:&quot;,
+            overallCountUncached,
+            safeDivision(overallCountUncached, overallCountRatio, 100.0),
+            &quot;&quot;,
+        )
+        self.tableFooter((s, s_cached, s_uncached), pt)
+
+        self.window.refresh()
+
+
+
+Dashboard.registerWindow(HelpWindow, &quot;h&quot;)
+Dashboard.registerWindow(SystemWindow, &quot;s&quot;)
+Dashboard.registerWindow(RequestStatsWindow, &quot;r&quot;)
+Dashboard.registerWindow(HTTPSlotsWindow, &quot;c&quot;)
+Dashboard.registerWindow(MethodsWindow, &quot;m&quot;)
+Dashboard.registerWindow(AssignmentsWindow, &quot;w&quot;)
+Dashboard.registerWindow(JobsWindow, &quot;j&quot;)
+Dashboard.registerWindow(DirectoryStatsWindow, &quot;d&quot;)
+
+Dashboard.registerWindowSet(SystemWindow, &quot;H&quot;)
+Dashboard.registerWindowSet(RequestStatsWindow, &quot;H&quot;)
+Dashboard.registerWindowSet(HTTPSlotsWindow, &quot;H&quot;)
+Dashboard.registerWindowSet(MethodsWindow, &quot;H&quot;)
+
+Dashboard.registerWindowSet(SystemWindow, &quot;J&quot;)
+Dashboard.registerWindowSet(AssignmentsWindow, &quot;J&quot;)
+Dashboard.registerWindowSet(JobsWindow, &quot;J&quot;)
+
+if __name__ == &quot;__main__&quot;:
+    main()
</ins><span class="cx">Property changes on: CalendarServer/trunk/calendarserver/tools/dashview.py
</span><span class="cx">___________________________________________________________________
</span></span></pre></div>
<a id="svnexecutable"></a>
<div class="addfile"><h4>Added: svn:executable</h4></div>
</div>

</body>
</html>