-
Notifications
You must be signed in to change notification settings - Fork 202
/
nbd.py
542 lines (436 loc) · 14.8 KB
/
nbd.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
# SPDX-FileCopyrightText: Red Hat, Inc.
# SPDX-License-Identifier: GPL-2.0-or-later
"""
NBD - manage network block devices
"""
from __future__ import absolute_import
from __future__ import division
import collections
import errno
import json
import logging
import os
import time
from vdsm.common import cmdutils
from vdsm.common import constants
from vdsm.common import properties
from vdsm.common import supervdsm
from vdsm.common import systemctl
from vdsm.common import systemd
from vdsm.common import nbdutils
from vdsm.common.time import monotonic_time
from . import constants as sc
from . import exception as se
from . import fileUtils
from . import qemuimg
from . import transientdisk
from . sdc import sdCache
DEFAULT_SOCKET_MODE = 0o660
RUN_DIR = os.path.join(constants.P_VDSM_RUN, "nbd")
OVERLAY = "overlay"
QEMU_NBD = cmdutils.CommandPath(
"qemu-nbd", "/usr/local/bin/qemu-nbd", "/usr/bin/qemu-nbd")
log = logging.getLogger("storage.nbd")
class Error(Exception):
""" Base class for nbd errors """
class Timeout(Error):
""" Timeout starting nbd server """
class InvalidPath(Error):
""" Path is not a valid volume path """
class ServerConfig(properties.Owner):
sd_id = properties.UUID(required=True)
img_id = properties.UUID(required=True)
vol_id = properties.UUID(required=True)
readonly = properties.Boolean(default=False)
discard = properties.Boolean(default=False)
detect_zeroes = properties.Boolean(default=False)
backing_chain = properties.Boolean(default=True)
bitmap = properties.UUID()
def __init__(self, config):
self.sd_id = config.get("sd_id")
self.img_id = config.get("img_id")
self.vol_id = config.get("vol_id")
self.readonly = config.get("readonly")
self.discard = config.get("discard")
self.detect_zeroes = config.get("detect_zeroes")
# Setting to None overrides the default value.
# See https://bugzilla.redhat.com/1892403
self.backing_chain = config.get("backing_chain", True)
self.bitmap = config.get("bitmap")
if not self.backing_chain and self.bitmap:
# When exporting a bitmap we always export the entire chain.
raise se.UnsupportedOperation(
"Cannot export bitmap with backing_chain=False")
if self.bitmap and not self.readonly:
# Exporting bitmaps makes sense only for incremental backup.
raise se.UnsupportedOperation(
"Cannot export bitmap for writing")
QemuNBDConfig = collections.namedtuple(
"QemuNBDConfig",
"format,readonly,discard,detect_zeroes,path,backing_chain,is_block,bitmap")
def start_server(server_id, config):
cfg = ServerConfig(config)
dom = sdCache.produce_manifest(cfg.sd_id)
vol = dom.produceVolume(cfg.img_id, cfg.vol_id)
if vol.isShared() and not cfg.readonly:
raise se.SharedVolumeNonWritable(vol)
if cfg.bitmap:
if vol.getFormat() != sc.COW_FORMAT:
raise se.UnsupportedOperation(
"Cannot export bitmap from RAW volume")
# The bitmap must exist in the volume, and may exist in the
# backing chain.
bitmap_chain = _find_bitmap(vol.volumePath, cfg.bitmap)
if not bitmap_chain:
raise se.BitmapDoesNotExist(
reason=f"Bitmap does not exist in {vol.volumePath}",
bitmap=cfg.bitmap)
_create_rundir()
# If the bitmap exists in the volume backing chain, we need to
# create an overlay exporting the bitmap from the entire chain.
using_overlay = cfg.bitmap and len(bitmap_chain) > 1
if using_overlay:
path = _create_overlay(
server_id, vol.volumePath, cfg.bitmap, bitmap_chain)
format = "qcow2"
is_block = False
else:
path = vol.volumePath
format = sc.fmt2str(vol.getFormat())
is_block = vol.is_block()
try:
sock = _socket_path(server_id)
log.info(
"Starting transient service %s, serving %s via unix socket %s",
_service_name(server_id), path, sock)
qemu_nbd_config = QemuNBDConfig(
format=format,
readonly=cfg.readonly,
discard=cfg.discard,
detect_zeroes=cfg.detect_zeroes,
path=path,
backing_chain=cfg.backing_chain,
is_block=is_block,
bitmap=cfg.bitmap)
start_transient_service(server_id, qemu_nbd_config)
if not _wait_for_socket(sock, 10.0):
raise Timeout("Timeout starting NBD server {}: {}"
.format(server_id, config))
finally:
if using_overlay:
# When qemu-nbd is ready it has an open file descriptor, and it
# does not need the overlay. Removing the overlay now simplifies
# cleanup when stopping the service.
_remove_overlay(server_id)
os.chmod(sock, DEFAULT_SOCKET_MODE)
unix_address = nbdutils.UnixAddress(sock)
return unix_address.url()
def stop_server(server_id):
service = _service_name(server_id)
# systemctl.stop() does not have a way to detect that a server was not
# running, so we need to check the service state before we stop it. This
# is racy, but should be fine since service names are random and we start
# them only once.
info = systemctl.show(service, properties=("LoadState",))
if info and info[0]["LoadState"] == "not-found":
log.info("Transient service %s is not running", service)
return
log.info("Stopping transient service %s", service)
systemctl.stop(service)
def _create_overlay(server_id, backing, bitmap, bitmap_chain):
"""
To export bitmaps from entire chain, we need to create an overlay, and
merge all bitmaps from the chain into the overlay.
"""
overlay = transientdisk.create_disk(
server_id,
OVERLAY,
backing=backing,
backing_format="qcow2")["path"]
try:
# Merge bitmap from filenames into overlay.
qemuimg.bitmap_add(overlay, bitmap).run()
for src_img in bitmap_chain:
qemuimg.bitmap_merge(
src_img, bitmap, "qcow2", overlay, bitmap).run()
except:
try:
transientdisk.remove_disk(server_id, OVERLAY)
except Exception:
log.exception("Error removing overlay: %s", overlay)
raise
return overlay
def _remove_overlay(server_id):
"""
Remove the overlay created by _create_overlay().
"""
transientdisk.remove_disk(server_id, OVERLAY)
def _find_bitmap(path, bitmap):
"""
Return filenames in backing chain containing bitmap.
An example of normal case. "bitmap1" was create after we took a snapshot
and added "/file2". Then we took another snapshot and added /file3".
[
{
"filename": "/file3"
"bitmaps":
[
{
"name": "bitmap1",
"flags": ["auto"]
}
]
},
{
"filename": "/file2"
"bitmaps":
[
{
"name": "bitmap1",
"flags": ["auto"]
}
]
},
{
"filename": "/file1"
}
]
In this case we return the filenames:
["/file3", "/file2"]
The caller can merge the contents of "bitmap1" from these files to create a
new bitmap referencing all the data written to the disk since "bitmap1" was
created.
We have several cases when the bitmap chain is invalid, and cannot be used
to create incremental backup.
Case 1: The bitmap is inconsistent ("in-use" flag) in one of the nodes.
We cannot trust the data in this bitmap.
[
{
"filename": "/file2"
"bitmaps":
[
{
"name": "bitmap1",
"flags": ["in-use", "auto"]
}
]
},
{
"filename": "/file1"
"bitmaps":
[
{
"name": "bitmap1",
"flags": ["auto"]
}
]
}
]
Case 2: The bitmap is disabled (no "auto" flag) on one of the nodes. This
bitmap may be missing data added while the bitmap was disabled.
[
{
"filename": "/file2"
"bitmaps":
[
{
"name": "bitmap1",
"flags": ["auto"]
}
]
},
{
"filename": "/file1"
"bitmaps":
[
{
"name": "bitmap1",
"flags": []
}
]
}
]
Case 3: The bitmap is missing in in one node, but exists on the next node.
Data from the node may be missing from the backup.
Here the bitmap is missing in the top node:
[
{
"filename": "/file2"
},
{
"filename": "/file1"
"bitmaps":
[
{
"name": "bitmap1",
"flags": ["auto"]
}
]
}
]
Here the bitmap is missing in the middle node:
[
{
"filename": "/file3"
"bitmaps":
[
{
"name": "bitmap1",
"flags": ["auto"]
}
]
},
{
"filename": "/file2"
},
{
"filename": "/file1"
"bitmaps":
[
{
"name": "bitmap1",
"flags": ["auto"]
}
]
}
]
Case 4: Bitmap does not exist on any node. This is a caller error, or maybe
someone deleted the bitmaps manually from the chain.
[
{
"filename": "/file2"
},
{
"filename": "/file1"
}
]
Raises se.InvalidBitmapChain if bitmap is invalid or missing in one of the
backing chain nodes.
"""
filenames = []
missing = []
for node in qemuimg.info(path, format="qcow2", backing_chain=True):
if node["format"] != "qcow2":
break
node_bitmaps = node["format-specific"]["data"].get("bitmaps", [])
for bitmap_info in node_bitmaps:
if bitmap_info["name"] != bitmap:
continue
if "in-use" in bitmap_info["flags"]:
raise se.InvalidBitmapChain(
reason="Bitmap in use",
bitmap=bitmap_info,
filename=node["filename"])
if "auto" not in bitmap_info["flags"]:
raise se.InvalidBitmapChain(
reason="Bitmap is disabled",
bitmap=bitmap_info,
filename=node["filename"])
if missing:
# This bitmap was not found in previous nodes - a hole.
raise se.InvalidBitmapChain(
reason="Bitmap is missing in {}".format(missing),
bitmap=bitmap)
# Found a valid bitmap in this node.
filenames.append(node["filename"])
break
else:
# Bitmap is not in this node. Continue to search next nodes to
# detect holes.
missing.append(node["filename"])
return filenames
def start_transient_service(server_id, config):
if os.geteuid() != 0:
return supervdsm.getProxy().nbd_start_transient_service(
server_id, config)
_verify_path(config.path)
cmd = [
str(QEMU_NBD),
"--socket", _socket_path(server_id),
"--persistent",
# Allow up to 8 clients to share the device. Safe for readers, but for
# now, consistency is not guaranteed between multiple writers. Eric
# Blake says it should be safe if clients write to distinct areas.
# https://patchwork.kernel.org/patch/11096321/
"--shared=8",
# Use empty export name for nicer url: "nbd:unix:/path" instead of
# "nbd:unix:/path:exportname=name".
"--export-name=",
"--cache=none",
"--aio=native",
]
if config.format != "raw":
# Enable detection of unallocated extents in qcow2 images. Required for
# downloading single volume with backing_chain=False. Always enable it
# so NBD client can inspect image allocation.
# For raw images allocation depth is not useful, and also triggers a
# bug in qemu-nbd 6.2 breaking extents reporting in some cases.
# See https://bugzilla.redhat.com/2041480.
cmd.append("--allocation-depth")
if config.readonly:
cmd.append("--read-only")
else:
if config.discard:
cmd.append("--discard=unmap")
if config.detect_zeroes:
# "on" convert zero write to fallocate(WRITE_ZEROES).
# "unmap" convert zero write to fallocate(PUNCH_HOLE).
detect_mode = "unmap" if config.discard else "on"
cmd.append("--detect-zeroes={}".format(detect_mode))
if config.bitmap:
cmd.append("--bitmap={}".format(config.bitmap))
cmd.append(json_uri(config))
systemd.run(
cmd,
unit=_service_name(server_id),
uid=fileUtils.resolveUid(constants.VDSM_USER),
gid=fileUtils.resolveGid(constants.VDSM_GROUP))
def json_uri(config):
image = {
"driver": config.format,
"file": {
"driver": "host_device" if config.is_block else "file",
"filename": config.path,
}
}
if config.format == "qcow2" and not config.backing_chain:
image["backing"] = None
return "json:" + json.dumps(image)
def _verify_path(path):
"""
Anyone running as vdsm can invoke nbd_start_transient_service() with
arbitrary path. Verify the path is in the storage repository, or path is a
transient disk with a backing file in the storage repository.
"""
path = os.path.normpath(path)
if path.startswith(transientdisk.P_TRANSIENT_DISKS):
path = qemuimg.info(path, format="qcow2")["backing-filename"]
if not path.startswith(sc.REPO_MOUNT_DIR):
raise InvalidPath(
"Path {!r} is outside storage repository {!r}"
.format(path, sc.REPO_MOUNT_DIR))
def _service_name(server_id):
return "vdsm-nbd-{}.service".format(server_id)
def _socket_path(server_id):
return os.path.join(RUN_DIR, server_id + ".sock")
def _wait_for_socket(sock, timeout):
start = monotonic_time()
elapsed = 0.0
while elapsed < timeout:
if os.path.exists(sock):
log.debug("Waited for socket %.3f seconds", elapsed)
return True
# Socket is usually availble after 20 milliseconds.
time.sleep(0.02)
elapsed = monotonic_time() - start
return False
def _create_rundir():
try:
# /run/vdsm must exists, created by systemd. Do not try to recreate it,
# hiding the fact that it was missing.
os.mkdir(RUN_DIR)
except OSError as e:
if e.errno != errno.EEXIST:
raise
else:
log.info("Created %s", RUN_DIR)