Class: Yast::SpaceCalculationClass

Inherits:
Module
  • Object
show all
Includes:
Logger
Defined in:
../../src/modules/SpaceCalculation.rb

Constant Summary

MIN_SPARE_KIB =

16 MiB (in KiB)

16 * 1024
MAX_SPARE_KIB =

1 GiB (in KiB)

1 * 1024 * 1024
MIB =

1 MiB in KiB

1024

Instance Method Summary (collapse)

Instance Method Details

- (Boolean) btrfs_snapshots?(directory)

check whether the Btrfs filesystem at the specified directory contains any snapshot (in any subvolume)

Parameters:

  • directory (String)

    mounted directory with Btrfs

Returns:

  • (Boolean)

    true when a snapshot is found



1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File '../../src/modules/SpaceCalculation.rb', line 1047

def btrfs_snapshots?(directory)
  # list available snapshot subvolumes
  ret = SCR.Execute(path(".target.bash_output"), "btrfs subvolume list -s #{Shellwords.escape(directory)}")

  if ret["exit"] != 0
    log.error "btrfs call failed: #{ret}"
    raise "Cannot detect Btrfs snapshots, subvolume listing failed : #{ret["stderr"]}"
  end

  snapshots = ret["stdout"].split("\n")
  log.info "Found #{snapshots.size} btrfs snapshots"
  log.debug "Snapshots: #{snapshots}"

  !snapshots.empty?
end

- (Integer) btrfs_used_size(directory)

Returns used size in bytes

Parameters:

  • directory (String)

    mounted directory with Btrfs

Returns:

  • (Integer)

    used size in bytes



1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
# File '../../src/modules/SpaceCalculation.rb', line 1065

def btrfs_used_size(directory)
  ret = SCR.Execute(path(".target.bash_output"),
    "LC_ALL=C btrfs filesystem df #{Shellwords.escape(directory)}")

  if ret["exit"] != 0
    log.error "btrfs call failed: #{ret}"
    raise "Cannot detect Btrfs disk usage: #{ret["stderr"]}"
  end

  df_info = ret["stdout"].split("\n")
  log.info "Usage reported by btrfs: #{df_info}"

  # sum the "used" sizes
  used = df_info.reduce(0) do |acc, line |
    size = line[/used=(\S+)/, 1]
    size = size ? size_from_string(size) : 0
    acc += size
  end

  log.info "Detected total used size: #{used} (#{used / 1024 / 1024}MiB)"
  used
end

- (Object) CheckCurrentSpace(current_partitions)

get current space data for partitions current_partitions = list of maps of $[“format”:bool, “free”:integer, “name” : string, “used” :integer, “used_fs”: symbol] from Storage module returns list of maps of $[“name” : string, “free” : integer, “used” : integer ]



812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
# File '../../src/modules/SpaceCalculation.rb', line 812

def CheckCurrentSpace(current_partitions)
  current_partitions = deep_copy(current_partitions)
  output = []

  Builtins.foreach(current_partitions) do |par|
    outdata = {}
    Ops.set(outdata, "name", Ops.get_string(par, "name", ""))
    Ops.set(
      outdata,
      "used",
      Pkg.TargetUsed(
        Ops.add(Installation.destdir, Ops.get_string(par, "name", ""))
      )
    )
    Ops.set(
      outdata,
      "free",
      Ops.subtract(
        Pkg.TargetCapacity(
          Ops.add(Installation.destdir, Ops.get_string(par, "name", ""))
        ),
        Ops.get_integer(outdata, "used", 0)
      )
    )
    output = Builtins.add(output, Builtins.eval(outdata))
  end
  Builtins.y2milestone(
    "CheckCurrentSpace(%1) = %2",
    current_partitions,
    output
  )

  deep_copy(output)
end

- (Array) CheckDiskFreeSpace(free_percent, max_unsufficient_free_size)

Check, if there is enough free space after installing the current selection

Parameters:

  • free_percent (Fixnum)

    minimal free space after installation (in percent)

Returns:

  • (Array)

    of partitions which have less than free_percent free size



978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# File '../../src/modules/SpaceCalculation.rb', line 978

def CheckDiskFreeSpace(free_percent, max_unsufficient_free_size)
  GetPartitionInfo() if !@info_called

  Builtins.y2milestone(
    "min. free space: %1%%, max. unsufficient free space: %2",
    free_percent,
    max_unsufficient_free_size
  )

  ret = []

  if Ops.greater_than(free_percent, 0)
    #$[ "dir" : [ total, usednow, usedfuture ], .... ]
    Builtins.foreach(Pkg.TargetGetDU) do |dir, sizelist|
      Builtins.y2milestone("Disk usage of directory %1: %2", dir, sizelist)
      total = Ops.get_integer(sizelist, 0, 0)
      used_future = Ops.get_integer(sizelist, 2, 0)
      used_now = Ops.get_integer(sizelist, 1, 0)
      current_free_size = Ops.subtract(total, used_future)
      current_free_percent = Ops.divide(
        Ops.multiply(current_free_size, 100),
        total
      )
      # ignore the partitions which were already full and no files will be installed there (bnc#259493)
      if Ops.greater_than(used_future, used_now) &&
          Ops.greater_than(current_free_size, 0)
        if Ops.less_than(current_free_percent, free_percent) &&
            Ops.less_than(current_free_size, max_unsufficient_free_size)
          Builtins.y2warning(
            "Partition %1: less than %2%% free space (%3%%, %4)",
            dir,
            free_percent,
            current_free_percent,
            current_free_size
          )

          ret = Builtins.add(
            ret,
            {
              "dir"          => dir,
              "free_percent" => current_free_percent,
              "free_size"    => current_free_size
            }
          )
        end
      end
    end
  end

  Builtins.y2milestone("Result: %1", ret)

  deep_copy(ret)
end

- (Object) CheckDiskSize

Check, if the current selection fits on the disk return true or false



944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
# File '../../src/modules/SpaceCalculation.rb', line 944

def CheckDiskSize
  fit = true

  GetPartitionInfo() if !@info_called

  used = 0

  #$[ "dir" : [ total, usednow, usedfuture ], .... ]
  Builtins.foreach(Pkg.TargetGetDU) do |dir, sizelist|
    Builtins.y2milestone("%1: %2", dir, sizelist)
    needed = Ops.subtract(
      Ops.get_integer(sizelist, 2, 0),
      Ops.get_integer(sizelist, 0, 0)
    ) # usedfuture - total
    if Ops.greater_than(needed, 0)
      Builtins.y2warning(
        "Partition \"%1\" needs %2 more disk space.",
        # size is in kB
        dir,
        String.FormatSize(Ops.multiply(needed, 1024))
      )
      fit = false
    end
    used = Ops.add(used, Ops.get_integer(sizelist, 2, 0))
  end

  Builtins.y2milestone("Total used space (kB): %1, fits ?: %2", used, fit)

  fit
end

- (Object) DefaultExtJournalSize(part)

return default ext3/4 journal size (in B) for target partition size



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
# File '../../src/modules/SpaceCalculation.rb', line 193

def DefaultExtJournalSize(part)
  part = deep_copy(part)
  if Ops.get_symbol(part, "used_fs", :unknown) == :ext2
    Builtins.y2milestone("No journal on ext2")
    return 0
  end

  ret = 0

  part_size = Ops.multiply(1024, Ops.get_integer(part, "size_k", 0))
  # default block size is 4k
  bs = Builtins.tointeger(
    Ops.get_string(
      part,
      ["fs_options", "opt_blocksize", "option_value"],
      "4096"
    )
  )
  blocks = Ops.divide(part_size, bs)

  Builtins.y2milestone(
    "Partition %1: %2 blocks (block size: %3)",
    Ops.get_string(part, "name", ""),
    blocks,
    bs
  )

  # values extracted from ext2fs_default_journal_size() function in e2fsprogs sources
  if Ops.less_than(blocks, 2048)
    ret = 0
  elsif Ops.less_than(blocks, 32768)
    ret = 1024
  elsif Ops.less_than(blocks, 256 * 1024)
    ret = 4096
  elsif Ops.less_than(blocks, 512 * 1024)
    ret = 8192
  elsif Ops.less_than(blocks, 1024 * 1024)
    ret = 16384
  else
    # maximum journal size
    ret = 32768
  end

  # converts blocks to bytes
  ret = Ops.multiply(ret, bs)

  Builtins.y2milestone("Default journal size: %1kB", Ops.divide(ret, 1024))


  ret
end

- (Object) DefaultJfsJournalSize(part_size)



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File '../../src/modules/SpaceCalculation.rb', line 320

def DefaultJfsJournalSize(part_size)
  # the default is 0.4% rounded to megabytes, 128MB max.
  ret = Ops.shift_right(part_size, 8) # 0.4% ~= 1/256
  max = 128 * (1 << 20) # 128 MB

  ret = Ops.shift_left(
    Ops.shift_right(Ops.subtract(Ops.add(ret, 1 << 20), 1), 20),
    20
  )

  ret = max if Ops.greater_than(ret, max)

  Builtins.y2milestone(
    "Default JFS journal size: %1MB",
    Ops.shift_right(ret, 20)
  )

  ret
end

- (Object) EstimateFsOverhead(part)

return estimated fs overhead (the difference between partition size and reported fs blocks)



448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File '../../src/modules/SpaceCalculation.rb', line 448

def EstimateFsOverhead(part)
  part = deep_copy(part)
  fs_size = Ops.multiply(1024, Ops.get_integer(part, "size_k", 0))
  fs = Ops.get_symbol(part, "used_fs", :unknown)

  ret = 0

  if ExtFs(fs)
    # ext2/3/4 overhead is about 1.6% according to my test (8GB partition)
    ret = Ops.divide(Ops.multiply(fs_size, 16), 1000)
    Builtins.y2milestone("Estimated Ext2/3/4 overhead: %1kB", ret)
  elsif fs == :xfs
    # xfs overhead is about 0.1%
    ret = Ops.divide(fs_size, 1000)
    Builtins.y2milestone("Estimated XFS overhead: %1kB", ret)
  elsif fs == :jfs
    # jfs overhead is about 0.3%
    ret = Ops.divide(Ops.multiply(fs_size, 3), 1000)
    Builtins.y2milestone("Estimated JFS overhead: %1kB", ret)
  end
  # reiser and btrfs have negligible overhead, just ignore it

  ret
end

- (Object) EstimateTargetUsage(parts)



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
# File '../../src/modules/SpaceCalculation.rb', line 368

def EstimateTargetUsage(parts)
  parts = deep_copy(parts)
  log.info "EstimateTargetUsage(#{parts})"

  # invalid or empty input
  if parts == nil || parts.empty?
    log.error "Invalid input: #{parts.inspect}"
    return []
  end

  # the numbers are from openSUSE-11.4 default KDE installation
  used_mapping = {
    "/var/lib/rpm"    => 42 * MIB, # RPM database
    "/var/log"        => 14 * MIB, # system logs (YaST logs have ~12MB)
    "/var/adm/backup" => 10 * MIB, # backups
    "/var/cache/zypp" => 38 * MIB, # zypp metadata cache after refresh (with OSS + update repos)
    "/etc"            =>  2 * MIB, # various /etc config files not belonging to any package
    "/usr/share"      =>  1 * MIB, # some files created by postinstall scripts
    "/boot/initrd"    => 11 * MIB  # depends on HW but better than nothing
  }

  Builtins.y2milestone("Adding target size mapping: %1", used_mapping)

  mount_points = []

  # convert list to map indexed by mount point
  mounts = Builtins.listmap(parts) do |part|
    mount_points = Builtins.add(
      mount_points,
      Ops.get_string(part, "name", "")
    )
    { Ops.get_string(part, "name", "") => part }
  end


  Builtins.foreach(used_mapping) do |dir, used|
    mounted = String.FindMountPoint(dir, mount_points)
    Builtins.y2milestone("Dir %1 is mounted on %2", dir, mounted)
    part = Ops.get(mounts, mounted, {})
    if part != {}
      curr_used = Ops.get_integer(part, "used", 0)
      Builtins.y2milestone(
        "Adding %1kB to %2kB currently used",
        used,
        curr_used
      )
      curr_used = Ops.add(curr_used, used)

      Ops.set(part, "used", curr_used)
      Ops.set(
        part,
        "free",
        Ops.subtract(Ops.get_integer(part, "free", 0), used)
      )

      Ops.set(mounts, mounted, part)
    else
      Builtins.y2warning(
        "Cannot find partition for mount point %1, ignoring it",
        mounted
      )
    end
  end


  # convert back to list
  ret = Builtins.maplist(mounts) { |dir, part| part }

  Builtins.y2milestone("EstimateTargetUsage() result: %1", ret)

  deep_copy(ret)
end

- (Array) EvaluateFreeSpace(spare_percentage)

Evaluate the free space on the file system. Runs the command “df” and creates a map containig information about used and free space on every partition. Free space is calculated respecting the spare_percentage given in second argument.

* This is needed during update !

Examples:

EvaluateFreeSpace ( 5 );

Parameters:

  • spare_percentage (Fixnum)

    percentage of spare disk space, i.e. free space is increased

Returns:

  • (Array)

    partition list, e.g. [$[“free”:389318, “name”:“/”, “used”:1487222], $[“free”:1974697, “name”:“/usr”, “used”:4227733]]



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
# File '../../src/modules/SpaceCalculation.rb', line 95

def EvaluateFreeSpace(spare_percentage)
  target = Installation.destdir

  # get information about diskspace ( used/free space on every partition )
  partitions = SCR.Read(path(".run.df"))

  # filter out headline and other invalid entries
  partitions.select!{ |p| p["name"].start_with?("/") }

  log.info "df result: #{partitions}"

  # TODO FIXME dirinstall has been dropped, probably drop this block completely
  if Installation.dirinstall_installing_into_dir
    target = GetDirMountPoint(Installation.dirinstall_target, partitions)
    log.info "Installing into a directory, target directory: " \
      "#{Installation.dirinstall_target}, target mount point: #{target}"
  end

  du_partitions = []

  partitions.each do |part|
    part_info = {}
    mountName = part["name"] || ""

    # TODO FIXME dirinstall has been dropped, probably drop this block completely?
    if Installation.dirinstall_installing_into_dir
      mountName.prepend("/") unless mountName.start_with?("/")
      dir_target = Installation.dirinstall_target

      log.debug "mountName: #{mountName}, dir_target: #{dir_target}"

      if mountName.start_with?(dir_target)
        part_info["name"] = mountName
      elsif mountName == target
        part_info["name"] = "/"
      end
    elsif target != "/"
      if mountName.start_with?(target)
        partName = mountName[target.size..-1]
        # nothing left, it was target root itself
        part_info["name"] = partName.empty? ? "/" : partName
      end # target is "/"
    else
      if mountName == "/"
        part_info["name"] = mountName
      # ignore some mount points
      elsif mountName != Installation.sourcedir && mountName != "/cdrom" &&
          mountName != "/dev/shm" &&
          part["spec"] != "udev" &&
          !mountName.start_with?("/media/") &&
          !mountName.start_with?("/var/adm/mount/")
        part_info["name"] = mountName
      end
    end

    next if part_info.empty?

    filesystem = part["type"]
    part_info["filesystem"] = filesystem

    if filesystem == "btrfs"
      log.info "Detected btrfs at #{mountName}"
      btrfs_used_kib = btrfs_used_size(mountName) / 1024
      log.info "Difference to 'df': #{(part["used"].to_i - btrfs_used_kib) / 1024}MiB"
      part_info["used"] = btrfs_used_kib
      part_info["growonly"] = btrfs_snapshots?(mountName)
      total_kb = part["whole"].to_i
      free_size_kib = total_kb - btrfs_used_kib
    else
      part_info["used"] = part["used"].to_i
      free_size_kib = part["free"].to_i
      part_info["growonly"] = false
    end

    spare_size_kb = free_size_kib * spare_percentage / 100

    if spare_size_kb < MIN_SPARE_KIB
      spare_size_kb = MIN_SPARE_KIB
    elsif spare_size_kb > MAX_SPARE_KIB
      spare_size_kb = MAX_SPARE_KIB
    end

    free_size_kib -= spare_size_kb
    # don't use a negative size
    free_size_kib = 0 if free_size_kib < 0

    part_info["free"] = free_size_kib

    du_partitions << part_info
  end

  log.info "UTILS *** EvaluateFreeSpace returns: #{du_partitions}"
  Pkg.TargetInitDU(du_partitions)

  du_partitions
end

- (Object) ExtFs(fs)

is the filesystem one of Ext2/3/4?



442
443
444
# File '../../src/modules/SpaceCalculation.rb', line 442

def ExtFs(fs)
  fs == :ext2 || fs == :ext3 || fs == :ext4
end

- (Object) ExtJournalSize(part)



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
# File '../../src/modules/SpaceCalculation.rb', line 245

def ExtJournalSize(part)
  part = deep_copy(part)
  if Ops.get_symbol(part, "used_fs", :unknown) == :ext2
    Builtins.y2milestone("No journal on ext2")
    return 0
  end

  ret = 0
  # no journal
  if Builtins.haskey(Ops.get_map(part, "fs_options", {}), "no_journal")
    Builtins.y2milestone(
      "Partition %1 has disabled journal",
      Ops.get_string(part, "name", "")
    )
  else
    Builtins.y2milestone(
      "Using default journal size for %1",
      Ops.get_string(part, "name", "")
    )
    ret = DefaultExtJournalSize(part)
  end
  # Note: custom journal size cannot be entered in the partitioner

  Builtins.y2milestone(
    "Journal size for %1: %2kB",
    Ops.get_string(part, "name", ""),
    Ops.divide(ret, 1024)
  )

  ret
end

- (Object) get_partition_info

Define a macro that transforms information about all partitions ( from Storage::GetTargetMap() ) into a list(map) with information about partitions which are available for installation, e.g.:

[$[“free”:1625676, “name”:“/boot”, “used”:0], $[“free”:2210406, “name”:“/”, “used”:0]]

Please note: there isn't any information about used space, so “used” at begin of installation is initialized with zero; size “free”, “used” in KBytes



526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
# File '../../src/modules/SpaceCalculation.rb', line 526

def get_partition_info
  # remove leading slash so it matches the packages.DU path
  remove_slash = true

  if !Stage.initial
    # read /proc/mounts as a list of maps
    # $["file":"/boot", "freq":0, "mntops":"rw", "passno":0, "spec":"/dev/sda1", "vfstype":"ext2"]
    mounts = SCR.Read(path(".proc.mounts"))
    log.info "mounts #{mounts}"

    partitions = []
    mounts.each do |mpoint|
      name = mpoint["file"]
      filesystem = mpoint["vfstype"]

      if name.start_with?("/") &&
          # filter out /dev/pts etc.
          !name.start_with?("/dev/") &&
          # filter out duplicate "/" entry
          filesystem != "rootfs"

        capacity = Pkg.TargetCapacity(name)

        if capacity != 0 # dont look at pseudo-devices (proc, shmfs, ...)
          used = Pkg.TargetUsed(name)
          growonly = false

          if filesystem == "btrfs"
            log.info "Btrfs file system detected at #{name}"
            growonly = btrfs_snapshots?(name)
            log.info "Snapshots detected: #{growonly}"
            new_used = btrfs_used_size(name) / 1024
            log.info "Updated the used size by 'btrfs' utility from #{used} to #{new_used} (diff: #{new_used - used})"
            used = new_used
          end

          partitions << {
            "name" => name,
            "free" => capacity - used,
            "used" => used,
            "filesystem" => filesystem,
            "growonly" => growonly
          }
        end
      end
    end
    Pkg.TargetInitDU(partitions)
    Builtins.y2milestone("get_partition_info: %1", partitions)
    return partitions
  end # !Stage::initial ()

  # remove the previous failures
  @failed_mounts = []

  # installation stage - Storage:: is definitely present
  # call Storage::GetTargetMap()
  targets = Convert.convert(
    WFM.call("wrapper_storage", ["GetTargetMap"]),
    :from => "any",
    :to   => "map <string, map>"
  )

  log.error "Target map is nil, Storage:: is probably missing" unless targets

  if Mode.test
    targets = Convert.convert(
      SCR.Read(path(".target.yast2"), "test_target_map.ycp"),
      :from => "any",
      :to   => "map <string, map>"
    )
  end

  target_partitions = []
  min_spare = 20 * 1024 * 1024 # minimum free space ( 20 MB )

  Builtins.foreach(targets) do |disk, diskinfo|
    part_info = Ops.get_list(diskinfo, "partitions", [])
    Builtins.foreach(part_info) do |part|
      log.info "Adding partition: #{part}"
      used_fs = part["used_fs"]
      # ignore VFAT and NTFS partitions (bnc#)
      if used_fs == :vfat || used_fs == :ntfs
        log.warn "Ignoring partition with #{used_fs} filesystem"
      else
        free_size = 0
        growonly = false

        if Ops.get(part, "mount") != nil &&
            part["mount"].start_with?("/")
          if Ops.get(part, "create") == true ||
              Ops.get(part, "delete") == false ||
              Ops.get(part, "create") == nil &&
                Ops.get(part, "delete") == nil
            log.debug "get_partition_info: adding partition: #{part}"

            # get free_size on partition in kBytes
            free_size = part["size_k"] * 1024
            free_size -= min_spare

            # free_size smaller than min_spare, fix negative value
            if free_size <  0
              log.info "Fixing free size: #{free_size} to 0"
              free_size = 0
            end

            used = 0
            # If reusing a previously existent filesystem
            if !(part["create"] || part["format"])

              # Mount the filesystem to check the available space.
              # FIXME: libstorage provides functions to query free
              # information for devices (even caching the information).
              # This part should be refactored to rely on libstorage.

              tmpdir = SCR.Read(path(".target.tmpdir")) + "/diskspace_mount"
              SCR.Execute(path(".target.bash"), "mkdir -p #{Shellwords.escape(tmpdir)}")

              # mount options determined by partitioner
              mount_options = (part["fstopt"] || "").split(",")

              # mount in read-only mode (safer)
              mount_options << "ro"

              # add "nolock" if it's a NFS share (bnc#433893)
              if used_fs == :nfs
                log.info "Mounting NFS with 'nolock' option"
                mount_options << "nolock"
              end

              # join the options
              mount_options_str = mount_options.uniq.join(",")

              # Use DM device if it's encrypted, plain device otherwise
              # (bnc#889334)
              device = part["crypt_device"] || part["device"] || ""

              mount_command = "mount -o #{mount_options_str} " \
                "#{Shellwords.escape(device)} #{Shellwords.escape(tmpdir)}"

              log.info "Executing mount command: #{mount_command}"

              result = SCR.Execute(path(".target.bash"), mount_command)
              log.info "Mount result: #{result}"

              if result == 0
                # specific handler for btrfs
                if used_fs == :btrfs
                  used = btrfs_used_size(tmpdir)
                  free_size -= used
                  growonly = btrfs_snapshots?(tmpdir)
                else
                  partition = SCR.Read(path(".run.df"))

                  Builtins.foreach(partition) do |p|
                    if p["name"] == tmpdir
                      log.info "Partition: #{p}"
                      free_size = p["free"].to_i * 1024
                      used = p["used"].to_i * 1024
                    end
                  end
                end

                SCR.Execute(path(".target.bash"), "umount #{Shellwords.escape(tmpdir)}")
              else
                log.error "Mount failed, ignoring partition #{device}"
                @failed_mounts = Builtins.add(@failed_mounts, part)

                next
              end
            else
              # for formatted partitions estimate free system size
              # compute fs overhead
              used = EstimateFsOverhead(part)
              log.info "#{device}: assuming fs overhead: #{used / 1024}KiB"

              # get the journal size
              case used_fs
              when :ext2, :ext3, :ext4
                js = ExtJournalSize(part)
                reserved = ReservedSpace(part)
                used += reserved if reserved > 0
              when :xfs
                js = XfsJournalSize(part)
              when :reiser
                js = ReiserJournalSize(part)
              when :jfs
                js = JfsJournalSize(part)
              when :btrfs
                # Btrfs uses temporary trees instead of a fixed journal,
                # there is no journal, it's a logging FS
                # http://en.wikipedia.org/wiki/Btrfs#Log_tree
                js = 0
              else
                log.warn "Unknown journal size for filesystem: #{used_fs}"
              end

              if js && js > 0
                log.info "Partition #{part["device"]}: assuming journal size: #{js / 1024}KiB"
                used += js
              end

              # decrease free size
              free_size -= used

              # check for underflow
              if free_size < 0
                log.info "Fixing free size: #{free_size} to 0"
                free_size = 0
              end
            end

            # convert into KiB for TargetInitDU
            free_size_kib = free_size / 1024
            used_kib = used / 1024
            mount_name = part["mount"]
            log.info "partition: mount: #{mount_name}, free: #{free_size_kib}KiB, used: #{used_kib}KiB"

            mount_name = mount_name[1..-1] if remove_slash && mount_name != "/"

            target_partitions << {
              "filesystem" => used_fs.to_s,
              "growonly" => growonly,
              "name" => mount_name,
              "used" => used_kib,
              "free" => free_size_kib
            }
          end
        end
      end
    end # foreach (`part)
  end # foreach (`disk)

  # add estimated size occupied by non-package files
  target_partitions = EstimateTargetUsage(target_partitions)

  Builtins.y2milestone("get_partition_info: part %1", target_partitions)
  Pkg.TargetInitDU(target_partitions)

  deep_copy(target_partitions)
end

- (Object) GetDirMountPoint(target, partition)

Get mountpoint for a directory

Parameters:

  • target (String)

    directory

  • partition (Array<Hash{String => String>})

    partitions list

Returns:

  • mountpoint



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File '../../src/modules/SpaceCalculation.rb', line 61

def GetDirMountPoint(target, partition)
  partition = deep_copy(partition)
  d = Builtins.splitstring(target, "/")
  d = Builtins.filter(d) { |fd| fd != "" }
  mountpoint = ""

  Builtins.foreach(partition) do |part|
    #  dirinstall: /test/xen dir: /test
    #  dirinstall:/var/tmp/xen dir: /
    dir = Ops.get_string(part, "name", "")
    tmpdir = ""
    Builtins.foreach(d) do |dd|
      tmpdir = Builtins.sformat("%1/%2", tmpdir, dd)
      Builtins.y2debug("tmpdir: %1 dir: %2", tmpdir, dir)
      mountpoint = dir if dir == tmpdir
    end
  end

  mountpoint = "/" if mountpoint == ""

  mountpoint
end

- (Object) GetFailedMounts



53
54
55
# File '../../src/modules/SpaceCalculation.rb', line 53

def GetFailedMounts
  deep_copy(@failed_mounts)
end

- (Object) GetPartitionInfo

Get information about available partitions either from “targetMap” in case of a new installation or from 'df' command (continue mode and installation on installed system). Returns a list containing available partitions and stores the list in “partition_info”.

Will be called from Packages when re-doing proposal !!

Examples:

GetPartitionInfo();

Returns:

  • list partition list, e.g. [$[“free”:389318, “name”:“/”, “used”:1487222], $[“free”:1974697, “name”:“usr”, “used”:4227733]]



780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
# File '../../src/modules/SpaceCalculation.rb', line 780

def GetPartitionInfo
  partition = []

  if Stage.cont
    partition = EvaluateFreeSpace(0) # free spare already checked during first part of installation
  elsif Mode.update
    partition = EvaluateFreeSpace(15) # 15% free spare for update/upgrade
  elsif Mode.normal
    partition = EvaluateFreeSpace(5) # 5% free spare for post installation # Stage::initial ()
  else
    partition = get_partition_info
  end
  Builtins.y2milestone(
    "INIT done, SpaceCalculation - partitions: %1",
    partition
  )

  @info_called = true
  @partition_info = deep_copy(partition) # store partition_info

  deep_copy(partition)
end

- (Object) GetPartitionList

Return partition info list

Returns:

  • list of available partitions



49
50
51
# File '../../src/modules/SpaceCalculation.rb', line 49

def GetPartitionList
  deep_copy(@partition_info)
end

- (Object) GetPartitionWarning



847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
# File '../../src/modules/SpaceCalculation.rb', line 847

def GetPartitionWarning
  GetPartitionInfo() if !@info_called
  used = 0
  message = []

  #$[ "dir" : [ total, usednow, usedfuture ], .... ]

  Builtins.foreach(Pkg.TargetGetDU) do |dir, sizelist|
    Builtins.y2milestone(
      "dir %1, sizelist (total, current, future) %2",
      dir,
      sizelist
    )
    needed = Ops.subtract(
      Ops.get_integer(sizelist, 2, 0),
      Ops.get_integer(sizelist, 0, 0)
    ) # usedfuture - total
    if Ops.greater_than(needed, 0)
      # Warning message, e.g.: Partition /usr needs 35 MB more disk space
      message = Builtins.add(
        message,
        Builtins.sformat(
          _("Partition \"%1\" needs %2 more disk space."),
          # needed is in kB
          dir,
          String.FormatSize(Ops.multiply(needed, 1024))
        )
      )
    end
    used = Ops.add(used, Ops.get_integer(sizelist, 2, 0))
  end

  Builtins.y2debug("Total used space (kB): %1", used)

  if Ops.greater_than(Builtins.size(message), 0)
    # dont ask user to deselect packages for imap server, product
    if ProductFeatures.GetFeature("software", "selection_type") == :auto
      if Mode.update
        message = Builtins.add(
          message,
          "\n" +
            # popup message
            _(
              "Deselect packages or delete data or temporary files\nbefore updating the system.\n"
            )
        )
      else
        message = Builtins.add(
          message,
          "\n" +
            # popup message
            _("Deselect some packages.")
        )
      end
    end
  end
  deep_copy(message)
end

- (Object) GetRequSpace(initialize)

Calculate required disk space



924
925
926
927
928
929
930
931
932
933
934
935
936
937
# File '../../src/modules/SpaceCalculation.rb', line 924

def GetRequSpace(initialize)
  GetPartitionInfo() if !@info_called

  # used space in kB
  used = 0

  #$[ "dir" : [ total, usednow, usedfuture ], .... ]
  Builtins.foreach(Pkg.TargetGetDU) do |dir, sizelist|
    used = Ops.add(used, Ops.get_integer(sizelist, 2, 0))
  end
  Builtins.y2milestone("GetReqSpace Pkg::TargetGetDU() %1", Pkg.TargetGetDU)
  # used is in kB
  String.FormatSize(Ops.multiply(used, 1024))
end

- (Object) JfsJournalSize(part)



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
# File '../../src/modules/SpaceCalculation.rb', line 340

def JfsJournalSize(part)
  part = deep_copy(part)
  # log size (in MB)
  log_size = Builtins.tointeger(
    Ops.get_string(
      part,
      ["fs_options", "opt_log_size", "option_value"],
      "0"
    )
  )

  if Ops.greater_than(log_size, 0)
    # convert to bytes
    log_size = Ops.multiply(log_size, 1 << 20)
  else
    log_size = DefaultJfsJournalSize(
      Ops.multiply(1024, Ops.get_integer(part, "size_k", 0))
    )
  end

  Builtins.y2milestone(
    "Jfs journal size: %1MB",
    Ops.shift_right(log_size, 20)
  )

  log_size
end

- (Object) main



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File '../../src/modules/SpaceCalculation.rb', line 29

def main
  Yast.import "Pkg"

  textdomain "packager"

  Yast.import "Installation"
  Yast.import "Mode"
  Yast.import "ProductFeatures"
  Yast.import "Report"
  Yast.import "String"
  Yast.import "Stage"

  @info_called = false # list partition_info already initialized?
  @partition_info = [] # information about available partitions

  @failed_mounts = []
end

- (Object) ReiserJournalSize(part)



307
308
309
310
311
312
313
314
315
316
317
318
# File '../../src/modules/SpaceCalculation.rb', line 307

def ReiserJournalSize(part)
  part = deep_copy(part)
  # the default is 8193 of 4k blocks (max = 32749, min = 513 blocks)
  ret = 8193 * 4096

  Builtins.y2milestone(
    "Default Reiser journal size: %1kB",
    Ops.divide(ret, 1024)
  )

  ret
end

- (Object) ReservedSpace(part)

return reserved space for root user (in bytes)



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
# File '../../src/modules/SpaceCalculation.rb', line 474

def ReservedSpace(part)
  part = deep_copy(part)
  # read the percentage
  option = Ops.get_string(
    part,
    ["fs_options", "opt_reserved_blocks", "option_value"],
    ""
  )
  ret = 0

  if option != nil && option != ""
    percent = Builtins.tofloat(option)

    if Ops.greater_than(percent, 0.0)
      # convert to absolute value
      fs_size = Ops.get_integer(part, "size_k", 0)
      ret = Builtins.tointeger(
        Ops.multiply(
          Convert.convert(
            Ops.divide(fs_size, 100),
            :from => "integer",
            :to   => "float"
          ),
          percent
        )
      )
    end
  end

  if Ops.greater_than(ret, 0)
    Builtins.y2milestone(
      "Partition %1: reserved space: %2%% (%3kB)",
      Ops.get_string(part, "name", ""),
      option,
      ret
    )
  end

  Ops.multiply(ret, 1024)
end

- (Object) ShowPartitionWarning

Popup displays warning about exhausted disk space



909
910
911
912
913
914
915
916
917
918
# File '../../src/modules/SpaceCalculation.rb', line 909

def ShowPartitionWarning
  message = GetPartitionWarning()
  if Ops.greater_than(Builtins.size(message), 0)
    Builtins.y2warning("Warning: %1", message)
    Report.Message(Builtins.mergestring(message, "\n"))
    return true
  else
    return false
  end
end