2 # NBD server - fault injection utility
4 # Configuration file syntax:
5 # [inject-error "disconnect-neg1"]
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"
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
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
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.
52 FAKE_DISK_SIZE
= 8 * 1024 * 1024 * 1024 # 8 GB
58 NBD_REQUEST_MAGIC
= 0x25609513
59 NBD_SIMPLE_REPLY_MAGIC
= 0x67446698
60 NBD_PASSWD
= 0x4e42444d41474943
61 NBD_OPTS_MAGIC
= 0x49484156454F5054
62 NBD_CLIENT_MAGIC
= 0x0000420281861253
63 NBD_OPT_EXPORT_NAME
= 1 << 0
66 neg_classic_struct
= struct
.Struct('>QQQI124x')
67 neg1_struct
= struct
.Struct('>QQH')
68 export_tuple
= collections
.namedtuple('Export', 'reserved magic opt len')
69 export_struct
= struct
.Struct('>IQII')
70 neg2_struct
= struct
.Struct('>QH124x')
71 request_tuple
= collections
.namedtuple('Request', 'magic type handle from_ len')
72 request_struct
= struct
.Struct('>IIQQI')
73 reply_struct
= struct
.Struct('>IIQ')
76 sys
.stderr
.write(msg
+ '\n')
79 def recvall(sock
, bufsize
):
82 while received
< bufsize
:
83 chunk
= sock
.recv(bufsize
- received
)
85 raise Exception('unexpected disconnect')
87 received
+= len(chunk
)
88 return ''.join(chunks
)
91 def __init__(self
, name
, event
, io
, when
):
97 def match(self
, event
, io
):
98 if event
!= self
.event
:
100 if io
!= self
.io
and self
.io
!= 'readwrite':
104 class FaultInjectionSocket(object):
105 def __init__(self
, sock
, rules
):
109 def check(self
, event
, io
, bufsize
=None):
110 for rule
in self
.rules
:
111 if rule
.match(event
, io
):
112 if rule
.when
== 0 or bufsize
is None:
113 print 'Closing connection on rule match %s' % rule
.name
119 def send(self
, buf
, event
):
120 bufsize
= self
.check(event
, 'write', bufsize
=len(buf
))
121 self
.sock
.sendall(buf
[:bufsize
])
122 self
.check(event
, 'write')
124 def recv(self
, bufsize
, event
):
125 bufsize
= self
.check(event
, 'read', bufsize
=bufsize
)
126 data
= recvall(self
.sock
, bufsize
)
127 self
.check(event
, 'read')
133 def negotiate_classic(conn
):
134 buf
= neg_classic_struct
.pack(NBD_PASSWD
, NBD_CLIENT_MAGIC
,
136 conn
.send(buf
, event
='neg-classic')
138 def negotiate_export(conn
):
139 # Send negotiation part 1
140 buf
= neg1_struct
.pack(NBD_PASSWD
, NBD_OPTS_MAGIC
, 0)
141 conn
.send(buf
, event
='neg1')
143 # Receive export option
144 buf
= conn
.recv(export_struct
.size
, event
='export')
145 export
= export_tuple
._make
(export_struct
.unpack(buf
))
146 assert export
.magic
== NBD_OPTS_MAGIC
147 assert export
.opt
== NBD_OPT_EXPORT_NAME
148 name
= conn
.recv(export
.len, event
='export-name')
150 # Send negotiation part 2
151 buf
= neg2_struct
.pack(FAKE_DISK_SIZE
, 0)
152 conn
.send(buf
, event
='neg2')
154 def negotiate(conn
, use_export
):
155 '''Negotiate export with client'''
157 negotiate_export(conn
)
159 negotiate_classic(conn
)
161 def read_request(conn
):
162 '''Parse NBD request from client'''
163 buf
= conn
.recv(request_struct
.size
, event
='request')
164 req
= request_tuple
._make
(request_struct
.unpack(buf
))
165 assert req
.magic
== NBD_REQUEST_MAGIC
168 def write_reply(conn
, error
, handle
):
169 buf
= reply_struct
.pack(NBD_SIMPLE_REPLY_MAGIC
, error
, handle
)
170 conn
.send(buf
, event
='reply')
172 def handle_connection(conn
, use_export
):
173 negotiate(conn
, use_export
)
175 req
= read_request(conn
)
176 if req
.type == NBD_CMD_READ
:
177 write_reply(conn
, 0, req
.handle
)
178 conn
.send('\0' * req
.len, event
='data')
179 elif req
.type == NBD_CMD_WRITE
:
180 _
= conn
.recv(req
.len, event
='data')
181 write_reply(conn
, 0, req
.handle
)
182 elif req
.type == NBD_CMD_DISC
:
185 print 'unrecognized command type %#02x' % req
.type
189 def run_server(sock
, rules
, use_export
):
191 conn
, _
= sock
.accept()
192 handle_connection(FaultInjectionSocket(conn
, rules
), use_export
)
194 def parse_inject_error(name
, options
):
195 if 'event' not in options
:
196 err('missing \"event\" option in %s' % name
)
197 event
= options
['event']
198 if event
not in ('neg-classic', 'neg1', 'export', 'neg2', 'request', 'reply', 'data'):
199 err('invalid \"event\" option value \"%s\" in %s' % (event
, name
))
200 io
= options
.get('io', 'readwrite')
201 if io
not in ('read', 'write', 'readwrite'):
202 err('invalid \"io\" option value \"%s\" in %s' % (io
, name
))
203 when
= options
.get('when', 'before')
209 elif when
== 'after':
212 err('invalid \"when\" option value \"%s\" in %s' % (when
, name
))
213 return Rule(name
, event
, io
, when
)
215 def parse_config(config
):
217 for name
in config
.sections():
218 if name
.startswith('inject-error'):
219 options
= dict(config
.items(name
))
220 rules
.append(parse_inject_error(name
, options
))
222 err('invalid config section name: %s' % name
)
225 def load_rules(filename
):
226 config
= ConfigParser
.RawConfigParser()
227 with
open(filename
, 'rt') as f
:
228 config
.readfp(f
, filename
)
229 return parse_config(config
)
231 def open_socket(path
):
232 '''Open a TCP or UNIX domain listen socket'''
234 host
, port
= path
.split(':', 1)
235 sock
= socket
.socket()
236 sock
.setsockopt(socket
.SOL_SOCKET
, socket
.SO_REUSEADDR
, 1)
237 sock
.bind((host
, int(port
)))
239 # If given port was 0 the final port number is now available
240 path
= '%s:%d' % sock
.getsockname()
242 sock
= socket
.socket(socket
.AF_UNIX
)
245 print 'Listening on %s' % path
246 sys
.stdout
.flush() # another process may be waiting, show message now
250 sys
.stderr
.write('usage: %s [--classic-negotiation] <tcp-port>|<unix-path> <config-file>\n' % args
[0])
251 sys
.stderr
.write('Run an fault injector NBD server with rules defined in a config file.\n')
255 if len(args
) != 3 and len(args
) != 4:
258 if args
[1] == '--classic-negotiation':
262 sock
= open_socket(args
[1 if use_export
else 2])
263 rules
= load_rules(args
[2 if use_export
else 3])
264 run_server(sock
, rules
, use_export
)
267 if __name__
== '__main__':
268 sys
.exit(main(sys
.argv
))