Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set up db connections to use SOCKS proxy in Development environment #756

Merged
merged 5 commits into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ attrs = "==18.2.0"
pytest-cov = "*"
supervisor = "~=4.2"
yoyo-migrations = "==7.3.2"
pysocks = "*"

# Versions required for dependabot
sqlparse = "~=0.5.0"
Expand Down
198 changes: 114 additions & 84 deletions Pipfile.lock

Large diffs are not rendered by default.

22 changes: 11 additions & 11 deletions wp1/credentials.py.example
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,18 @@ CONF_LANG = 'en'
CREDENTIALS = {
Environment.DEVELOPMENT: {
# Database credentials for the wikipedia replica database.
# For development, you can use your toolforge credentials and connect
# to a live replica via an SSH tunnel, as outlined here:
# https://wikitech.wikimedia.org/wiki/Help:Toolforge/Database#Connecting_to_the_database_replicas_from_your_own_computer
# The 'local port' you use, 4711 in the example, will correspond to the
# port you set below.
# For development, start a SOCKS5 proxy connection to login.toolforge.org
# with the command:
# $ ssh -D 1080 login.toolforge.org
# (This is assuming you have set up your SSH credentials for Toolforge)
# Database traffic will be tunneled through this proxy, so that URLs
# inside of *.eqiad.wmflabs can be resolved.
'WIKIDB': {
'user': 'yourtoolforgeuser', # EDIT this line
'password': 'yourtoolforgepass', # EDIT this line
'host': 'localhost',
'port': 4711,
'db': 'enwiki_p',
},
'user': 'someuser', # EDIT this line for production.
'password': 'somepass', # EDIT this line for production.
'host': 'enwiki.analytics.db.svc.eqiad.wmflabs',
'db': 'enwiki_p',
},

# Database credentials for the enwp10 project/application database.
# For development, use the docker-compose-dev.yml file and spin up a
Expand Down
22 changes: 18 additions & 4 deletions wp1/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import pymysql
import pymysql.cursors
import pymysql.err
import socks

logger = logging.getLogger(__name__)

Expand All @@ -19,22 +20,35 @@
RETRY_TIME_SECONDS = 5


def connect(db_name):
def connect(db_name, **overrides):
creds = CREDENTIALS[ENV].get(db_name)
if creds is None:
raise ValueError('db credentials for %r in ENV=%s are None')
raise ValueError('db credentials for %r in ENV=%s are None' %
(db_name, ENV))

kwargs = {
'charset': None,
'use_unicode': False,
'cursorclass': pymysql.cursors.SSDictCursor,
**creds
**creds,
**overrides
}

tries = 4
while True:
try:
return pymysql.connect(**kwargs)
if db_name == 'WIKIDB' and ENV == ENV.DEVELOPMENT:
# In development, connect through a SOCKS5 proxy so that hosts on
# *.eqiad.wmflabs can be reached.
s = socks.socksocket()
s.set_proxy(socks.SOCKS5, 'localhost')
s.connect((kwargs['host'], kwargs.get('port', 3306)))
conn = pymysql.connect(**kwargs, defer_connect=True)
conn.connect(sock=s)
else:
conn = pymysql.connect(**kwargs)

return conn
except pymysql.err.InternalError:
if tries > 0:
logging.warning('Could not connect to database, retrying in %s seconds',
Expand Down
31 changes: 30 additions & 1 deletion wp1/db_test.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import unittest
from unittest.mock import patch
from unittest.mock import MagicMock, patch

import pymysql.err
import socks

from wp1.environment import Environment

Expand Down Expand Up @@ -30,3 +31,31 @@ def test_retries_four_times_failure(self, patched_sleep, patched_pymysql):
with self.assertRaises(pymysql.err.InternalError):
connect('WP10DB')
self.assertEqual(5, patched_pymysql.call_count)

@patch('wp1.db.pymysql.connect')
@patch('wp1.db.socks.socksocket')
@patch('wp1.db.ENV', Environment.DEVELOPMENT)
def test_socks_proxy(self, mock_socket, mock_connect):
from wp1.db import connect

socket = MagicMock()
mock_socket.return_value = socket
conn = MagicMock()
mock_connect.return_value = conn

connect('WIKIDB', host='foo.wikimedia.cloud', port=6000)

socket.set_proxy.assert_called_once_with(socks.SOCKS5, 'localhost')
socket.connect.assert_called_once_with(('foo.wikimedia.cloud', 6000))
defer = mock_connect.call_args.kwargs.get('defer_connect')
self.assertTrue(defer)
conn.connect.assert_called_once_with(sock=socket)

@patch('wp1.db.pymysql.connect')
@patch('wp1.db.socks.socksocket')
@patch('wp1.db.ENV', Environment.DEVELOPMENT)
def test_socks_proxy_not_used(self, mock_socket, mock_connect):
from wp1.db import connect
connect('WP10DB')
mock_socket.assert_not_called()
mock_connect.assert_called_once()
4 changes: 2 additions & 2 deletions wp1/wiki_db.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from functools import partial

from wp1.db import connect
from wp1.db import connect as base_connect

connect = partial(connect, 'WIKIDB')
connect = partial(base_connect, 'WIKIDB')
10 changes: 10 additions & 0 deletions wp1/wikilang_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from functools import partial

from wp1.db import connect as db_connect


def connect(lang):
wiki = f'{lang}wiki'
db = f'{wiki}_p'
host = f'{wiki}.analytics.db.svc.eqiad.wmflabs'
return db_connect('WIKIDB', host=host, db=db)
14 changes: 14 additions & 0 deletions wp1/wikilang_db_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import unittest
from unittest.mock import patch

import wp1.wikilang_db


class WikiLangDbTest(unittest.TestCase):

@patch('wp1.wikilang_db.db_connect')
def test_connect(self, mock_connect):
wp1.wikilang_db.connect('fr')

mock_connect.assert_called_once_with(
'WIKIDB', host='frwiki.analytics.db.svc.eqiad.wmflabs', db='frwiki_p')