python: futurize -f libfuturize.fixes.fix_print_with_import
[qemu/ar7.git] / tests / qemu-iotests / nbd-fault-injector.py
blobf9193c0faee67f741998caa3d167636ae629eff1
1 #!/usr/bin/env python
2 # NBD server - fault injection utility
4 # Configuration file syntax:
5 # [inject-error "disconnect-neg1"]
6 # event=neg1
7 # io=readwrite
8 # when=before
10 # Note that Python's ConfigParser squashes together all sections with the same
11 # name, so give each [inject-error] a unique name.
13 # inject-error options:
14 # event - name of the trigger event
15 # "neg1" - first part of negotiation struct
16 # "export" - export struct
17 # "neg2" - second part of negotiation struct
18 # "request" - NBD request struct
19 # "reply" - NBD reply struct
20 # "data" - request/reply data
21 # io - I/O direction that triggers this rule:
22 # "read", "write", or "readwrite"
23 # default: readwrite
24 # when - after how many bytes to inject the fault
25 # -1 - inject error after I/O
26 # 0 - inject error before I/O
27 # integer - inject error after integer bytes
28 # "before" - alias for 0
29 # "after" - alias for -1
30 # default: before
32 # Currently the only error injection action is to terminate the server process.
33 # This resets the TCP connection and thus forces the client to handle
34 # unexpected connection termination.
36 # Other error injection actions could be added in the future.
38 # Copyright Red Hat, Inc. 2014
40 # Authors:
41 # Stefan Hajnoczi <stefanha@redhat.com>
43 # This work is licensed under the terms of the GNU GPL, version 2 or later.
44 # See the COPYING file in the top-level directory.
46 from __future__ import print_function
47 import sys
48 import socket
49 import struct
50 import collections
51 import ConfigParser
53 FAKE_DISK_SIZE = 8 * 1024 * 1024 * 1024 # 8 GB
55 # Protocol constants
56 NBD_CMD_READ = 0
57 NBD_CMD_WRITE = 1
58 NBD_CMD_DISC = 2
59 NBD_REQUEST_MAGIC = 0x25609513
60 NBD_SIMPLE_REPLY_MAGIC = 0x67446698
61 NBD_PASSWD = 0x4e42444d41474943
62 NBD_OPTS_MAGIC = 0x49484156454F5054
63 NBD_CLIENT_MAGIC = 0x0000420281861253
64 NBD_OPT_EXPORT_NAME = 1 << 0
66 # Protocol structs
67 neg_classic_struct = struct.Struct('>QQQI124x')
68 neg1_struct = struct.Struct('>QQH')
69 export_tuple = collections.namedtuple('Export', 'reserved magic opt len')
70 export_struct = struct.Struct('>IQII')
71 neg2_struct = struct.Struct('>QH124x')
72 request_tuple = collections.namedtuple('Request', 'magic type handle from_ len')
73 request_struct = struct.Struct('>IIQQI')
74 reply_struct = struct.Struct('>IIQ')
76 def err(msg):
77 sys.stderr.write(msg + '\n')
78 sys.exit(1)
80 def recvall(sock, bufsize):
81 received = 0
82 chunks = []
83 while received < bufsize:
84 chunk = sock.recv(bufsize - received)
85 if len(chunk) == 0:
86 raise Exception('unexpected disconnect')
87 chunks.append(chunk)
88 received += len(chunk)
89 return ''.join(chunks)
91 class Rule(object):
92 def __init__(self, name, event, io, when):
93 self.name = name
94 self.event = event
95 self.io = io
96 self.when = when
98 def match(self, event, io):
99 if event != self.event:
100 return False
101 if io != self.io and self.io != 'readwrite':
102 return False
103 return True
105 class FaultInjectionSocket(object):
106 def __init__(self, sock, rules):
107 self.sock = sock
108 self.rules = rules
110 def check(self, event, io, bufsize=None):
111 for rule in self.rules:
112 if rule.match(event, io):
113 if rule.when == 0 or bufsize is None:
114 print('Closing connection on rule match %s' % rule.name)
115 sys.exit(0)
116 if rule.when != -1:
117 return rule.when
118 return bufsize
120 def send(self, buf, event):
121 bufsize = self.check(event, 'write', bufsize=len(buf))
122 self.sock.sendall(buf[:bufsize])
123 self.check(event, 'write')
125 def recv(self, bufsize, event):
126 bufsize = self.check(event, 'read', bufsize=bufsize)
127 data = recvall(self.sock, bufsize)
128 self.check(event, 'read')
129 return data
131 def close(self):
132 self.sock.close()
134 def negotiate_classic(conn):
135 buf = neg_classic_struct.pack(NBD_PASSWD, NBD_CLIENT_MAGIC,
136 FAKE_DISK_SIZE, 0)
137 conn.send(buf, event='neg-classic')
139 def negotiate_export(conn):
140 # Send negotiation part 1
141 buf = neg1_struct.pack(NBD_PASSWD, NBD_OPTS_MAGIC, 0)
142 conn.send(buf, event='neg1')
144 # Receive export option
145 buf = conn.recv(export_struct.size, event='export')
146 export = export_tuple._make(export_struct.unpack(buf))
147 assert export.magic == NBD_OPTS_MAGIC
148 assert export.opt == NBD_OPT_EXPORT_NAME
149 name = conn.recv(export.len, event='export-name')
151 # Send negotiation part 2
152 buf = neg2_struct.pack(FAKE_DISK_SIZE, 0)
153 conn.send(buf, event='neg2')
155 def negotiate(conn, use_export):
156 '''Negotiate export with client'''
157 if use_export:
158 negotiate_export(conn)
159 else:
160 negotiate_classic(conn)
162 def read_request(conn):
163 '''Parse NBD request from client'''
164 buf = conn.recv(request_struct.size, event='request')
165 req = request_tuple._make(request_struct.unpack(buf))
166 assert req.magic == NBD_REQUEST_MAGIC
167 return req
169 def write_reply(conn, error, handle):
170 buf = reply_struct.pack(NBD_SIMPLE_REPLY_MAGIC, error, handle)
171 conn.send(buf, event='reply')
173 def handle_connection(conn, use_export):
174 negotiate(conn, use_export)
175 while True:
176 req = read_request(conn)
177 if req.type == NBD_CMD_READ:
178 write_reply(conn, 0, req.handle)
179 conn.send('\0' * req.len, event='data')
180 elif req.type == NBD_CMD_WRITE:
181 _ = conn.recv(req.len, event='data')
182 write_reply(conn, 0, req.handle)
183 elif req.type == NBD_CMD_DISC:
184 break
185 else:
186 print('unrecognized command type %#02x' % req.type)
187 break
188 conn.close()
190 def run_server(sock, rules, use_export):
191 while True:
192 conn, _ = sock.accept()
193 handle_connection(FaultInjectionSocket(conn, rules), use_export)
195 def parse_inject_error(name, options):
196 if 'event' not in options:
197 err('missing \"event\" option in %s' % name)
198 event = options['event']
199 if event not in ('neg-classic', 'neg1', 'export', 'neg2', 'request', 'reply', 'data'):
200 err('invalid \"event\" option value \"%s\" in %s' % (event, name))
201 io = options.get('io', 'readwrite')
202 if io not in ('read', 'write', 'readwrite'):
203 err('invalid \"io\" option value \"%s\" in %s' % (io, name))
204 when = options.get('when', 'before')
205 try:
206 when = int(when)
207 except ValueError:
208 if when == 'before':
209 when = 0
210 elif when == 'after':
211 when = -1
212 else:
213 err('invalid \"when\" option value \"%s\" in %s' % (when, name))
214 return Rule(name, event, io, when)
216 def parse_config(config):
217 rules = []
218 for name in config.sections():
219 if name.startswith('inject-error'):
220 options = dict(config.items(name))
221 rules.append(parse_inject_error(name, options))
222 else:
223 err('invalid config section name: %s' % name)
224 return rules
226 def load_rules(filename):
227 config = ConfigParser.RawConfigParser()
228 with open(filename, 'rt') as f:
229 config.readfp(f, filename)
230 return parse_config(config)
232 def open_socket(path):
233 '''Open a TCP or UNIX domain listen socket'''
234 if ':' in path:
235 host, port = path.split(':', 1)
236 sock = socket.socket()
237 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
238 sock.bind((host, int(port)))
240 # If given port was 0 the final port number is now available
241 path = '%s:%d' % sock.getsockname()
242 else:
243 sock = socket.socket(socket.AF_UNIX)
244 sock.bind(path)
245 sock.listen(0)
246 print('Listening on %s' % path)
247 sys.stdout.flush() # another process may be waiting, show message now
248 return sock
250 def usage(args):
251 sys.stderr.write('usage: %s [--classic-negotiation] <tcp-port>|<unix-path> <config-file>\n' % args[0])
252 sys.stderr.write('Run an fault injector NBD server with rules defined in a config file.\n')
253 sys.exit(1)
255 def main(args):
256 if len(args) != 3 and len(args) != 4:
257 usage(args)
258 use_export = True
259 if args[1] == '--classic-negotiation':
260 use_export = False
261 elif len(args) == 4:
262 usage(args)
263 sock = open_socket(args[1 if use_export else 2])
264 rules = load_rules(args[2 if use_export else 3])
265 run_server(sock, rules, use_export)
266 return 0
268 if __name__ == '__main__':
269 sys.exit(main(sys.argv))