cluster.py 9.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
#
# Copyright (c) 2011 Nexedi SARL and Contributors. All Rights Reserved.
#                    Julien Muchembled <jm@nexedi.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

import __builtin__
import errno
import mmap
import os
import psutil
import signal
import socket
import sys
import tempfile
from cPickle import dumps, loads
from functools import wraps
from time import time, sleep
from neo.lib import debug


class SocketLock(object):
    """Basic system-wide lock"""

    _socket = None

    def __init__(self, address, family=socket.AF_UNIX, type=socket.SOCK_DGRAM):
        if family == socket.AF_UNIX:
            address = '\0' + address
        self.address = address
        self.socket_args = family, type

    def locked(self):
        return self._socket is not None

    def acquire(self, blocking=1):
        assert self._socket is None
        s = socket.socket(*self.socket_args)
        try:
            while True:
                try:
                    s.bind(self.address)
                except socket.error, e:
                    if e[0] != errno.EADDRINUSE:
                        raise
                    if not blocking:
                        return False
                    sleep(1)
                else:
                    self._socket = s
                    return True
        finally:
            if self._socket is None:
                s.close()

    def release(self):
        s = self._socket
        del self._socket
        s.close()


class ClusterDict(dict):
    """Simple storage (dict), shared with forked processes"""

    _acquired = 0

    def __init__(self, *args, **kw):
        dict.__init__(self, *args, **kw)
        self._r, self._w = os.pipe()
        # shm_open(3) would be better but Python doesn't provide it.
        # See also http://nikitathespider.com/python/shm/
84
        with tempfile.TemporaryFile() as f:
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
            f.write(dumps(self.copy(), -1))
            f.flush()
            self._shared = mmap.mmap(f.fileno(), f.tell())
        self.release()

    def __del__(self):
        try:
            os.close(self._r)
            os.close(self._w)
        except TypeError: # if os.close is None
            pass

    def acquire(self):
        self._acquired += 1
        if not self._acquired:
            os.read(self._r, 1)
            try:
                self.clear()
                shared = self._shared
                shared.resize(shared.size())
                self.update(loads(shared[:]))
            except:
                self.release()
                raise

    def release(self, commit=False):
        if not self._acquired:
            if commit:
                self.commit()
            os.write(self._w, '\0')
        self._acquired -= 1

    def commit(self):
        shared = self._shared
        p = dumps(self.copy(), -1)
        shared.resize(len(p))
        shared[:] = p

cluster_dict = ClusterDict()


class ClusterPdb(object):
    """Multiprocess-aware wrapper around console and winpdb debuggers

    __call__ is the method to break.

    TODO: monkey-patch normal code not to timeout
          if another node is being debugged
    """

    def __init__(self):
        self._count_dict = {}

    def __setattr__(self, name, value):
        try:
            hook = getattr(self, name)
            setattr(value.im_self, value.__name__, wraps(value)(
                lambda *args, **kw: hook(value, *args, **kw)))
        except AttributeError:
            object.__setattr__(self, name, value)

    @property
    def broken_peer(self):
        return self._getLastPdb(os.getpid()) is None

    def __call__(self, max_count=None, depth=0, text=None):
        depth += 1
        if max_count:
            frame = sys._getframe(depth)
            key = id(frame.f_code), frame.f_lineno
            del frame
            self._count_dict[key] = count = 1 + self._count_dict.get(key, 0)
            if max_count < count:
                return
        if not text:
            try:
                import rpdb2
            except ImportError:
                if text is not None:
                    raise
            else:
                if rpdb2.g_debugger is None:
                    rpdb2_CStateManager = rpdb2.CStateManager
                    def CStateManager(*args, **kw):
                        rpdb2.CStateManager = rpdb2_CStateManager
                        state_manager = rpdb2.CStateManager(*args, **kw)
                        self._rpdb2_set_state = state_manager.set_state
                        return state_manager
                    rpdb2.CStateManager = CStateManager
                return debug.winpdb(depth)
        try:
            debugger = self.__dict__['_debugger']
        except KeyError:
            assert 'rpdb2' not in sys.modules
            self._debugger = debugger = debug.getPdb()
            self._bdb_interaction = debugger.interaction
        return debugger.set_trace(sys._getframe(depth))

    def kill(self, pid, sig):
        force = []
        sigint_handler = None
        try:
            while 1:
                cluster_dict.acquire()
                try:
                    last_pdb = cluster_dict.get('last_pdb', {})
                    if force or pid not in last_pdb:
                        os.kill(pid, sig)
                        last_pdb.pop(pid, None)
                        cluster_dict.commit()
                        break
                    try:
                        if psutil.Process(pid).status == psutil.STATUS_ZOMBIE:
                            break
                    except psutil.NoSuchProcess:
                        raise OSError(errno.ESRCH, 'No such process')
                finally:
                    cluster_dict.release()
                if sigint_handler is None:
                    sigint_handler = signal.signal(signal.SIGINT,
                        lambda *args: force.append(None))
                    sys.stderr.write('Pid %u is/was debugged.'
                                    ' Press ^C to kill it...' % pid)
                sleep(1)
        finally:
            if sigint_handler is not None:
                signal.signal(signal.SIGINT, sigint_handler)
        if force:
            sys.stderr.write('\n')

    def _lock_console(self):
        while 1:
            cluster_dict.acquire()
            try:
                if 'text_pdb' not in cluster_dict:
                    cluster_dict['text_pdb'] = pid = os.getpid()
                    cluster_dict.setdefault('last_pdb', {})[pid] = None
                    cluster_dict.commit()
                    break
            finally:
                cluster_dict.release()
            sleep(0.5)

    def _unlock_console(self):
        cluster_dict.acquire()
        try:
            pid = cluster_dict.pop('text_pdb')
            cluster_dict['last_pdb'][pid] = time()
            cluster_dict.commit()
        finally:
            cluster_dict.release()

    def _bdb_interaction(self, hooked, *args, **kw):
        self._lock_console()
        try:
            return hooked(*args, **kw)
        finally:
            self._unlock_console()

    def _rpdb2_set_state(self, hooked, state=None, *args, **kw):
        from rpdb2 import STATE_BROKEN, STATE_DETACHED
        cluster_dict.acquire()
        try:
            if state is None:
                state = hooked.im_self.get_state()
            last_pdb = cluster_dict.setdefault('last_pdb', {})
            pid = os.getpid()
            if state == STATE_DETACHED:
                last_pdb.pop(pid, None)
            else:
                last_pdb[pid] = state != STATE_BROKEN and time() or None
            return hooked(state=state, *args, **kw)
        finally:
            cluster_dict.release(True)

    def _getLastPdb(self, *exclude):
        result = 0
        for pid, last_pdb in cluster_dict.get('last_pdb', {}).iteritems():
            if pid not in exclude:
                if last_pdb is None:
                    return
                if result < last_pdb:
                    result = last_pdb
        return result

270
    def wait(self, test, timeout):
271
        end_time = time() + timeout
272
        period = 0.1
273 274 275 276
        while not test():
            cluster_dict.acquire()
            try:
                last_pdb = self._getLastPdb()
277 278 279 280 281 282 283 284 285
                if last_pdb is None:
                    next_sleep = 1
                else:
                    next_sleep = max(last_pdb + timeout, end_time) - time()
                    if next_sleep > period:
                        next_sleep = period
                        period *= 1.5
                    elif next_sleep < 0:
                        return False
286 287
            finally:
                cluster_dict.release()
288
            sleep(next_sleep)
289 290 291 292 293
        return True

__builtin__.pdb = ClusterPdb()

signal.signal(signal.SIGUSR2, debug.decorate(lambda sig, frame: pdb(depth=2)))