[Git][NTPsec/ntpsec][master] Formatting function changeover and associated fixes.

Gary E. Miller gitlab at mg.gitlab.com
Thu Apr 13 01:08:09 UTC 2017


Gary E. Miller pushed to branch master at NTPsec / ntpsec


Commits:
e648b0c5 by Ian Bruene at 2017-04-13T01:05:59+00:00
Formatting function changeover and associated fixes.

- - - - -


4 changed files:

- ntpclients/ntpmon
- ntpclients/ntpq
- pylib/packet.py
- pylib/util.py


Changes:

=====================================
ntpclients/ntpmon
=====================================
--- a/ntpclients/ntpmon
+++ b/ntpclients/ntpmon
@@ -69,7 +69,7 @@ def iso8601(t):
 def statline(_peerlist, _mrulist, nyquist):
     "Generate a status line"
     # We don't use stdversion here because the presence of a date is confusing
-    leader = sysvars['version']
+    leader = sysvars['version'][0]
     if span.entries:
         trailer = "Last update: %s (%s)" \
                   % (iso8601(span.entries[0].last),
@@ -86,7 +86,12 @@ def peer_detail(variables, showunits=False):
     # One of the goals here is to emit field values at fixed positions
     # on the 2D display, so that changes in the details are easier to spot.
     vcopy = {}
+    vcopyraw = {}
     vcopy.update(variables)
+    # Need to seperate the casted from the raw
+    for key in vcopy.keys():
+        vcopyraw[key] = vcopy[key][1]
+        vcopy[key] = vcopy[key][0]
     vcopy["leap"] = ("no-leap", "add-leap", "del-leap",
                      "unsync")[vcopy["leap"]]
     for fld in ('xmt', 'rec', 'reftime'):
@@ -97,28 +102,28 @@ def peer_detail(variables, showunits=False):
     if showunits:
         for name in ntp.util.MS_VARS:
             if name in vcopy:
-                vcopy[name] = ntp.util.unitformatter(vcopy[name],
-                                                     ntp.util.UNITS_SEC,
-                                                     ntp.util.UNIT_MS,
-                                                     strip=True,
-                                                     width=None)
+                vcopy[name] = ntp.util.unitify(vcopyraw[name],
+                                               ntp.util.UNITS_SEC,
+                                               ntp.util.UNIT_MS,
+                                               strip=True,
+                                               width=None)
         for name in ntp.util.PPM_VARS:
             if name in vcopy:
-                vcopy[name] = ntp.util.unitformatter(vcopy[name],
-                                                     ntp.util.UNITS_PPX,
-                                                     ntp.util.UNIT_PPM,
-                                                     strip=True,
-                                                     width=None)
+                vcopy[name] = ntp.util.unitify(vcopyraw[name],
+                                               ntp.util.UNITS_PPX,
+                                               ntp.util.UNIT_PPM,
+                                               strip=True,
+                                               width=None)
         for name in ntp.util.S_VARS:
             if name in vcopy:
-                vcopy[name] = ntp.util.unitformatter(vcopy[name],
-                                                     ntp.util.UNITS_SEC,
-                                                     ntp.util.UNIT_S,
-                                                     strip=True,
-                                                     width=None)
-        vcopy['filtdelay'] = ntp.util.filtcooker(vcopy['filtdelay'])
-        vcopy['filtoffset'] = ntp.util.filtcooker(vcopy['filtoffset'])
-        vcopy['filtdisp'] = ntp.util.filtcooker(vcopy['filtdisp'])
+                vcopy[name] = ntp.util.unitify(vcopyraw[name],
+                                               ntp.util.UNITS_SEC,
+                                               ntp.util.UNIT_S,
+                                               strip=True,
+                                               width=None)
+        vcopy['filtdelay'] = ntp.util.filtcooker(vcopyraw['filtdelay'])
+        vcopy['filtoffset'] = ntp.util.filtcooker(vcopyraw['filtoffset'])
+        vcopy['filtdisp'] = ntp.util.filtcooker(vcopyraw['filtdisp'])
     else:
         vcopy['filtdelay'] = vcopy['filtdelay'].replace(' ', '\t')
         vcopy['filtoffset'] = vcopy['filtoffset'].replace(' ', '\t')
@@ -209,7 +214,7 @@ if __name__ == '__main__':
     try:
         session = ntp.packet.ControlSession()
         session.openhost(arguments[0] if arguments else "localhost")
-        sysvars = session.readvar()
+        sysvars = session.readvar(raw=True)
         with OutputContext() as ctx:
             while True:
                 stdscr.clear()
@@ -246,7 +251,8 @@ if __name__ == '__main__':
                                        ntp.control.CTL_PST_REACH))):
                                 continue
                             try:
-                                variables = session.readvar(peer.associd)
+                                variables = session.readvar(peer.associd,
+                                                            raw=True)
                             except ntp.packet.ControlException as e:
                                 raise Fatal(e.message + "\n")
                             except IOError as e:
@@ -304,7 +310,8 @@ if __name__ == '__main__':
                             try:
                                 clockvars = session.readvar(
                                     peers[selected].associd,
-                                    opcode=ntp.control.CTL_OP_READCLOCK)
+                                    opcode=ntp.control.CTL_OP_READCLOCK,
+                                    raw=True)
                                 strconvert = ntp.util.cook(clockvars)
                                 stdscr.addstr(strconvert.encode('UTF-8'))
                             except ntp.packet.ControlException as e:


=====================================
ntpclients/ntpq
=====================================
--- a/ntpclients/ntpq
+++ b/ntpclients/ntpq
@@ -317,7 +317,7 @@ usage: help [ command ]
                         self.warn("eliding [%d]\n" % peer.associd)
                     continue
                 try:
-                    variables = self.session.readvar(peer.associd)
+                    variables = self.session.readvar(peer.associd, raw=True)
                 except ntp.packet.ControlException as e:
                     self.warn(e.message + "\n")
                     return
@@ -413,7 +413,7 @@ usage: help [ command ]
     def __dolist(self, varlist, associd, op, type, quiet=False):
         "List variables associated with a specified peer."
         try:
-            variables = self.session.readvar(associd, varlist, op)
+            variables = self.session.readvar(associd, varlist, op, raw=True)
         except ntp.packet.ControlException as e:
             self.warn(e.message + "\n")
             return False
@@ -474,8 +474,9 @@ usage: timeout [ msec ]
                 items = []
                 for var in varlist:
                     try:
-                        queried = self.session.readvar(associd, [var])
-                        for (name, value) in queried.items():
+                        queried = self.session.readvar(associd, [var],
+                                                       raw=True)
+                        for (name, (value, rawvalue)) in queried.items():
                             items.append((name, value))
                     except ntp.packet.ControlException as e:
                         if ntp.control.CERR_UNKNOWNVAR == e.errorcode:


=====================================
pylib/packet.py
=====================================
--- a/pylib/packet.py
+++ b/pylib/packet.py
@@ -1267,11 +1267,13 @@ class ControlSession:
                     eq = pair.index("=")
                     var = pair[:eq].strip()
                     val = pair[eq+1:].strip()
+                    casted = False
                     try:
                         if raw is True:
                             val = (int(val, 0), val)
                         else:
                             val = int(val, 0)
+                        casted = True
                     except ValueError:
                         try:
                             if raw is True:
@@ -1284,11 +1286,15 @@ class ControlSession:
                                 # so printout can handle .3f vs .6f
                                 items.append(("delay-s", val))
                             val = valf
+                            casted = True
                         except ValueError:
                             if val[0] == '"' and val[-1] == '"':
                                 val = val[1:-1]
                                 if raw is True:
                                     val = (val, val)
+                                casted = True
+                    if (raw is True) and (casted is False):
+                        val = (val, val)
                     items.append((var, val))
                 except ValueError:
                     # Yes, ntpd really does emit bare tags for empty


=====================================
pylib/util.py
=====================================
--- a/pylib/util.py
+++ b/pylib/util.py
@@ -3,6 +3,7 @@
 
 from __future__ import print_function
 
+
 import socket
 import sys
 import time
@@ -360,15 +361,19 @@ def unitify(value, unitgroup, startingunit, baseunit=0,
     if isstringzero(value) is True:  # display highest precision zero
         base = unitgroup[baseunit]
         if strip is False:
-            newvalue = fitinfield("0", width - len(base)) + base
-        return newvalue
+            value = fitinfield("0", width - len(base)) + base
+        return value
     ooms = oomsbetweenunits(startingunit, baseunit)
     newvalue = cropprecision(value, ooms)
     newvalue, unitsmoved = scalestring(newvalue)
     unitget = startingunit + unitsmoved
     if 0 <= unitget < len(unitgroup):  # We have a unit
         unit = unitgroup[unitget]
-        newvalue = fitinfield(newvalue, width - len(unit)) + unit
+        if width is None:
+            realwidth = None
+        else:
+            realwidth = width - len(unit)
+        newvalue = fitinfield(newvalue, realwidth) + unit
     else:  # don't have a replacement unit, use original
         newvalue = value + unitgroup[startingunit]
     if strip is True:
@@ -608,7 +613,7 @@ def cook(variables, showunits=False):
     text = ""
     specials = ("filtdelay", "filtoffset", "filtdisp", "filterror")
     longestspecial = len(max(specials, key=len))
-    for (name, value) in variables.items():
+    for (name, (value, rawvalue)) in variables.items():
         if name in specials:  # need special formatting for column alignment
             formatter = "%" + str(longestspecial) + "s ="
             item = formatter % name
@@ -662,20 +667,20 @@ def cook(variables, showunits=False):
             #   missing variables here.
             #  Completion cannot occur until all units are tracked down.
             if showunits:
-                item += unitformatter(value, UNITS_SEC, UNIT_MS, UNIT_NS,
-                                      True, width=None)
+                item += unitify(rawvalue, UNITS_SEC, UNIT_MS, UNIT_NS,
+                                True, width=None)
             else:
                 item += repr(value)
         elif name in S_VARS:
             if showunits:
-                item += unitformatter(value, UNITS_SEC, UNIT_S, UNIT_NS,
-                                      True, width=None)
+                item += unitify(rawvalue, UNITS_SEC, UNIT_S, UNIT_NS,
+                                True, width=None)
             else:
                 item += repr(value)
         elif name in PPM_VARS:
             if showunits:
-                item += unitformatter(value, UNITS_PPX, UNIT_PPM,
-                                      strip=True, width=None)
+                item += unitify(rawvalue, UNITS_PPX, UNIT_PPM,
+                                strip=True, width=None)
             else:
                 item += repr(value)
         else:
@@ -792,7 +797,7 @@ class PeerSummary:
 
         now = time.time()
 
-        for (name, value) in variables.items():
+        for (name, (value, rawvalue)) in variables.items():
             if name in ("srcadr", "peeradr"):
                 srcadr = value
             elif name == "srchost":
@@ -822,18 +827,18 @@ class PeerSummary:
                 # Shipped as hex, displayed in octal
                 reach = value
             elif name == "delay":
-                estdelay = value
+                estdelay = rawvalue if self.showunits else value
             elif name == "delay-s":
                 if len(value) > 6 and value[-7] == ".":
                     saw6 = True
             elif name == "offset":
-                estoffset = value
+                estoffset = rawvalue if self.showunits else value
             elif name == "jitter":
                 if "jitter" in self.__header:
-                    estjitter = value
+                    estjitter = rawvalue if self.showunits else value
                     have_jitter = True
             elif name == "rootdisp" or name == "dispersion":
-                estdisp = value
+                estdisp = rawvalue if self.showunits else value
             elif name == "rec":
                 # FIXME, rec never used.
                 rec = value     # l_fp timestamp
@@ -912,11 +917,13 @@ class PeerSummary:
             line += (" " * (self.refidwidth - len(visible)))
         # The rest of the story
         last_sync = variables.get("rec") or variables.get("reftime")
+        if isinstance(last_sync, tuple):
+            last_sync = last_sync[0]
         jd = estjitter if have_jitter else estdisp
         try:
             line += (
                 " %2ld %c %4.4s %4.4s  %3lo"
-                % (variables.get("stratum", 0),
+                % (variables.get("stratum", 0)[0],
                    ptype,
                    PeerSummary.prettyinterval(
                     now if last_sync is None
@@ -926,9 +933,9 @@ class PeerSummary:
                 if self.showunits:
                     line += (
                         " %s %s %s" %
-                        (unitformatter(estdelay, UNITS_SEC, UNIT_MS),
-                         unitformatter(estoffset, UNITS_SEC, UNIT_MS),
-                         unitformatter(jd, UNITS_SEC, UNIT_MS)))
+                        (unitify(estdelay, UNITS_SEC, UNIT_MS),
+                         unitify(estoffset, UNITS_SEC, UNIT_MS),
+                         unitify(jd, UNITS_SEC, UNIT_MS)))
                 else:
                     line += (
                         " %s %s %s" %
@@ -939,9 +946,9 @@ class PeerSummary:
                 if self.showunits:
                     line += (
                         " %s %s %s" %
-                        (unitformatter(estdelay, UNITS_SEC, UNIT_MS),
-                         unitformatter(estoffset, UNITS_SEC, UNIT_MS),
-                         unitformatter(jd, UNITS_SEC, UNIT_MS)))
+                        (unitify(estdelay, UNITS_SEC, UNIT_MS),
+                         unitify(estoffset, UNITS_SEC, UNIT_MS),
+                         unitify(jd, UNITS_SEC, UNIT_MS)))
                 else:
                     line += (
                         " %s %s %s" %



View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/e648b0c5d288a341592f121de08492a6f32a8ed0

---
View it on GitLab: https://gitlab.com/NTPsec/ntpsec/commit/e648b0c5d288a341592f121de08492a6f32a8ed0
You're receiving this email because of your account on gitlab.com.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.ntpsec.org/pipermail/vc/attachments/20170413/86588945/attachment.html>


More information about the vc mailing list