| 1 |
# connectionpool.py - class for pooling peer connections for reuse |
| 2 |
# |
| 3 |
# Copyright 2017 Facebook, Inc. |
| 4 |
# |
| 5 |
# This software may be used and distributed according to the terms of the |
| 6 |
# GNU General Public License version 2 or any later version. |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
from mercurial import ( |
| 11 |
sshpeer, |
| 12 |
) |
| 13 |
from mercurial.repo import ( |
| 14 |
factory as repo_factory, |
| 15 |
) |
| 16 |
|
| 17 |
_sshv1peer = sshpeer.sshv1peer |
| 18 |
|
| 19 |
|
| 20 |
class connectionpool: |
| 21 |
def __init__(self, repo): |
| 22 |
self._repo = repo |
| 23 |
self._pool = dict() |
| 24 |
|
| 25 |
def get(self, path): |
| 26 |
pathpool = self._pool.get(path) |
| 27 |
if pathpool is None: |
| 28 |
pathpool = list() |
| 29 |
self._pool[path] = pathpool |
| 30 |
|
| 31 |
conn = None |
| 32 |
if len(pathpool) > 0: |
| 33 |
try: |
| 34 |
conn = pathpool.pop() |
| 35 |
peer = conn.peer |
| 36 |
# If the connection has died, drop it |
| 37 |
if isinstance(peer, _sshv1peer): |
| 38 |
if peer._subprocess.poll() is not None: |
| 39 |
conn = None |
| 40 |
except IndexError: |
| 41 |
pass |
| 42 |
|
| 43 |
if conn is None: |
| 44 |
peer = repo_factory.peer(self._repo.ui, {}, path) |
| 45 |
if hasattr(peer, '_cleanup'): |
| 46 |
|
| 47 |
class mypeer(peer.__class__): |
| 48 |
def _cleanup(self, warn=None): |
| 49 |
# close pipee first so peer.cleanup reading it won't |
| 50 |
# deadlock, if there are other processes with pipeo |
| 51 |
# open (i.e. us). |
| 52 |
if hasattr(self, 'pipee'): |
| 53 |
self.pipee.close() |
| 54 |
return super()._cleanup() |
| 55 |
|
| 56 |
peer.__class__ = mypeer |
| 57 |
|
| 58 |
conn = connection(pathpool, peer) |
| 59 |
|
| 60 |
return conn |
| 61 |
|
| 62 |
def close(self): |
| 63 |
for pathpool in self._pool.values(): |
| 64 |
for conn in pathpool: |
| 65 |
conn.close() |
| 66 |
del pathpool[:] |
| 67 |
|
| 68 |
|
| 69 |
class connection: |
| 70 |
def __init__(self, pool, peer): |
| 71 |
self._pool = pool |
| 72 |
self.peer = peer |
| 73 |
|
| 74 |
def __enter__(self): |
| 75 |
return self |
| 76 |
|
| 77 |
def __exit__(self, type, value, traceback): |
| 78 |
# Only add the connection back to the pool if there was no exception, |
| 79 |
# since an exception could mean the connection is not in a reusable |
| 80 |
# state. |
| 81 |
if type is None: |
| 82 |
self._pool.append(self) |
| 83 |
else: |
| 84 |
self.close() |
| 85 |
|
| 86 |
def close(self): |
| 87 |
if hasattr(self.peer, 'cleanup'): |
| 88 |
self.peer.cleanup() |