]> git.proxmox.com Git - pve-common.git/blob - src/PVE/Format.pm
cgroup: cpu quota: fix resetting period length for v1
[pve-common.git] / src / PVE / Format.pm
1 package PVE::Format;
2
3 use strict;
4 use warnings;
5
6 use POSIX qw(strftime round);
7
8 use base 'Exporter';
9 our @EXPORT_OK = qw(
10 render_timestamp
11 render_timestamp_gmt
12 render_duration
13 render_fraction_as_percentage
14 render_bytes
15 );
16
17 sub render_timestamp {
18 my ($epoch) = @_;
19
20 # ISO 8601 date format
21 return strftime("%F %H:%M:%S", localtime($epoch));
22 }
23
24 sub render_timestamp_gmt {
25 my ($epoch) = @_;
26
27 # ISO 8601 date format, standard Greenwich time zone
28 return strftime("%F %H:%M:%S", gmtime($epoch));
29 }
30
31 sub render_duration {
32 my ($duration_in_seconds) = @_;
33
34 my $text = '';
35 my $rest = round($duration_in_seconds // 0);
36
37 return "0s" if !$rest;
38
39 my $step = sub {
40 my ($unit, $unitlength) = @_;
41
42 if ((my $v = int($rest/$unitlength)) > 0) {
43 $text .= " " if length($text);
44 $text .= "${v}${unit}";
45 $rest -= $v * $unitlength;
46 }
47 };
48
49 $step->('w', 7*24*3600);
50 $step->('d', 24*3600);
51 $step->('h', 3600);
52 $step->('m', 60);
53 $step->('s', 1);
54
55 return $text;
56 }
57
58 sub render_fraction_as_percentage {
59 my ($fraction) = @_;
60
61 return sprintf("%.2f%%", $fraction*100);
62 }
63
64 sub render_bytes {
65 my ($value, $precision) = @_;
66
67 $precision = $precision->{precision} if ref($precision) eq 'HASH';
68
69 my @units = qw(B KiB MiB GiB TiB PiB);
70
71 my $max_unit = 0;
72 if ($value > 1023) {
73 $max_unit = int(log($value)/log(1024));
74 $value /= 1024**($max_unit);
75 }
76 my $unit = $units[$max_unit];
77 return sprintf "%." . ($precision || 2) . "f $unit", $value;
78 }
79
80 1;