Skip to content

Commit 012d30e

Browse files
committed
Add try_connect method to Client class
1 parent 9455941 commit 012d30e

2 files changed

Lines changed: 39 additions & 4 deletions

File tree

cloudbot/client.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import asyncio
22
import collections
33
import logging
4+
import random
45

56
from cloudbot.permissions import PermissionManager
67

@@ -59,7 +60,20 @@ def describe_server(self):
5960
raise NotImplementedError
6061

6162
@asyncio.coroutine
62-
def connect(self):
63+
def try_connect(self):
64+
timeout = 30
65+
while True:
66+
try:
67+
yield from self.connect(timeout)
68+
except Exception:
69+
logger.exception("[%s] Error occurred while connecting.")
70+
else:
71+
break
72+
73+
yield from asyncio.sleep(random.randrange(timeout))
74+
75+
@asyncio.coroutine
76+
def connect(self, timeout=None):
6377
"""
6478
Connects to the server, or reconnects if already connected.
6579
"""

cloudbot/clients/irc.py

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import asyncio
22
import logging
3+
import random
34
import re
45
import ssl
56
from _ssl import PROTOCOL_SSLv23
@@ -106,7 +107,20 @@ def describe_server(self):
106107
return "{}:{}".format(self.server, self.port)
107108

108109
@asyncio.coroutine
109-
def connect(self):
110+
def try_connect(self):
111+
timeout = self.config["connection"].get("timeout", 30)
112+
while True:
113+
try:
114+
yield from self.connect(timeout)
115+
except (asyncio.TimeoutError, OSError):
116+
logger.exception("[%s] Error occurred while connecting", self.name)
117+
else:
118+
break
119+
120+
yield from asyncio.sleep(random.randrange(timeout))
121+
122+
@asyncio.coroutine
123+
def connect(self, timeout=None):
110124
"""
111125
Connects to the IRC server, or reconnects if already connected.
112126
"""
@@ -125,8 +139,15 @@ def connect(self):
125139
optional_params = {}
126140
if self.local_bind:
127141
optional_params["local_addr"] = self.local_bind
128-
self._transport, self._protocol = yield from self.loop.create_connection(
129-
lambda: _IrcProtocol(self), host=self.server, port=self.port, ssl=self.ssl_context, **optional_params)
142+
143+
coro = self.loop.create_connection(
144+
lambda: _IrcProtocol(self), host=self.server, port=self.port, ssl=self.ssl_context, **optional_params
145+
)
146+
147+
if timeout is not None:
148+
coro = asyncio.wait_for(coro, timeout)
149+
150+
self._transport, self._protocol = yield from coro
130151

131152
tasks = [
132153
self.bot.plugin_manager.launch(hook, Event(bot=self.bot, conn=self, hook=hook))

0 commit comments

Comments
 (0)