Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,7 @@ EOF
```bash
sudo install -Tm440 /dev/stdin /etc/sudoers.d/99-vol <<-'EOF'
Cmnd_Alias VOL_FORMAT = /usr/sbin/diskutil ^eraseDisk -noEFI APFS [a-zA-Z]+ /dev/disk[1-9][0-9]*$
Cmnd_Alias VOL_MOUNT = /usr/sbin/diskutil ^mount -mountPoint /mnt/point /dev/disk[1-9]+s[0-9]+$
Cmnd_Alias VOL_MOUNT = /usr/sbin/diskutil ^mount nobrowse -mountPoint /mnt/point /dev/disk[1-9]+s[0-9]+$
Cmnd_Alias VOL_UMOUNT = /usr/sbin/diskutil ^umount /mnt/point$, /usr/sbin/diskutil ^umount /Volumes/[a-zA-Z]+$
user ALL=(root) NOPASSWD: VOL_FORMAT, VOL_MOUNT, VOL_UMOUNT
EOF
Expand Down
52 changes: 39 additions & 13 deletions vol
Original file line number Diff line number Diff line change
Expand Up @@ -192,12 +192,19 @@ def get_args():
toList = list

def run(cmd, **kw):
check = kw.get('check', True)
try:
command = ['sudo'] + cmd if kw.get('sudo') else cmd
options = {'capture_output': True, 'text': True, 'check': True} | {k: kw[k] for k in kw if k != 'sudo'}
return subprocess.run(command, **options)
except subprocess.CalledProcessError as e:
if not check:
return e
err(text = f'Command {cmd} failed with exit status {e.returncode}:\n{e.stderr}')
except subprocess.TimeoutExpired as e:
if not check:
return subprocess.CompletedProcess(command, 124, stdout=e.stdout or '', stderr=e.stderr or 'Timed out')
err(text = f'Command {cmd} timed out:\n{e.stderr or ""}')

def run2json(cmd):
return json.loads(run(['plutil', '-convert', 'json', '-o', '-', '-'], input=run(cmd).stdout).stdout)
Expand Down Expand Up @@ -493,6 +500,9 @@ def attach_volume(volume, instance_id):
if [a for a in volume['Attachments'] if a['InstanceId'] == instance_id]:
msg(f'{volume_desc} is already attached to {instance_id}')
return
other_instance_id = volume['Attachments'][0]['InstanceId']
msg(f'{volume_desc} is attached to instance {other_instance_id}, detaching')
return attach_volume(detach_and_wait(volume), instance_id)
Comment thread
Copilot marked this conversation as resolved.
Resolved

err(text = f'{volume_desc} is in state {volume_state} and can\'t be attached')

Expand All @@ -513,6 +523,10 @@ def detach_volume(volume):
case volume_state:
err(text = f'{volume_desc} is in state {volume_state} and can\'t be detached')

def detach_and_wait(volume):
detach_volume(volume)
Comment thread
Copilot marked this conversation as resolved.
Resolved
return wait_for_volume(volume, wait_states = ['in-use/attached', 'in-use/detaching', 'in-use/detached'])
Comment thread
Copilot marked this conversation as resolved.
Resolved

def delete_volume(volume):
volume_desc = get_volume_desc(volume)
volume_state = get_volume_state(volume)
Expand All @@ -523,9 +537,12 @@ def delete_volume(volume):
return ec2.delete_volume(VolumeId=volume["VolumeId"])
case 'deleted' | 'deleting':
dbg(f'{volume_desc} is {volume_state}')
case 'in-use/detaching':
case 'in-use/attached':
msg(f'{volume_desc} is attached, detaching before delete')
return delete_volume(detach_and_wait(volume))
Comment thread
Copilot marked this conversation as resolved.
Resolved
case 'in-use/detaching' | 'in-use/detached':
dbg(f'{volume_desc} is detaching, waiting...')
updated_volume = wait_for_volume(volume, wait_states = [volume_state])
updated_volume = wait_for_volume(volume, wait_states = ['in-use/detaching', 'in-use/detached'])
return delete_volume(updated_volume)
case _:
err(text = f'{volume_desc} is in state {volume_state} and can\'t be deleted')
Expand Down Expand Up @@ -565,19 +582,24 @@ def mount(volume_id, mountpoint, fstype):
makedirs(mountpoint, exist_ok=True)
match system():
case 'Darwin':
# Disk Arbitration mounts a new volume at /Volumes/<name> and can remount it
# there between an unmount and diskutil mount. A failed mount must be retried;
# run() would otherwise exit. nobrowse matches Jenkins start-mount.
for _ in range(5):
di = run2json(['diskutil', 'info', '-plist', disk])
if realpath(di['MountPoint']) == realpath(mountpoint):
current = di.get('MountPoint') or ''
if current and realpath(current) == realpath(mountpoint):
return
# Countering the automounter
if di['MountPoint'] == f'/Volumes/{di["VolumeName"]}':
umount(di['MountPoint'], force=True)
if current.startswith('/Volumes/'):
umount(current, force=True, check=False, timeout=30)
msg(f'Mounting {disk} ({volume_id}) at {mountpoint}')
run(['diskutil', 'mount', '-mountPoint', mountpoint, disk], sudo=not is_mac_admin())
if ismount(mountpoint):
mounted = run(['diskutil', 'mount', 'nobrowse', '-mountPoint', mountpoint, disk],
sudo=not is_mac_admin(), check=False, timeout=30)
if mounted.returncode == 0 and ismount(mountpoint):
return
else:
msg(f'Path {mountpoint} is not a mountpoint (likely automounted under /Volumes)')
detail = (mounted.stderr or mounted.stdout or '').strip()
msg(f'Failed to mount {disk} ({volume_id}) at {mountpoint}' + (f': {detail}' if detail else ''))
sleep(2)
err(text = f'Failed to mount volume {volume_id} at {mountpoint}')
case _:
findmnt = run(['findmnt', '-rno', 'SOURCE', mountpoint], check=False)
Expand All @@ -587,15 +609,19 @@ def mount(volume_id, mountpoint, fstype):
msg(f'Mounting {disk} ({volume_id}) at {mountpoint}')
run(['mount', '-t', fstype, '-o', 'noatime', disk, mountpoint], sudo=True)

def umount(mountpoint, force = False):
def umount(mountpoint, force = False, check = True, timeout = None):
msg(f'Unmounting {mountpoint}')
if ismount(mountpoint):
match system():
case 'Darwin':
maybe_force = ['force'] if force else []
run(['diskutil', 'umount'] + maybe_force + [mountpoint], sudo=not is_mac_admin())
result = run(['diskutil', 'umount'] + maybe_force + [mountpoint],
sudo=not is_mac_admin(), check=check, timeout=timeout)
case _:
run(['umount', mountpoint], sudo=True)
result = run(['umount', mountpoint], sudo=True, check=check, timeout=timeout)
if not check and result.returncode != 0:
msg(f'Unmount of {mountpoint} failed ({result.returncode}): {(result.stderr or "").strip()}')
return result
else:
msg(f'Path {mountpoint} is not a mountpoint, nothing to do')

Expand Down
Loading