ui: add an uninterruptable context manager that can block SIGINT
authorAugie Fackler <augie@google.com>
Wed, 27 Jun 2018 10:47:14 -0400
changeset 38526 313a940d49a3
parent 38525 c153f440682f
child 38527 6e0c66ef8cd0
ui: add an uninterruptable context manager that can block SIGINT The blocking of SIGINT is not done by default, but my hope is that we will one day. This was inspired by Facebook's "nointerrupt" extension, which is a bit more heavy-handed than this (whole commands are treated as unsafe to interrupt). A future patch will enable this for varying bits of Mercurial that are performing unsafe operations. It's intentional that the KeyboardInterrupt is raised as the context manager exits: during the span of the context manager interrupting Mercurial could lead to data loss, but typically those spans are fairly narrow, so we can let the unsafe block complete and then terminate hg (which will leave the repo in a consistent state, even if it's not the user's desired state). .. api:: New context manager ``ui.uninterruptable()`` to mark portions of a command as potentially unsafe places to interrupt Mercurial with Control-C or similar. Differential Revision: https://phab.mercurial-scm.org/D3716
mercurial/configitems.py
mercurial/ui.py
mercurial/utils/procutil.py
tests/test-nointerrupt.t
--- a/mercurial/configitems.py	Tue Jul 03 12:22:37 2018 -0400
+++ b/mercurial/configitems.py	Wed Jun 27 10:47:14 2018 -0400
@@ -560,6 +560,9 @@
 coreconfigitem('experimental', 'mergedriver',
     default=None,
 )
+coreconfigitem('experimental', 'nointerrupt', default=False)
+coreconfigitem('experimental', 'nointerrupt-interactiveonly', default=True)
+
 coreconfigitem('experimental', 'obsmarkers-exchange-debug',
     default=False,
 )
--- a/mercurial/ui.py	Tue Jul 03 12:22:37 2018 -0400
+++ b/mercurial/ui.py	Wed Jun 27 10:47:14 2018 -0400
@@ -224,6 +224,7 @@
         self._colormode = None
         self._terminfoparams = {}
         self._styles = {}
+        self._uninterruptible = False
 
         if src:
             self.fout = src.fout
@@ -334,6 +335,37 @@
             self._blockedtimes[key + '_blocked'] += \
                 (util.timer() - starttime) * 1000
 
+    @contextlib.contextmanager
+    def uninterruptable(self):
+        """Mark an operation as unsafe.
+
+        Most operations on a repository are safe to interrupt, but a
+        few are risky (for example repair.strip). This context manager
+        lets you advise Mercurial that something risky is happening so
+        that control-C etc can be blocked if desired.
+        """
+        enabled = self.configbool('experimental', 'nointerrupt')
+        if (enabled and
+            self.configbool('experimental', 'nointerrupt-interactiveonly')):
+            enabled = self.interactive()
+        if self._uninterruptible or not enabled:
+            # if nointerrupt support is turned off, the process isn't
+            # interactive, or we're already in an uninterruptable
+            # block, do nothing.
+            yield
+            return
+        def warn():
+            self.warn(_("shutting down cleanly\n"))
+            self.warn(
+                _("press ^C again to terminate immediately (dangerous)\n"))
+            return True
+        with procutil.uninterruptable(warn):
+            try:
+                self._uninterruptible = True
+                yield
+            finally:
+                self._uninterruptible = False
+
     def formatter(self, topic, opts):
         return formatter.formatter(self, self, topic, opts)
 
--- a/mercurial/utils/procutil.py	Tue Jul 03 12:22:37 2018 -0400
+++ b/mercurial/utils/procutil.py	Wed Jun 27 10:47:14 2018 -0400
@@ -415,3 +415,36 @@
     finally:
         if prevhandler is not None:
             signal.signal(signal.SIGCHLD, prevhandler)
+
+@contextlib.contextmanager
+def uninterruptable(warn):
+    """Inhibit SIGINT handling on a region of code.
+
+    Note that if this is called in a non-main thread, it turns into a no-op.
+
+    Args:
+      warn: A callable which takes no arguments, and returns True if the
+            previous signal handling should be restored.
+    """
+
+    oldsiginthandler = [signal.getsignal(signal.SIGINT)]
+    shouldbail = []
+
+    def disabledsiginthandler(*args):
+        if warn():
+            signal.signal(signal.SIGINT, oldsiginthandler[0])
+            del oldsiginthandler[0]
+        shouldbail.append(True)
+
+    try:
+        try:
+            signal.signal(signal.SIGINT, disabledsiginthandler)
+        except ValueError:
+            # wrong thread, oh well, we tried
+            del oldsiginthandler[0]
+        yield
+    finally:
+        if oldsiginthandler:
+            signal.signal(signal.SIGINT, oldsiginthandler[0])
+        if shouldbail:
+            raise KeyboardInterrupt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tests/test-nointerrupt.t	Wed Jun 27 10:47:14 2018 -0400
@@ -0,0 +1,83 @@
+Dummy extension simulating unsafe long running command
+  $ cat > sleepext.py <<EOF
+  > import time
+  > import itertools
+  > 
+  > from mercurial import registrar
+  > from mercurial.i18n import _
+  > 
+  > cmdtable = {}
+  > command = registrar.command(cmdtable)
+  > 
+  > @command(b'sleep', [], _(b'TIME'), norepo=True)
+  > def sleep(ui, sleeptime=b"1", **opts):
+  >     with ui.uninterruptable():
+  >         for _i in itertools.repeat(None, int(sleeptime)):
+  >             time.sleep(1)
+  >         ui.warn(b"end of unsafe operation\n")
+  >     ui.warn(b"%s second(s) passed\n" % sleeptime)
+  > EOF
+
+Kludge to emulate timeout(1) which is not generally available.
+  $ cat > timeout.py <<EOF
+  > from __future__ import print_function
+  > import argparse
+  > import signal
+  > import subprocess
+  > import sys
+  > import time
+  > 
+  > ap = argparse.ArgumentParser()
+  > ap.add_argument('-s', nargs=1, default='SIGTERM')
+  > ap.add_argument('duration', nargs=1, type=int)
+  > ap.add_argument('argv', nargs='*')
+  > opts = ap.parse_args()
+  > try:
+  >     sig = int(opts.s[0])
+  > except ValueError:
+  >     sname = opts.s[0]
+  >     if not sname.startswith('SIG'):
+  >         sname = 'SIG' + sname
+  >     sig = getattr(signal, sname)
+  > proc = subprocess.Popen(opts.argv)
+  > time.sleep(opts.duration[0])
+  > proc.poll()
+  > if proc.returncode is None:
+  >     proc.send_signal(sig)
+  >     proc.wait()
+  >     sys.exit(124)
+  > EOF
+
+Set up repository
+  $ hg init repo
+  $ cd repo
+  $ cat >> $HGRCPATH << EOF
+  > [extensions]
+  > sleepext = ../sleepext.py
+  > EOF
+
+Test ctrl-c
+  $ python $TESTTMP/timeout.py -s INT 1 hg sleep 2
+  interrupted!
+  [124]
+
+  $ cat >> $HGRCPATH << EOF
+  > [experimental]
+  > nointerrupt = yes
+  > EOF
+
+  $ python $TESTTMP/timeout.py -s INT 1 hg sleep 2
+  interrupted!
+  [124]
+
+  $ cat >> $HGRCPATH << EOF
+  > [experimental]
+  > nointerrupt-interactiveonly = False
+  > EOF
+
+  $ python $TESTTMP/timeout.py -s INT 1 hg sleep 2
+  shutting down cleanly
+  press ^C again to terminate immediately (dangerous)
+  end of unsafe operation
+  interrupted!
+  [124]