Skip to contentSkip to conversation

Multiplexed task logs / bitbake fixes for fetch2

PATCH Superseded Jason Wessel 1 participant 10 messages Jun 1, 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 second version of fixes and features for bit bake logging.

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 8/9 - 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.

#1 lore raw

PATCH v2 1/9 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 v2 2/9 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 v2 3/9 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 v2 4/9 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 v2 5/9 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 v2 6/9 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 v2 7/9 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 v2 8/9 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
#9 lore raw

PATCH v2 9/9 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