2020-09-16 04:26:10 +00:00
|
|
|
import os
|
2017-05-19 18:54:05 +00:00
|
|
|
import subprocess
|
|
|
|
import time
|
|
|
|
|
|
|
|
import docker
|
|
|
|
|
|
|
|
|
|
|
|
class PartitionManager:
|
|
|
|
"""Allows introducing failures in the network between docker containers.
|
|
|
|
|
|
|
|
Can act as a context manager:
|
|
|
|
|
2020-05-14 20:08:15 +00:00
|
|
|
with PartitionManager() as pm:
|
2017-05-19 18:54:05 +00:00
|
|
|
pm.partition_instances(instance1, instance2)
|
|
|
|
...
|
|
|
|
# At exit all partitions are removed automatically.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self._iptables_rules = []
|
2020-10-27 12:24:10 +00:00
|
|
|
self._netem_delayed_instances = []
|
2020-10-08 13:35:44 +00:00
|
|
|
_NetworkManager.get()
|
2017-05-19 18:54:05 +00:00
|
|
|
|
2017-05-30 11:49:17 +00:00
|
|
|
def drop_instance_zk_connections(self, instance, action='DROP'):
|
2017-05-19 18:54:05 +00:00
|
|
|
self._check_instance(instance)
|
|
|
|
|
|
|
|
self._add_rule({'source': instance.ip_address, 'destination_port': 2181, 'action': action})
|
|
|
|
self._add_rule({'destination': instance.ip_address, 'source_port': 2181, 'action': action})
|
|
|
|
|
2017-05-30 11:49:17 +00:00
|
|
|
def restore_instance_zk_connections(self, instance, action='DROP'):
|
|
|
|
self._check_instance(instance)
|
|
|
|
|
|
|
|
self._delete_rule({'source': instance.ip_address, 'destination_port': 2181, 'action': action})
|
|
|
|
self._delete_rule({'destination': instance.ip_address, 'source_port': 2181, 'action': action})
|
|
|
|
|
2017-08-01 17:36:00 +00:00
|
|
|
def partition_instances(self, left, right, port=None, action='DROP'):
|
2017-05-19 18:54:05 +00:00
|
|
|
self._check_instance(left)
|
|
|
|
self._check_instance(right)
|
|
|
|
|
2017-08-01 17:36:00 +00:00
|
|
|
def create_rule(src, dst):
|
|
|
|
rule = {'source': src.ip_address, 'destination': dst.ip_address, 'action': action}
|
|
|
|
if port is not None:
|
|
|
|
rule['destination_port'] = port
|
|
|
|
return rule
|
|
|
|
|
|
|
|
self._add_rule(create_rule(left, right))
|
|
|
|
self._add_rule(create_rule(right, left))
|
2017-05-19 18:54:05 +00:00
|
|
|
|
2020-10-27 12:24:10 +00:00
|
|
|
def add_network_delay(self, instance, delay_ms):
|
|
|
|
self._add_tc_netem_delay(instance, delay_ms)
|
|
|
|
|
2017-05-19 18:54:05 +00:00
|
|
|
def heal_all(self):
|
|
|
|
while self._iptables_rules:
|
|
|
|
rule = self._iptables_rules.pop()
|
|
|
|
_NetworkManager.get().delete_iptables_rule(**rule)
|
|
|
|
|
2020-10-27 12:24:10 +00:00
|
|
|
while self._netem_delayed_instances:
|
|
|
|
instance = self._netem_delayed_instances.pop()
|
|
|
|
instance.exec_in_container(["bash", "-c", "tc qdisc del dev eth0 root netem"], user="root")
|
|
|
|
|
2017-08-02 14:42:35 +00:00
|
|
|
def pop_rules(self):
|
|
|
|
res = self._iptables_rules[:]
|
|
|
|
self.heal_all()
|
|
|
|
return res
|
|
|
|
|
|
|
|
def push_rules(self, rules):
|
|
|
|
for rule in rules:
|
|
|
|
self._add_rule(rule)
|
|
|
|
|
2017-05-19 18:54:05 +00:00
|
|
|
@staticmethod
|
|
|
|
def _check_instance(instance):
|
|
|
|
if instance.ip_address is None:
|
|
|
|
raise Exception('Instance + ' + instance.name + ' is not launched!')
|
|
|
|
|
|
|
|
def _add_rule(self, rule):
|
|
|
|
_NetworkManager.get().add_iptables_rule(**rule)
|
|
|
|
self._iptables_rules.append(rule)
|
|
|
|
|
2017-05-30 11:49:17 +00:00
|
|
|
def _delete_rule(self, rule):
|
|
|
|
_NetworkManager.get().delete_iptables_rule(**rule)
|
|
|
|
self._iptables_rules.remove(rule)
|
|
|
|
|
2020-10-27 12:24:10 +00:00
|
|
|
def _add_tc_netem_delay(self, instance, delay_ms):
|
|
|
|
instance.exec_in_container(["bash", "-c", "tc qdisc add dev eth0 root netem delay {}ms".format(delay_ms)], user="root")
|
|
|
|
self._netem_delayed_instances.append(instance)
|
|
|
|
|
2017-05-19 18:54:05 +00:00
|
|
|
def __enter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
self.heal_all()
|
|
|
|
|
2017-11-20 20:07:29 +00:00
|
|
|
def __del__(self):
|
|
|
|
self.heal_all()
|
|
|
|
|
2017-05-19 18:54:05 +00:00
|
|
|
|
2020-02-06 12:18:19 +00:00
|
|
|
class PartitionManagerDisabler:
|
2017-08-02 14:42:35 +00:00
|
|
|
def __init__(self, manager):
|
|
|
|
self.manager = manager
|
|
|
|
self.rules = self.manager.pop_rules()
|
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
|
|
self.manager.push_rules(self.rules)
|
|
|
|
|
|
|
|
|
2017-05-19 18:54:05 +00:00
|
|
|
class _NetworkManager:
|
|
|
|
"""Execute commands inside a container with access to network settings.
|
|
|
|
|
|
|
|
We need to call iptables to create partitions, but we want to avoid sudo.
|
|
|
|
The way to circumvent this restriction is to run iptables in a container with network=host.
|
|
|
|
The container is long-running and periodically renewed - this is an optimization to avoid the overhead
|
|
|
|
of container creation on each call.
|
|
|
|
Source of the idea: https://github.com/worstcase/blockade/blob/master/blockade/host.py
|
|
|
|
"""
|
|
|
|
|
|
|
|
# Singleton instance.
|
|
|
|
_instance = None
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def get(cls, **kwargs):
|
|
|
|
if cls._instance is None:
|
|
|
|
cls._instance = cls(**kwargs)
|
|
|
|
return cls._instance
|
|
|
|
|
|
|
|
def add_iptables_rule(self, **kwargs):
|
2017-07-10 20:34:19 +00:00
|
|
|
cmd = ['iptables', '-I', 'DOCKER-USER', '1']
|
2017-05-19 18:54:05 +00:00
|
|
|
cmd.extend(self._iptables_cmd_suffix(**kwargs))
|
|
|
|
self._exec_run(cmd, privileged=True)
|
|
|
|
|
|
|
|
def delete_iptables_rule(self, **kwargs):
|
2017-07-10 20:34:19 +00:00
|
|
|
cmd = ['iptables', '-D', 'DOCKER-USER']
|
2017-05-19 18:54:05 +00:00
|
|
|
cmd.extend(self._iptables_cmd_suffix(**kwargs))
|
|
|
|
self._exec_run(cmd, privileged=True)
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _iptables_cmd_suffix(
|
|
|
|
source=None, destination=None,
|
|
|
|
source_port=None, destination_port=None,
|
2017-07-31 18:57:13 +00:00
|
|
|
action=None, probability=None):
|
|
|
|
ret = []
|
|
|
|
if probability is not None:
|
|
|
|
ret.extend(['-m', 'statistic', '--mode', 'random', '--probability', str(probability)])
|
|
|
|
ret.extend(['-p', 'tcp'])
|
2017-05-19 18:54:05 +00:00
|
|
|
if source is not None:
|
|
|
|
ret.extend(['-s', source])
|
|
|
|
if destination is not None:
|
|
|
|
ret.extend(['-d', destination])
|
|
|
|
if source_port is not None:
|
2017-06-14 14:38:08 +00:00
|
|
|
ret.extend(['--sport', str(source_port)])
|
2017-05-19 18:54:05 +00:00
|
|
|
if destination_port is not None:
|
2017-06-14 14:38:08 +00:00
|
|
|
ret.extend(['--dport', str(destination_port)])
|
2017-05-19 18:54:05 +00:00
|
|
|
if action is not None:
|
2017-06-14 14:38:08 +00:00
|
|
|
ret.extend(['-j'] + action.split())
|
2017-05-19 18:54:05 +00:00
|
|
|
return ret
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
container_expire_timeout=50, container_exit_timeout=60):
|
|
|
|
|
|
|
|
self.container_expire_timeout = container_expire_timeout
|
|
|
|
self.container_exit_timeout = container_exit_timeout
|
|
|
|
|
2018-08-24 11:19:06 +00:00
|
|
|
self._docker_client = docker.from_env(version=os.environ.get("DOCKER_API_VERSION"))
|
2017-05-19 18:54:05 +00:00
|
|
|
|
|
|
|
self._container = None
|
|
|
|
|
|
|
|
self._ensure_container()
|
|
|
|
|
|
|
|
def _ensure_container(self):
|
|
|
|
if self._container is None or self._container_expire_time <= time.time():
|
|
|
|
|
2020-12-07 09:25:27 +00:00
|
|
|
for i in range(5):
|
|
|
|
if self._container is not None:
|
|
|
|
try:
|
|
|
|
self._container.remove(force=True)
|
|
|
|
break
|
|
|
|
except docker.errors.NotFound:
|
|
|
|
break
|
|
|
|
except Exception as ex:
|
|
|
|
print("Error removing network blocade container, will try again", str(ex))
|
|
|
|
time.sleep(i)
|
2017-05-19 18:54:05 +00:00
|
|
|
|
2020-11-27 11:38:04 +00:00
|
|
|
image = subprocess.check_output("docker images -q yandex/clickhouse-integration-helper 2>/dev/null", shell=True)
|
|
|
|
if not image.strip():
|
|
|
|
print("No network image helper, will try download")
|
|
|
|
# for some reason docker api may hang if image doesn't exist, so we download it
|
|
|
|
# before running
|
|
|
|
for i in range(5):
|
|
|
|
try:
|
2021-01-22 14:27:23 +00:00
|
|
|
subprocess.check_call("docker pull yandex/clickhouse-integration-helper", shell=True) # STYLE_CHECK_ALLOW_SUBPROCESS_CHECK_CALL
|
2020-11-27 11:38:04 +00:00
|
|
|
break
|
|
|
|
except:
|
|
|
|
time.sleep(i)
|
|
|
|
else:
|
|
|
|
raise Exception("Cannot pull yandex/clickhouse-integration-helper image")
|
2020-10-09 14:38:31 +00:00
|
|
|
|
2020-09-16 04:26:10 +00:00
|
|
|
self._container = self._docker_client.containers.run('yandex/clickhouse-integration-helper',
|
|
|
|
auto_remove=True,
|
2020-07-27 17:00:14 +00:00
|
|
|
command=('sleep %s' % self.container_exit_timeout),
|
|
|
|
detach=True, network_mode='host')
|
|
|
|
container_id = self._container.id
|
2017-05-19 18:54:05 +00:00
|
|
|
self._container_expire_time = time.time() + self.container_expire_timeout
|
|
|
|
|
|
|
|
return self._container
|
|
|
|
|
|
|
|
def _exec_run(self, cmd, **kwargs):
|
|
|
|
container = self._ensure_container()
|
|
|
|
|
|
|
|
handle = self._docker_client.api.exec_create(container.id, cmd, **kwargs)
|
|
|
|
output = self._docker_client.api.exec_start(handle).decode('utf8')
|
|
|
|
exit_code = self._docker_client.api.exec_inspect(handle)['ExitCode']
|
|
|
|
|
|
|
|
if exit_code != 0:
|
2020-10-02 16:54:07 +00:00
|
|
|
print(output)
|
2017-05-19 18:54:05 +00:00
|
|
|
raise subprocess.CalledProcessError(exit_code, cmd)
|
|
|
|
|
|
|
|
return output
|