-
Notifications
You must be signed in to change notification settings - Fork 12
/
plugin.py
218 lines (183 loc) · 8.08 KB
/
plugin.py
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
84
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
"""Distributed tests planner plugin for pytest testing framework.
Provides an easy way of running tests amoung several test nodes (slaves).
"""
from __future__ import division
import os.path
import itertools
import math
import execnet
import six
class SplinterXdistPlugin(object):
"""Plugin class to defer pytest-xdist hook handler."""
def pytest_configure_node(self, node):
"""Configure node information before it gets instantiated.
Acivate the virtual env, so the node is able to import dependencies.
"""
virtualenv_path = node.config.option.cloud_virtualenv_path
node.gateway.remote_exec(activate_env, virtualenv_path=virtualenv_path).waitclose()
def pytest_configure(config):
"""Register pytest-cloud's deferred plugin."""
if (
getattr(config, 'slaveinput', {}).get('slaveid', 'local') == 'local'
and config.option.cloud_nodes
and config.pluginmanager.getplugin('xdist')):
config.pluginmanager.register(SplinterXdistPlugin())
def pytest_addoption(parser):
"""Pytest hook to add custom command line option(s)."""
group = parser.getgroup("cloud", "distributed tests scheduler")
group._addoption(
'--cloud-chdir',
action="store", dest="cloud_chdir",
default=os.path.join(
'pytest',
os.environ['USER'],
os.path.basename(os.environ['PWD'])
).replace(os.path.sep, '_'),
help="relative path on remote node to run tests in. Default is pytest_<username>_<current_folder_name>")
group.addoption(
"--cloud-node",
help="test node to use for distributed testing", type='string', action="append",
dest='cloud_nodes', metavar="USER@HOST", default=[])
group.addoption(
"--cloud-virtualenv-path",
help="relative path to the virtualenv to be used on the remote test nodes.", type='string', action="store",
dest='cloud_virtualenv_path', metavar="PATH", default=None)
group.addoption(
"--cloud-mem-per-process",
help="amount of memory roughly needed for test process, in megabytes", type='int', action="store",
dest='cloud_mem_per_process', metavar="NUMBER", default=None)
group.addoption(
"--cloud-max-processes",
help="maximum number of processes per test node", type='int', action="store",
dest='cloud_max_processes', metavar="NUMBER", default=None)
def pytest_cmdline_main(config):
"""Custom cmd line manipulation for pytest-cloud."""
check_options(config)
def activate_env(channel, virtualenv_path):
"""Activate virtual environment.
Executed on the remote side.
:param channel: execnet channel for communication with master node
:type channel: execnet.gateway_base.Channel
:param virtualenv_path: relative path to the virtualenv to activate on the remote test node
:type virtualenv_path: str
"""
import os.path
import six
if virtualenv_path:
activate_script = os.path.abspath(os.path.normpath(os.path.join(virtualenv_path, 'bin', 'activate_this.py')))
if six.PY3:
exec(compile(open(activate_script).read()))
else:
execfile(activate_script, {'__file__': activate_script}) # NOQA
def get_node_capabilities(channel):
"""Get test node capabilities.
Executed on the remote side.
:param channel: execnet channel for communication with master node
:type channel: execnet.gateway_base.Channel
:return: `dict` in form {'cpu_count': 1, 'virtual_memory': {'free': 100, 'total': 200}}
:rtype: dict
"""
import psutil
memory = psutil.virtual_memory()
caps = dict(cpu_count=psutil.cpu_count(), virtual_memory=dict(free=memory.free, total=memory.total))
channel.send(caps)
def get_node_specs(node, host, caps, chdir=None, mem_per_process=None, max_processes=None):
"""Get single node specs.
Executed on the master node side.
:param node: node name in form <username>@<hostname>
:type node: str
:param host: hostname of the node
:type host: str
:param chdir: relative path where to run (and sync) tests on the remote side
:type chdir: str
:param mem_per_process: optional amount of memory per process needed, in megabytest
:type mem_per_process: int
:param max_processes: optional maximum number of processes per test node
:type max_processes: int
:return: `list` of test gateway specs for single test node in form ['1*ssh=<node>//id=<hostname>:<index>', ...]
:rtype: list
"""
count = min(max_processes or six.MAXSIZE, caps['cpu_count'])
if mem_per_process:
count = min(int(math.floor(caps['virtual_memory']['free'] / mem_per_process)), count)
return (
'1*ssh={node}//id={host}:{index}//chdir={chdir}'.format(
count=count,
node=node,
host=host,
index=index,
chdir=chdir)
for index in range(count))
def get_nodes_specs(nodes, chdir=None, virtualenv_path=None, mem_per_process=None, max_processes=None):
"""Get nodes specs.
Get list of node names, connect to each of them, get the system information, produce the list of node specs out of
that information filtering non-connectable nodes and nodes which don't comply the requirements.
Executed on the master node side.
:param nodes: `list` of node names in form [[<username>@]<hostname>, ...]
:type nodes: list
:param chdir: relative path where to run (and sync) tests on the remote side
:type chdir: str
:param virtualenv_path: relative path to the virtualenv to activate on the remote test node
:type virtualenv_path: str
:param mem_per_process: optional amount of memory per process needed, in megabytest
:type mem_per_process: int
:param max_processes: optional maximum number of processes per test node
:type max_processes: int
:return: `list` of test gateway specs for all test nodes which confirm given requirements
in form ['1*ssh=<node>//id=<hostname>:<index>', ...]
:rtype: list
"""
group = execnet.Group()
if virtualenv_path:
rsync = execnet.RSync(virtualenv_path)
node_specs = []
node_caps = {}
for node in nodes:
host = node.split('@')[1] if '@' in node else node
spec = 'ssh={node}//id={host}//chdir={chdir}'.format(
node=node,
host=host,
chdir=chdir)
try:
gw = group.makegateway(spec)
except Exception:
continue
if virtualenv_path:
rsync.add_target(gw, virtualenv_path)
node_specs.append((node, host))
if virtualenv_path:
rsync.send()
try:
group.remote_exec(activate_env, virtualenv_path=virtualenv_path).waitclose()
multi_channel = group.remote_exec(get_node_capabilities)
try:
caps = multi_channel.receive_each(True)
for ch, cap in caps:
node_caps[ch.gateway.id] = cap
finally:
multi_channel.waitclose()
return list(itertools.chain.from_iterable(
get_node_specs(
node, hst, node_caps[hst], chdir=chdir, mem_per_process=mem_per_process, max_processes=max_processes)
for node, hst in node_specs)
)
finally:
group.terminate()
def check_options(config):
"""Process options to manipulate (produce other options) important for pytest-cloud."""
if getattr(config, 'slaveinput', {}).get('slaveid', 'local') == 'local' and config.option.cloud_nodes:
mem_per_process = config.option.cloud_mem_per_process
if mem_per_process:
mem_per_process = mem_per_process * 1024 * 1024
virtualenv_path = config.option.cloud_virtualenv_path
chdir = config.option.cloud_chdir
node_specs = get_nodes_specs(
config.option.cloud_nodes,
chdir=chdir,
virtualenv_path=virtualenv_path,
max_processes=config.option.cloud_max_processes,
mem_per_process=mem_per_process)
if virtualenv_path:
config.option.rsyncdir += [virtualenv_path]
config.option.tx += node_specs
config.option.dist = 'load'