nspkg / engine / download_space.v
58 lines · 52 sloc · 2.25 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1// download block accounting and free-space cushion follow diskspace.c.
2// SPDX-License-Identifier: GPL-2.0-or-later
3module engine
4
5import os
6
7#include "@DIR/native_space.h"
8
9@[typedef]
10struct C.v_alpm_space_info {
11mut:
12 block_size u64
13 blocks u64
14 available u64
15 read_only u32
16}
17
18fn C.v_alpm_space_stat(&char, &C.v_alpm_space_info) i32
19
20fn download_space_needed(sizes []i64, block_size u64, blocks u64) !u64 {
21 if block_size == 0 { return error('filesystem block size is zero') }
22 five_percent := blocks / 20 + 1
23 twenty_mib := u64(20 * 1024 * 1024) / block_size + 1
24 mut needed := if five_percent < twenty_mib { five_percent } else { twenty_mib }
25 for size in sizes {
26 if size < 0 { return error('negative download size') }
27 // keep the source's extra block, including at block_size-1 boundaries.
28 if block_size > (~u64(0) - 1) / 2 {
29 return error('filesystem block size overflows accounting')
30 }
31 amount := u64(size) / block_size + (u64(size) % block_size + block_size + 1) / block_size
32 if amount > ~u64(0) - needed { return error('download space accounting overflow') }
33 needed += amount
34 }
35 return needed
36}
37
38fn (mut handle Handle) check_download_space(directory string, sizes []i64) ! {
39 destination := os.real_path(directory)
40 mut mounts := handle.load_space_mounts()!
41 index := installation_mount_index(mounts, destination) or {
42 handle.log(.error, localized_message('could not determine cachedir mount point %s\n', destination))
43 return handle.fail(.disk_space, 'cannot determine cachedir mount point ${destination}')
44 }
45 mut mount := unsafe { &mounts[index] }
46 if !handle.load_installation_mount(mut mount) {
47 return handle.fail(.disk_space, 'cannot get filesystem information for ${mount.path}')
48 }
49 needed := download_space_needed(sizes, mount.info.block_size, mount.info.blocks) or { return handle.fail(.disk_space, err.msg()) }
50 cushion := download_space_needed([], mount.info.block_size, mount.info.blocks) or { return handle.fail(.disk_space, err.msg()) }
51 if needed - cushion > u64(max_i64) {
52 return handle.fail(.disk_space, 'download space accounting overflow')
53 }
54 mount.maximum_needed = i64(needed - cushion)
55 if handle.space_mount_full(mount)! {
56 return handle.fail(.disk_space, '${mount.path}: ${needed} blocks needed, ${mount.info.available} available')
57 }
58}
59