2

How can I tell if a /dev/nbd* device is in use? Will "lsof" tell me? Or is there a better way? Is there an equivalent to "losetup -a" which will tell me the next free one?

0

nbd-client -c /dev/nbdX does not do the job correctly.

It may tell, that /dev/nbdX is not in use while it still is used internally in the kernel driver. In that case you neither see this in dmsetup nor with nbd-client.

Example:

% nbd-client -c /dev/ndb2; echo $?
1
% e2fsck /dev/nbd2; echo $?
e2fsck 1.42.13 (17-May-2015)
/dev/nbd2 is in use.
e2fsck: Cannot continue, aborting.
8

Actually the second indicator you need is revealed by fsck:

% strace e2fsck /dev/nbd2 2>&1 | grep open | grep /dev/nbd2
open("/dev/nbd2", O_RDONLY|O_EXCL) = -1 EBUSY (Device or resource busy)

Compare this with a really unused NBD-device:

% nbd-client -c /dev/ndb1; echo $?; strace e2fsck /dev/nbd1 2>&1 | grep open | grep /dev/nbd1
1
open("/dev/nbd1", O_RDONLY|O_EXCL) = 4

So this is the correct way to determine a /dev/nbdX is not used:

nbd-available()
{
nbd-client -c "$1";
[ 1 = $? ] &&
python -c 'import os,sys; os.open(sys.argv[1], os.O_EXCL)' "$1" 2>/dev/null;
}
get-available-nbd()
{
local a;
for a in /dev/nbd[0-9] /dev/nbd[1-9][0-9];
do
  nbd-available "$a" || continue;
  echo "$a";
  return;
done
return 1;
}

use it like nbd="`get-available-nbd`" || fail "no free NBD device"

2

From the man page:

nbd-client -c /dev/nbdX

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.