Skip to contentSkip to conversation

Multiplexed task logs / bitbake fixes for fetch2

PATCH Superseded Jason Wessel 1 participant 16 messages Jun 6, 2012

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover Multiplexed task logs / bitbake fixes for fetch2

This is the v3 patch set for various fixes/features to bit bake logging.

New in this series:
Patch 8 - knotty would not flush in a timely manner throue |tee Patch 9 - knotty2 - fix reporting of set scene tasks Patch 10 - knotty2 - fix line wrap issues
Patch 11 - merge knotty2 functionatilty into knotty
Patch 12 - dynamically toggle log locations
Patch 15 - OE Core specific change to make screen_inline the default

-- Previous information from v2 patch set --

New in this series:
Patch 5 - Change to the api for passing the screen connection Patch 6 - Fix logging in fetch2
Patch 7 - Fix fetch2 failures to a read-only GITDIR
Patch 13/14 - OE Core specific changes related to screen as a reference

-- Previous information from first patch set --

This patch set is intended to provide a semi real time aspect to the logging to stdout. Originally I was just interested in the output of the do_compile and I will still consider adding that capability, but I ended up using the logger generically. It provides the ability to see all the task logs multiplexed to stdout by PID.

More recently I decided I wanted to be able to toggle the logs on and off while bitbake was already running, so that was added into the series as well. After seeing how that worked, I also decided I wanted to be able to run the dev shell in a single terminal window. The last patch in the series is for the OE-Core, but since I made reference to this patch I included in this series for completeness.

As a foot note, I have actually been using a more primitive version of this patch set for the last 4 weeks that was controlled only by the local.conf setting and used it to diagnose quite a few different problems as well as to just understand what it is that bitbake is doing at times.

Thanks,
Jason.

--

Bitbake specific short log:

Jason Wessel (12):
process.py: Fix log truncation problems
knotty: Extend knotty to support "real time" log tail for tasks
knotty: Add the ability to dynamically select loglevel from stdin
msg.py, knotty.py: Allow dynamic toggle of the debug log level
knotty.py: Add the ability to spawn screen directly from knotty with OE_TERMINAL=screen_inline
fetch2: Fix missing output from stderr in fetcher logs
fetch2/git.py: Use local download dir, when using an external read-only GITDIR knotty.py, knotty2,py: Flush and update footer on dynamic log level change knotty2.py: Fix knotty2 to report something other than 0 of 0 for setscene tasks
knotty2: Properly adjust for lines longer than terminal size
knotty: Merge knotty2 functionality into knotty
knotty: Add ability to dynamically toggle log location

 lib/bb/build.py                  |    4 +
 lib/bb/fetch2/__init__.py        |    5 +-
 lib/bb/fetch2/git.py             |    5 +-
 lib/bb/msg.py                    |    9 +-
 lib/bb/process.py                |   29 +++-
 lib/bb/ui/crumbs/multilogtail.py |  135 ++++++++++++++++++
 lib/bb/ui/knotty.py              |  283 ++++++++++++++++++++++++++++++++++++--
 lib/bb/ui/knotty2.py             |   51 ++++++-
 lib/bb/ui/uihelper.py            |    5 +
 9 files changed, 503 insertions(+), 23 deletions(-)
 create mode 100644 lib/bb/ui/crumbs/multilogtail.py
#1 lore raw

PATCH v3 1/15 process.py: Fix log truncation problems

There are two problems with the _logged_communicate that are both caused as a result of buffering I/O, instead of flushing it out to the log files as it arrives.

1) log truncation when python dumps
I have seen the task logs missing data that was not flushed when bitbake crashes.

2) While a bitbake task is running it is impossible to see what is going on if it is only writing a small incremental log that is smaller than the buffer, or you get only a partial log, up until the task exists. It is worse in the case that stderr and stdout are separate file handles, because previous code blocks on the read of stdout and then stderr, serially.

The right approach is simply to use select() to determine if there is data available and then to flush the log buffers as they arrive. This still makes use of buffering in the cases where there is more than 1 byte of data, but the buffers are much more dynamic.

---
 lib/bb/process.py |   29 +++++++++++++++++++++++++++--
 1 file changed, 27 insertions(+), 2 deletions(-)
lib/bb/process.py +27 -2
index b74cb18..9848fc3 100644
@@ -1,6 +1,9 @@
 import logging
 import signal
 import subprocess
+import fcntl
+import errno
+import select
 
 logger = logging.getLogger('BitBake.Process')
 
@@ -70,18 +73,40 @@ def _logged_communicate(pipe, log, input):
 
     bufsize = 512
     outdata, errdata = [], []
+    rin = []
+
+    if pipe.stdout is not None:
+        fd = pipe.stdout.fileno()
+        fl = fcntl.fcntl(fd, fcntl.F_GETFL)
+        fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
+        rin.append(pipe.stdout)
+    if pipe.stderr is not None:
+        fd = pipe.stderr.fileno()
+        fl = fcntl.fcntl(fd, fcntl.F_GETFL)
+        fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
+        rin.append(pipe.stderr)
+
     while pipe.poll() is None:
-        if pipe.stdout is not None:
+        rlist = rin
+        try:
+            r,w,e = select.select (rlist, [], [])
+        except OSError, e:
+            if e.errno != errno.EINTR:
+                raise
+
+        if pipe.stdout in r:
             data = pipe.stdout.read(bufsize)
             if data is not None:
                 outdata.append(data)
                 log.write(data)
+                log.flush()
 
-        if pipe.stderr is not None:
+        if pipe.stderr in r:
             data = pipe.stderr.read(bufsize)
             if data is not None:
                 errdata.append(data)
                 log.write(data)
+                log.flush()
     return ''.join(outdata), ''.join(errdata)
 
 def run(cmd, input=None, log=None, **options):
Signature · 1 line
1.7.10
#2 lore raw

PATCH v3 2/15 knotty: Extend knotty to support "real time" log tail for tasks

In reply to Jason Wessel

This patch provides the capability to knotty to have a higher log level where the individual tasks logs can be multiplexed to stdio. This is highly desirable for several different use cases.

1) You can visually spot "hot spots" in building parallel tasks

2) The relative order an sequence of events can be determined in difficult to diagnose inter-related library problems.

3) It provides a nice way to see what all is actually going on and getting logged by various tasks such as a kernel compile where you might want to actually look at the output in a build over build scenario.

4) There are most certainly other aspects where this is useful.

The primary control is to set the BB_RT_LOGLEVEL = "2" in your local.conf. Additional capabilities will follow in successive patches. When parallel tasks are enabled, the logs will be multiplexed and prefixed with the PID of the task. In the non-parallel case there is no PID prefix as everything is linear.

---
 lib/bb/build.py                  |    4 ++
 lib/bb/ui/crumbs/multilogtail.py |  135 ++++++++++++++++++++++++++++++++++++++
 lib/bb/ui/knotty.py              |   46 +++++++++++++
 3 files changed, 185 insertions(+)
 create mode 100644 lib/bb/ui/crumbs/multilogtail.py
lib/bb/build.py +4 -0
index 95f1dcf..257ece7 100644
@@ -88,6 +88,10 @@ class TaskBase(event.Event):
 class TaskStarted(TaskBase):
     """Task execution started"""
 
+    def __init__(self, t, d):
+        self.logfile = d.getVar("BB_LOGFILE", True) or "";
+        super(TaskStarted, self).__init__(t, d)
+
 class TaskSucceeded(TaskBase):
     """Task execution completed"""
 
lib/bb/ui/crumbs/multilogtail.py new file +135 -0

135 lines not on this page · raw message

lib/bb/ui/knotty.py +46 -0

85 lines not on this page · raw message

Signature · 1 line
1.7.10
#3 lore raw

PATCH v3 3/15 knotty: Add the ability to dynamically select loglevel from stdin

In reply to Jason Wessel

If stdin is a controlling terminal, make it possible to dynamically select a log level with the keys 1 and 2.

1 = normal bitbake knotty logs
2 = realtime multiple tail of task logs

---
 lib/bb/ui/knotty.py |   32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
lib/bb/ui/knotty.py +32 -0
index fd86ed5..f72f0ad 100644
@@ -108,6 +108,32 @@ class TerminalFilter(object):
     def finish(self):
         return
 
+class StdinMgr:
+    def __init__(self):
+        self.stdinbackup = None
+        self.fd = None
+        if sys.stdin.isatty():
+            self.fd = sys.stdin.fileno()
+            self.stdinbackup = termios.tcgetattr(self.fd)
+            new = termios.tcgetattr(self.fd)
+            new[3] = new[3] & ~termios.ICANON & ~termios.ECHO
+            termios.tcsetattr(self.fd, termios.TCSANOW, new)
+
+    def poll(self):
+        if not self.stdinbackup:
+            return False
+        return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
+
+    def restore(self):
+        if self.stdinbackup:
+            termios.tcsetattr(self.fd, termios.TCSADRAIN, self.stdinbackup)
+            self.stdinbackup = None
+        # Force echo back on "just in case" something went haywire with an exception
+        if sys.stdin.isatty():
+            new = termios.tcgetattr(self.fd)
+            new[3] = new[3] | termios.ECHO
+            termios.tcsetattr(self.fd, termios.TCSANOW, new)
+
 class RtLogLevel:
     def __init__(self, mlt):
         self.displaytail = False
@@ -184,11 +210,15 @@ def main(server, eventHandler, tf = TerminalFilter):
     taskfailures = []
 
     termfilter = tf(main, helper, console, format)
+    stdin_mgr = StdinMgr()
 
     while True:
         try:
             termfilter.updateFooter()
             event = eventHandler.waitEvent(0.25)
+            if stdin_mgr.poll():
+                keyinput = sys.stdin.read(1)
+                rtloglevel.setLevel(keyinput, True)
             # Always try printing any accumulated log files first
             rtloglevel.displayLogs()
             if event is None:
@@ -364,6 +394,7 @@ def main(server, eventHandler, tf = TerminalFilter):
             if ioerror.args[0] == 4:
                 pass
         except KeyboardInterrupt:
+            stdin_mgr.restore()
             termfilter.clearFooter()
             if main.shutdown == 1:
                 print("\nSecond Keyboard Interrupt, stopping...\n")
@@ -375,6 +406,7 @@ def main(server, eventHandler, tf = TerminalFilter):
             main.shutdown = main.shutdown + 1
             pass
 
+    stdin_mgr.restore()
     summary = ""
     if taskfailures:
         summary += pluralise("\nSummary: %s task failed:",
Signature · 1 line
1.7.10
#4 lore raw

PATCH v3 4/15 msg.py, knotty.py: Allow dynamic toggle of the debug log level

In reply to Jason Wessel

If stdin is a controlling tty, make it possible to have log levels 1-4 where you can press a key to dynamically change the log level, while bitbake is running to see what is going on.

1 = default log level
2 = multiple log tail of bitbake tasks
3 = bit bake debug messages
4 = bitbake debug messages + multiple lot tail of bitbake tasks

In order to make this possible a slight modification to the msg logfilter was needed to make it possible to get an object so as to change the filter log level.

---
 lib/bb/msg.py       |    9 ++++++++-
 lib/bb/ui/knotty.py |   21 ++++++++++++++++++---
 2 files changed, 26 insertions(+), 4 deletions(-)
lib/bb/msg.py +8 -1
index 9b39325..4b2f90e 100644
@@ -86,6 +86,13 @@ class BBLogFilter(object):
         handler.setLevel(loglevel)
         handler.addFilter(self)
 
+    def setFiltLevel(self, handler, level):
+        self.stdlevel = level
+        handler.setLevel(level)
+
+    def getFiltLevel(self):
+        return self.stdlevel
+
     def filter(self, record):
         if record.levelno >= self.stdlevel:
             return True
@@ -131,7 +138,7 @@ def addDefaultlogFilter(handler):
         dlevel = len(tuple(iterator))
         debug_domains["BitBake.%s" % domainarg] = logging.DEBUG - dlevel + 1
 
-    BBLogFilter(handler, level, debug_domains)
+    return BBLogFilter(handler, level, debug_domains)
 
 #
 # Message handling functions
lib/bb/ui/knotty.py +18 -3
index f72f0ad..7a7a1b2 100644
@@ -135,8 +135,11 @@ class StdinMgr:
             termios.tcsetattr(self.fd, termios.TCSANOW, new)
 
 class RtLogLevel:
-    def __init__(self, mlt):
+    def __init__(self, handler, logfilter, mlt):
         self.displaytail = False
+        self.handler = handler
+        self.logfilter = logfilter
+        self.defaultLevel = logfilter.getFiltLevel()
         self.mlt = mlt
 
     def displayLogs(self):
@@ -147,10 +150,22 @@ class RtLogLevel:
         if input == "1":
             if verbose:
                 print "NOTE: Turning off real time log tail"
+            self.logfilter.setFiltLevel(self.handler, self.defaultLevel)
             self.displaytail = False
         elif input == "2":
             if verbose:
                 print "NOTE: Turning on real time log tail"
+            self.logfilter.setFiltLevel(self.handler, self.defaultLevel)
+            self.displaytail = True
+        elif input == "3":
+            if verbose:
+                print "NOTE: Turning on DEBUG logging"
+            self.logfilter.setFiltLevel(self.handler, logging.DEBUG)
+            self.displaytail = False
+        elif input == "4":
+            if verbose:
+                print "NOTE: Turning on DEBUG logging + real time log tail"
+            self.logfilter.setFiltLevel(self.handler, logging.DEBUG)
             self.displaytail = True
 
 def main(server, eventHandler, tf = TerminalFilter):
@@ -171,8 +186,8 @@ def main(server, eventHandler, tf = TerminalFilter):
 
     console = logging.StreamHandler(sys.stdout)
     format = bb.msg.BBLogFormatter("%(levelname)s: %(message)s")
-    bb.msg.addDefaultlogFilter(console)
-    rtloglevel = RtLogLevel(mlt)
+    logfilter = bb.msg.addDefaultlogFilter(console)
+    rtloglevel = RtLogLevel(console, logfilter, mlt)
     bb_rt_loglevel = server.runCommand(["getVariable", "BB_RT_LOGLEVEL"])
     if bb_rt_loglevel and bb_rt_loglevel != "":
         rtloglevel.setLevel(bb_rt_loglevel, False)
Signature · 1 line
1.7.10
#5 lore raw

PATCH v3 5/15 knotty.py: Add the ability to spawn screen directly from knotty with OE_TERMINAL=screen_inline

In reply to Jason Wessel

The oe-core has a change pending to add the screen_inline class.

This change allows the simple use case of directly using a devshell from the controlling terminal that started bitbake which is a significant convience for some use cases.

---
 lib/bb/ui/knotty.py |   10 ++++++++++
 1 file changed, 10 insertions(+)
lib/bb/ui/knotty.py +10 -0
index 7a7a1b2..b4125f6 100644
@@ -174,6 +174,10 @@ def main(server, eventHandler, tf = TerminalFilter):
     includelogs = server.runCommand(["getVariable", "BBINCLUDELOGS"])
     loglines = server.runCommand(["getVariable", "BBINCLUDELOGS_LINES"])
     consolelogfile = server.runCommand(["getVariable", "BB_CONSOLELOG"])
+    if sys.stdin.isatty() and sys.stdout.isatty():
+        runscreen = True
+    else:
+        runscreen = False
 
     # MultiTail affected varialbles
     numthreads = server.runCommand(["getVariable", "BB_NUMBER_THREADS"])
@@ -260,6 +264,12 @@ def main(server, eventHandler, tf = TerminalFilter):
                     errors = errors + 1
                     return_value = 1
                 elif event.levelno == format.WARNING:
+                    msg = event.getMessage()
+                    if runscreen and event.name == "BitBake.OE.Terminal" and msg.startswith("Screen Connect Command: "):
+                        msg = msg[24:]
+                        print "Starting terminal with: %s" % msg
+                        os.system(msg)
+                        continue
                     warnings = warnings + 1
                 # For "normal" logging conditions, don't show note logs from tasks
                 # but do show them if the user has changed the default log level to 
Signature · 1 line
1.7.10
#6 lore raw

PATCH v3 6/15 fetch2: Fix missing output from stderr in fetcher logs

In reply to Jason Wessel

There are actually two problems to fix

1) The exception for bb.process.ExecutionError must be processed first because it is a derived from the bb.process.CmdError class and we never reach the ExecutionError otherwise.

2) The stderr needs to be printed as well as stdout to determine the root cause of a fetch failure.

The example I have is that I got a log that looked like:

--
ERROR: Function failed: Network access disabled through
BB_NO_NETWORK but access requested with command
/usr/bin/env wget -t 5 -nv --passive-ftp --no-check-certificate -P /localds 'http://downloads.yoctoproject.org/[...CLIPPED...] url None)
--

That really didn't tell me much, but with this patch I get error above plus the following:

--
STDERR: /net/[...CLIPPED...]kernel-tools.git: Read-only file system --

Having the ability to see that the build was trying to write to a read-only file system was a good clue that the fetcher is broken in some other way to be fixed in a follow on patch, but let us fix the logging problem first.

---
 lib/bb/fetch2/__init__.py |    5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
lib/bb/fetch2/__init__.py +2 -3
index 3391e6a..ba562a8 100644
@@ -421,11 +421,10 @@ def runfetchcmd(cmd, d, quiet = False, cleanup = []):
         success = True
     except bb.process.NotFoundError as e:
         error_message = "Fetch command %s" % (e.command)
+    except bb.process.ExecutionError as e:
+        error_message = "Fetch command %s failed with exit code %s, output:\nSTDOUT: %s\nSTDERR: %s" % (e.command, e.exitcode, e.stdout, e.stderr)
     except bb.process.CmdError as e:
         error_message = "Fetch command %s could not be run:\n%s" % (e.command, e.msg)
-    except bb.process.ExecutionError as e:
-        error_message = "Fetch command %s failed with exit code %s, output:\n%s" % (e.command, e.exitcode, e.stderr)
-
     if not success:
         for f in cleanup:
             try:
Signature · 1 line
1.7.10
#7 lore raw

PATCH v3 7/15 fetch2/git.py: Use local download dir, when using an external read-only GITDIR

In reply to Jason Wessel

When building the yocto kernel or yocto kernel tools, if the GITDIR is on a read-only server that is shared and updated by via some cron jobs, the fetch2 should not try to write to that area. The end result will be odd failures if you have download turned off, or extra needless downloading if you have download turned on.

The fetch2 should prefer to create mirror the mirror clones in the local "downloads" directory in the work space.

---
 lib/bb/fetch2/git.py |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
lib/bb/fetch2/git.py +4 -1
index bcc0da5..59d95cb 100644
@@ -136,8 +136,11 @@ class Git(FetchMethod):
                 gitsrcname = gitsrcname + '_' + ud.revisions[name]
         ud.mirrortarball = 'git2_%s.tar.gz' % (gitsrcname)
         ud.fullmirror = os.path.join(data.getVar("DL_DIR", d, True), ud.mirrortarball)
-        ud.clonedir = os.path.join(data.expand('${GITDIR}', d), gitsrcname)
+        ud.gitdir = os.path.join(data.expand('${GITDIR}', d), gitsrcname)
+        ud.clonedir = os.path.join(data.getVar("DL_DIR", d, True), gitsrcname)
 
+        if os.path.exists(ud.gitdir):
+            ud.clonedir = ud.gitdir
         ud.localfile = ud.clonedir
 
     def localpath(self, url, ud, d):
Signature · 1 line
1.7.10
#8 lore raw

PATCH v3 8/15 knotty.py, knotty2, py: Flush and update footer on dynamic log level change

In reply to Jason Wessel

This patch adds a call to update the task list after changing log modes dynamically such that you can immediately see the remaining tasks. After adding this functionality, it became obvious there was a problem flushing data loaded into stdout because the task list would not appear immediately. Doing something like "bitbake IMAGE | tee /tmp/log" is where the flush problem manifests itself the most.

---
 lib/bb/ui/knotty.py  |   14 ++++++++++++--
 lib/bb/ui/knotty2.py |    4 ++++
 2 files changed, 16 insertions(+), 2 deletions(-)
lib/bb/ui/knotty.py +12 -2
index b4125f6..d7b1e19 100644
@@ -82,9 +82,16 @@ class TerminalFilter(object):
     def clearFooter(self):
         return
 
+    def updateFooterForce(self):
+        self.printFooter(True)
+
     def updateFooter(self):
-        if not main.shutdown or not self.helper.needUpdate:
-            return
+        self.printFooter(False)
+
+    def printFooter(self, force_update):
+        if not force_update:
+            if not main.shutdown or not self.helper.needUpdate:
+                return
 
         activetasks = self.helper.running_tasks
         runningpids = self.helper.running_pids
@@ -238,6 +245,9 @@ def main(server, eventHandler, tf = TerminalFilter):
             if stdin_mgr.poll():
                 keyinput = sys.stdin.read(1)
                 rtloglevel.setLevel(keyinput, True)
+                termfilter.updateFooterForce()
+                sys.stdout.flush()
+
             # Always try printing any accumulated log files first
             rtloglevel.displayLogs()
             if event is None:
lib/bb/ui/knotty2.py +4 -0
index aa6a408..01693e9 100644
@@ -73,6 +73,10 @@ class TerminalFilter2(object):
             sys.stdout.write(self.curses.tparm(self.ed))
         self.footer_present = False
 
+    def updateFooterForce(self):
+        self.footer_present = False
+        self.updateFooter()
+
     def updateFooter(self):
         if not self.cuu:
             return
Signature · 1 line
1.7.10
#9 lore raw

PATCH v3 9/15 knotty2.py: Fix knotty2 to report something other than 0 of 0 for setscene tasks

In reply to Jason Wessel

Any time knotty2 was running through the setscene tasks it was always reporting the top line as follows for a core-image-minimal build.

Currently 7 running tasks (0 of 0):

With this patch the number of SetScene tasks are tracked and reported with knotty such that it nows looks something like:

Currently 7 running SetScene tasks (342 of 479):

---
 lib/bb/ui/knotty2.py  |    5 ++++-
 lib/bb/ui/uihelper.py |    5 +++++
 2 files changed, 9 insertions(+), 1 deletion(-)
lib/bb/ui/knotty2.py +4 -1
index 01693e9..9e3619b 100644
@@ -97,7 +97,10 @@ class TerminalFilter2(object):
         if self.main.shutdown:
             print("Waiting for %s running tasks to finish:" % len(activetasks))
         else:
-            print("Currently %s running tasks (%s of %s):" % (len(activetasks), self.helper.tasknumber_current, self.helper.tasknumber_total))
+            if self.helper.tasknumber_current == 0:
+                print("Currently %s running SetScene tasks (%s of %s):" % (len(activetasks), self.helper.sc_tasknumber_current, self.helper.sc_tasknumber_total))
+            else:
+                print("Currently %s running tasks (%s of %s):" % (len(activetasks), self.helper.tasknumber_current, self.helper.tasknumber_total))
         for tasknum, task in enumerate(tasks):
             print("%s: %s" % (tasknum, task))
             lines = lines + 1
lib/bb/ui/uihelper.py +5 -0
index 2c78695..84af5a3 100644
@@ -28,6 +28,8 @@ class BBUIHelper:
         self.failed_tasks = []
         self.tasknumber_current = 0
         self.tasknumber_total = 0
+        self.sc_tasknumber_current = 0
+        self.sc_tasknumber_current = 0
 
     def eventHandler(self, event):
         if isinstance(event, bb.build.TaskStarted):
@@ -48,6 +50,9 @@ class BBUIHelper:
             self.running_pids.remove(event.pid)
             self.failed_tasks.append( { 'title' : "%s %s" % (event._package, event._task)})
             self.needUpdate = True
+        if isinstance(event, bb.runqueue.sceneQueueTaskStarted):
+            self.sc_tasknumber_current = event.stats.completed + event.stats.active + event.stats.failed + 1
+            self.sc_tasknumber_total = event.stats.total
         if isinstance(event, bb.runqueue.runQueueTaskStarted):
             self.tasknumber_current = event.stats.completed + event.stats.active + event.stats.failed + 1
             self.tasknumber_total = event.stats.total
Signature · 1 line
1.7.10
#10 lore raw

PATCH v3 10/15 knotty2: Properly adjust for lines longer than terminal size

In reply to Jason Wessel

knotty2 does not handle being resized nor does it work properly if a task line is longer than the terminal size.

The filter handler relies on the sigwinch to properly handle a terminal resize. The cache and parse tasks will try to take over the sigwinch handler, so it must be restored when either of these tasks completes.

---
 lib/bb/ui/knotty.py  |    5 +++++
 lib/bb/ui/knotty2.py |   42 +++++++++++++++++++++++++++++++++++++++---
 2 files changed, 44 insertions(+), 3 deletions(-)
lib/bb/ui/knotty.py +5 -0
index d7b1e19..58fb8f1 100644
@@ -82,6 +82,9 @@ class TerminalFilter(object):
     def clearFooter(self):
         return
 
+    def sigUpdate(self):
+        return
+
     def updateFooterForce(self):
         self.printFooter(True)
 
@@ -332,6 +335,7 @@ def main(server, eventHandler, tf = TerminalFilter):
                 parseprogress.finish()
                 print(("Parsing of %d .bb files complete (%d cached, %d parsed). %d targets, %d skipped, %d masked, %d errors."
                     % ( event.total, event.cached, event.parsed, event.virtuals, event.skipped, event.masked, event.errors)))
+                termfilter.sigUpdate()
                 continue
 
             if isinstance(event, bb.event.CacheLoadStarted):
@@ -343,6 +347,7 @@ def main(server, eventHandler, tf = TerminalFilter):
             if isinstance(event, bb.event.CacheLoadCompleted):
                 cacheprogress.finish()
                 print("Loaded %d entries from dependency cache." % event.num_entries)
+                termfilter.sigUpdate()
                 continue
 
             if isinstance(event, bb.command.CommandFailed):
lib/bb/ui/knotty2.py +39 -3

60 lines not on this page · raw message

Signature · 1 line
1.7.10
#11 lore raw

PATCH v3 11/15 knotty: Merge knotty2 functionality into knotty

In reply to Jason Wessel

The knotty 2 functionality can be activated in realtime by pressing "t" for top mode or reverted with "0" for normal mode.

---
 lib/bb/ui/knotty.py |  172 ++++++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 150 insertions(+), 22 deletions(-)
lib/bb/ui/knotty.py +150 -22
index 58fb8f1..765ad27 100644
@@ -74,50 +74,156 @@ def pluralise(singular, plural, qty):
     else:
         return plural % qty
 
+class InteractConsoleLogFilter(logging.Filter):
+    def __init__(self, tf, format):
+        self.tf = tf
+        self.format = format
+
+    def filter(self, record):
+        if record.levelno == self.format.NOTE and (record.msg.startswith("Running") or record.msg.startswith("package ")):
+            return False
+        self.tf.clearFooter()
+        return True
+
 class TerminalFilter(object):
     def __init__(self, main, helper, console, format):
+        import curses
         self.main = main
+        self.console = console
         self.helper = helper
+        self.topMode = False
+        self.cuu = None
+        self.interactive = sys.stdout.isatty()
+        self.footer_present = False
+        self.lastpids = []
+        self.curses = curses
+        self.confilter = InteractConsoleLogFilter(self, format)
+        self.curses_init = False
+        self.columns = 80
+
+    def cursesInit(self):
+        if self.curses_init:
+            return
+        self.curses_init = True
+        if self.interactive:
+            try:
+                self.curses.setupterm()
+                self.ed = self.curses.tigetstr("ed")
+                if self.ed:
+                    self.cuu = self.curses.tigetstr("cuu")
+                self.columns = self.getTerminalColumns()
+                self.sigUpdate()
+            except Exception as e:
+                self.cuu = None
+
+    def setTopMode(self):
+        if self.topMode:
+            return
+        self.cursesInit()
+        self.topMode = True
+        self.console.addFilter(self.confilter)
+
+    def setNormalMode(self):
+        if not self.topMode:
+            return
+        self.topMode = False
+        try:
+            self.console.removeFilter(self.confilter)
+        except:
+            pass
 
     def clearFooter(self):
-        return
+        if not self.topMode:
+            return
+        if self.footer_present:
+            lines = self.footer_present
+            sys.stdout.write(self.curses.tparm(self.cuu, lines))
+            sys.stdout.write(self.curses.tparm(self.ed))
+        self.footer_present = False
 
-    def sigUpdate(self):
-        return
 
     def updateFooterForce(self):
+        self.footer_present = False
         self.printFooter(True)
 
     def updateFooter(self):
         self.printFooter(False)
 
     def printFooter(self, force_update):
-        if not force_update:
-            if not main.shutdown or not self.helper.needUpdate:
-                return
-
         activetasks = self.helper.running_tasks
+        failedtasks = self.helper.failed_tasks
         runningpids = self.helper.running_pids
+        if self.topMode:
+            if not self.cuu:
+                return
+            if self.footer_present and (self.lastpids == runningpids):
+                return
+            if self.footer_present:
+                self.clearFooter()
+        else:
+            if not force_update:
+                if not main.shutdown or not self.helper.needUpdate:
+                    return
+            if len(runningpids) == 0:
+                return
+            self.helper.getTasks()
 
-        if len(runningpids) == 0:
+        if not activetasks:
             return
-
-        self.helper.getTasks()
-
+        lines = 1
         tasks = []
         for t in runningpids:
             tasks.append("%s (pid %s)" % (activetasks[t]["title"], t))
 
-        if main.shutdown:
+        if self.main.shutdown:
             print("Waiting for %s running tasks to finish:" % len(activetasks))
         else:
-            print("Currently %s running tasks (%s of %s):" % (len(activetasks), self.helper.tasknumber_current, self.helper.tasknumber_total))
+            if self.helper.tasknumber_current == 0:
+                print("Currently %s running SetScene tasks (%s of %s):" % (len(activetasks), self.helper.sc_tasknumber_current, self.helper.sc_tasknumber_total))
+            else:
+                print("Currently %s running tasks (%s of %s):" % (len(activetasks), self.helper.tasknumber_current, self.helper.tasknumber_total))
         for tasknum, task in enumerate(tasks):
-            print("%s: %s" % (tasknum, task))
+            content = "%s: %s" % (tasknum, task)
+            print content
+            lines = lines + 1 + int(len(content) / (self.columns + 1))
+        self.footer_present = lines
+        self.lastpids = runningpids[:]
 
     def finish(self):
         return
 
+    def sigwinch_handle(self, sig, data):
+        self.columns = self.getTerminalColumns()
+
+    def sigUpdate(self):
+        import signal
+        if self.interactive and self.cuu:
+            signal.signal(signal.SIGWINCH, self.sigwinch_handle)
+
+    def getTerminalColumns(self):
+        def ioctl_GWINSZ(fd):
+            try:
+                import fcntl, termios, struct, os
+                cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
+            except:
+                return None
+            return cr
+        cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
+        if not cr:
+            try:
+                fd = os.open(os.ctermid(), os.O_RDONLY)
+                cr = ioctl_GWINSZ(fd)
+                os.close(fd)
+            except:
+                pass
+        if not cr:
+            try:
+                cr = (env['LINES'], env['COLUMNS'])
+            except:
+                cr = (25, 80)
+        return cr[1]
+
+
 class StdinMgr:
     def __init__(self):
         self.stdinbackup = None
@@ -145,23 +251,26 @@ class StdinMgr:
             termios.tcsetattr(self.fd, termios.TCSANOW, new)
 
 class RtLogLevel:
-    def __init__(self, handler, logfilter, mlt):
+    def __init__(self, handler, logfilter, mlt, tf):
         self.displaytail = False
         self.handler = handler
         self.logfilter = logfilter
         self.defaultLevel = logfilter.getFiltLevel()
         self.mlt = mlt
+        self.tf = tf
 
     def displayLogs(self):
         if self.displaytail:
             self.mlt.displayLogs()
 
     def setLevel(self, input, verbose):
-        if input == "1":
+        if input == "1" or input == "0":
             if verbose:
                 print "NOTE: Turning off real time log tail"
             self.logfilter.setFiltLevel(self.handler, self.defaultLevel)
             self.displaytail = False
+            if input == "0" and isinstance(self.tf, TerminalFilter):
+                self.tf.setNormalMode()
         elif input == "2":
             if verbose:
                 print "NOTE: Turning on real time log tail"
@@ -177,6 +286,23 @@ class RtLogLevel:
                 print "NOTE: Turning on DEBUG logging + real time log tail"
             self.logfilter.setFiltLevel(self.handler, logging.DEBUG)
             self.displaytail = True
+        elif input == "t":
+            if verbose:
+                print "NOTE: Activing task \"top\" mode"
+            if isinstance(self.tf, TerminalFilter):
+                self.tf.setTopMode()
+        elif input == "h":
+            print "============================================="
+            print "Interaction help commands:"
+            print " 0 - default with default logs"
+            print " 1 - turn off real time log tail"
+            print " 2 - turn on real time log tail"
+            print " 3 - turn on debug logging"
+            print " 4 - turn on debug logging and real time log tail"
+            print " t - Display tasks in \"top\" mode (formerly knotty2 mode)"
+            print " h - display commands"
+            return False
+        return True
 
 def main(server, eventHandler, tf = TerminalFilter):
 
@@ -201,10 +327,6 @@ def main(server, eventHandler, tf = TerminalFilter):
     console = logging.StreamHandler(sys.stdout)
     format = bb.msg.BBLogFormatter("%(levelname)s: %(message)s")
     logfilter = bb.msg.addDefaultlogFilter(console)
-    rtloglevel = RtLogLevel(console, logfilter, mlt)
-    bb_rt_loglevel = server.runCommand(["getVariable", "BB_RT_LOGLEVEL"])
-    if bb_rt_loglevel and bb_rt_loglevel != "":
-        rtloglevel.setLevel(bb_rt_loglevel, False)
     console.setFormatter(format)
     logger.addHandler(console)
     if consolelogfile:
@@ -241,14 +363,20 @@ def main(server, eventHandler, tf = TerminalFilter):
     termfilter = tf(main, helper, console, format)
     stdin_mgr = StdinMgr()
 
+    rtloglevel = RtLogLevel(console, logfilter, mlt, termfilter)
+    bb_rt_loglevel = server.runCommand(["getVariable", "BB_RT_LOGLEVEL"])
+    if bb_rt_loglevel and bb_rt_loglevel != "":
+        for inputkey in bb_rt_loglevel:
+            rtloglevel.setLevel(inputkey, False)
     while True:
         try:
             termfilter.updateFooter()
             event = eventHandler.waitEvent(0.25)
             if stdin_mgr.poll():
                 keyinput = sys.stdin.read(1)
-                rtloglevel.setLevel(keyinput, True)
-                termfilter.updateFooterForce()
+                termfilter.clearFooter()
+                if (rtloglevel.setLevel(keyinput, True)):
+                    termfilter.updateFooterForce()
                 sys.stdout.flush()
 
             # Always try printing any accumulated log files first
Signature · 1 line
1.7.10
#12 lore raw

PATCH v3 12/15 knotty: Add ability to dynamically toggle log location

In reply to Jason Wessel

Add the ability to see where all the per task logs were written to disk.

The resulting output looks like where [...] is the full path:

NOTE: LOG: [...]/python-2.7.2-r2.20/temp/log.do_package_setscene.8719
NOTE: LOG: [...]/perl-5.14.2-r7/temp/log.do_package_setscene.8760

---
 lib/bb/ui/knotty.py |   13 +++++++++++++
 1 file changed, 13 insertions(+)
lib/bb/ui/knotty.py +13 -0
index 765ad27..e485c7e 100644
@@ -253,6 +253,7 @@ class StdinMgr:
 class RtLogLevel:
     def __init__(self, handler, logfilter, mlt, tf):
         self.displaytail = False
+        self.displayLogLocations = False
         self.handler = handler
         self.logfilter = logfilter
         self.defaultLevel = logfilter.getFiltLevel()
@@ -291,6 +292,14 @@ class RtLogLevel:
                 print "NOTE: Activing task \"top\" mode"
             if isinstance(self.tf, TerminalFilter):
                 self.tf.setTopMode()
+        elif input == "l":
+            if verbose:
+                print "NOTE: Activating log locations display"
+            self.displayLogLocations = True
+        elif input == "L":
+            if verbose:
+                print "NOTE: Disable log locations display"
+            self.displayLogLocations = False
         elif input == "h":
             print "============================================="
             print "Interaction help commands:"
@@ -300,6 +309,7 @@ class RtLogLevel:
             print " 3 - turn on debug logging"
             print " 4 - turn on debug logging and real time log tail"
             print " t - Display tasks in \"top\" mode (formerly knotty2 mode)"
+            print " l - emit log locations (L to turn off)"
             print " h - display commands"
             return False
         return True
@@ -387,6 +397,9 @@ def main(server, eventHandler, tf = TerminalFilter):
                 continue
             helper.eventHandler(event)
             if isinstance(event, bb.build.TaskStarted):
+                if (rtloglevel.displayLogLocations):
+                    termfilter.clearFooter()
+                    print "NOTE: LOG: %s" % event.logfile
                 mlt.openLog(event.logfile, event.pid)
                 rtloglevel.displayLogs()
 
Signature · 1 line
1.7.10
#13 lore raw

PATCH v3 13/15 meta/lib/oe/terminal.py: Add an additional reference to screen called screen_inline

In reply to Jason Wessel

This is a new mode for screen with the explicit purpose of invoking screen on the same terminal that you started bitbake. The bitbake knotty will attempt to launch screen directly when using this setting for OE_TERMINAL.

---
 meta/lib/oe/terminal.py |    7 +++++++
 1 file changed, 7 insertions(+)
meta/lib/oe/terminal.py +7 -0
index 43639d5..ca94e73 100644
@@ -92,6 +92,13 @@ class Rxvt(XTerminal):
     command = 'rxvt -T "{title}" -e {command}'
     priority = 1
 
+class Screen_inline(Terminal):
+    command = 'screen -D -m -t "{title}" -S devshell {command}'
+
+    def __init__(self, command, title=None, env=None):
+        Terminal.__init__(self, command, title, env)
+        logger.warn('Screen Connect Command: screen -r devshell')
+
 class Screen(Terminal):
     command = 'screen -D -m -t "{title}" -S devshell {command}'
 
Signature · 1 line
1.7.10
#14 lore raw

PATCH v3 14/15 terminal.bbclass: Allow OE_TERMINAL_PREFERRED to override the fallback order for OE_TERMINAL

In reply to Jason Wessel

With the addition of two different modes for the use of screen, an end user may prefer to set specific fall back order for an X vs tty environment. This patch modifies the terminal.bbclass and terminal.py to allow the variable OE_TERMINAL_PREFERRED to control the order of trying the various supported OE_TERMINAL's.

---
 meta/classes/terminal.bbclass |    3 ++-
 meta/lib/oe/terminal.py       |    8 +++++---
 2 files changed, 7 insertions(+), 4 deletions(-)
meta/classes/terminal.bbclass +2 -1
index 3cfc84b..2be6974 100644
@@ -4,6 +4,7 @@ OE_TERMINAL[choices] = 'auto none \
                         ${@" ".join(o.name \
                                     for o in oe.terminal.prioritized())}'
 
+OE_TERMINAL_PREFERRED ?= "auto"
 OE_TERMINAL_EXPORTS = 'XAUTHORITY SHELL DBUS_SESSION_BUS_ADDRESS DISPLAY EXTRA_OEMAKE SCREENDIR'
 OE_TERMINAL_EXPORTS[type] = 'list'
 
@@ -34,7 +35,7 @@ def oe_terminal(command, title, d):
             bb.fatal('Unable to spawn terminal %s: %s' % (terminal, exc))
 
     try:
-        oe.terminal.spawn_preferred(command, title)
+        oe.terminal.spawn_preferred(d.getVar('OE_TERMINAL_PREFERRED', True), command, title)
     except oe.terminal.NoSupportedTerminals:
         bb.fatal('No valid terminal found, unable to open devshell')
     except oe.terminal.ExecutionError as exc:
meta/lib/oe/terminal.py +5 -3
index ca94e73..943e5db 100644
@@ -111,11 +111,13 @@ class Screen(Terminal):
 def prioritized():
     return Registry.prioritized()
 
-def spawn_preferred(command, title=None, env=None):
+def spawn_preferred(priorityList, command, title=None, env=None):
     """Spawn the first supported terminal, by priority"""
-    for terminal in prioritized():
+    if priorityList == "auto":
+        priorityList = ' '.join(o.name for o in prioritized())
+    for terminal in priorityList.split():
         try:
-            spawn(terminal.name, command, title, env)
+            spawn(terminal, command, title, env)
             break
         except UnsupportedTerminal:
             continue
Signature · 1 line
1.7.10
#15 lore raw

PATCH v3 15/15 terminal.py: Make screen_inline have a higher priority than screen

In reply to Jason Wessel

The screen_inline is far easier to use and less confusing for beginner users of oe-core. Making this the default improves the end user experience, and it is possible to change the OE_TERMINAL variable as well as the default fall back list with OE_TERMINAL_PREFERRED for anyone who desires the original behavior.

---
 meta/lib/oe/terminal.py |   11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
meta/lib/oe/terminal.py +6 -5
index 943e5db..3122d56 100644
@@ -55,11 +55,11 @@ class XTerminal(Terminal):
 
 class Gnome(XTerminal):
     command = 'gnome-terminal --disable-factory -t "{title}" -x {command}'
-    priority = 2
+    priority = 3
 
 class Xfce(XTerminal):
     command = 'Terminal -T "{title}" -e "{command}"'
-    priority = 2
+    priority = 3
 
     def __init__(self, command, title=None, env=None):
         # Upstream binary name is Terminal but Debian/Ubuntu use
@@ -73,7 +73,7 @@ class Xfce(XTerminal):
 
 class Konsole(XTerminal):
     command = 'konsole -T "{title}" -e {command}'
-    priority = 2
+    priority = 3
 
     def __init__(self, command, title=None, env=None):
         # Check version
@@ -86,14 +86,15 @@ class Konsole(XTerminal):
 
 class XTerm(XTerminal):
     command = 'xterm -T "{title}" -e {command}'
-    priority = 1
+    priority = 2
 
 class Rxvt(XTerminal):
     command = 'rxvt -T "{title}" -e {command}'
-    priority = 1
+    priority = 2
 
 class Screen_inline(Terminal):
     command = 'screen -D -m -t "{title}" -S devshell {command}'
+    priority = 1
 
     def __init__(self, command, title=None, env=None):
         Terminal.__init__(self, command, title, env)
Signature · 1 line
1.7.10