]> git.proxmox.com Git - pve-common.git/blob - src/PVE/ProcFSTools.pm
7cf14721c2f2bb872ae41ae301a3d6a095826c26
[pve-common.git] / src / PVE / ProcFSTools.pm
1 package PVE::ProcFSTools;
2
3 use strict;
4 use warnings;
5 use POSIX;
6 use Time::HiRes qw (gettimeofday);
7 use IO::File;
8 use List::Util qw(sum);
9 use PVE::Tools;
10 use Cwd qw();
11
12 use Socket qw(PF_INET PF_INET6 SOCK_DGRAM IPPROTO_IP);
13
14 use constant IFF_UP => 1;
15 use constant IFNAMSIZ => 16;
16 use constant SIOCGIFFLAGS => 0x8913;
17
18 my $clock_ticks = POSIX::sysconf(&POSIX::_SC_CLK_TCK);
19
20 my $cpuinfo;
21
22 sub read_cpuinfo {
23 my $fn = '/proc/cpuinfo';
24
25 return $cpuinfo if $cpuinfo;
26
27 my $res = {
28 user_hz => $clock_ticks,
29 model => 'unknown',
30 mhz => 0,
31 cpus => 1,
32 sockets => 1,
33 flags => '',
34 };
35
36 my $fh = IO::File->new ($fn, "r");
37 return $res if !$fh;
38
39 my $cpuid = 0;
40 my $idhash = {};
41 my $count = 0;
42 while (defined(my $line = <$fh>)) {
43 if ($line =~ m/^processor\s*:\s*\d+\s*$/i) {
44 $count++;
45 } elsif ($line =~ m/^model\s+name\s*:\s*(.*)\s*$/i) {
46 $res->{model} = $1 if $res->{model} eq 'unknown';
47 } elsif ($line =~ m/^cpu\s+MHz\s*:\s*(\d+\.\d+)\s*$/i) {
48 $res->{mhz} = $1 if !$res->{mhz};
49 } elsif ($line =~ m/^flags\s*:\s*(.*)$/) {
50 $res->{flags} = $1 if !length $res->{flags};
51 } elsif ($line =~ m/^physical id\s*:\s*(\d+)\s*$/i) {
52 $cpuid = $1;
53 $idhash->{$1} = 1 if not defined($idhash->{$1});
54 } elsif ($line =~ m/^cpu cores\s*:\s*(\d+)\s*$/i) {
55 $idhash->{$cpuid} = $1 if defined($idhash->{$cpuid});
56 }
57 }
58
59 # Hardware Virtual Machine (Intel VT / AMD-V)
60 $res->{hvm} = $res->{flags} =~ m/\s(vmx|svm)\s/;
61
62 $res->{sockets} = scalar(keys %$idhash) || 1;
63
64 $res->{cores} = sum(values %$idhash) || 1;
65
66 $res->{cpus} = $count;
67
68 $fh->close;
69
70 $cpuinfo = $res;
71
72 return $res;
73 }
74
75 sub read_proc_uptime {
76 my $ticks = shift;
77
78 my $line = PVE::Tools::file_read_firstline("/proc/uptime");
79 if ($line && $line =~ m|^(\d+\.\d+)\s+(\d+\.\d+)\s*$|) {
80 if ($ticks) {
81 return (int($1*$clock_ticks), int($2*$clock_ticks));
82 } else {
83 return (int($1), int($2));
84 }
85 }
86
87 return (0, 0);
88 }
89
90 sub kernel_version {
91 my $line = PVE::Tools::file_read_firstline("/proc/version");
92
93 if ($line && $line =~ m|^Linux\sversion\s((\d+(?:\.\d+)+)-?(\S+)?)|) {
94 my ($fullversion, $version_numbers, $extra) = ($1, $2, $3);
95
96 # variable names are the one from the Linux kernel Makefile
97 my ($version, $patchlevel, $sublevel) = split(/\./, $version_numbers);
98
99 return wantarray
100 ? (int($version), int($patchlevel), int($sublevel), $extra, $fullversion)
101 : $fullversion;
102 }
103
104 return (0, 0, 0, '', '');
105 }
106
107 # Check if the kernel is at least $major.$minor. Return either just a boolean,
108 # or a boolean and the kernel version's major.minor string from /proc/version
109 sub check_kernel_release {
110 my ($major, $minor) = @_;
111
112 my ($k_major, $k_minor) = kernel_version();
113
114 my $ok;
115 if (defined($minor)) {
116 $ok = $k_major > $major || ($k_major == $major && $k_minor >= $minor);
117 } else {
118 $ok = $k_major >= $major;
119 }
120
121 return wantarray ? ($ok, "$k_major.$k_minor") : $ok;
122 }
123
124 sub read_loadavg {
125
126 my $line = PVE::Tools::file_read_firstline('/proc/loadavg');
127
128 if ($line =~ m|^(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)\s+\d+/\d+\s+\d+\s*$|) {
129 return wantarray ? ($1, $2, $3) : $1;
130 }
131
132 return wantarray ? (0, 0, 0) : 0;
133 }
134
135 my $last_proc_stat;
136
137 sub read_proc_stat {
138 my $res = { user => 0, nice => 0, system => 0, idle => 0 , sum => 0};
139
140 my $cpucount = 0;
141
142 if (my $fh = IO::File->new ("/proc/stat", "r")) {
143 while (defined (my $line = <$fh>)) {
144 if ($line =~ m|^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s|) {
145 $res->{user} = $1;
146 $res->{nice} = $2;
147 $res->{system} = $3;
148 $res->{idle} = $4;
149 $res->{used} = $1+$2+$3;
150 $res->{iowait} = $5;
151 } elsif ($line =~ m|^cpu\d+\s|) {
152 $cpucount++;
153 }
154 }
155 $fh->close;
156 }
157
158 $cpucount = 1 if !$cpucount;
159
160 my $ctime = gettimeofday; # floating point time in seconds
161
162 $res->{ctime} = $ctime;
163 $res->{cpu} = 0;
164 $res->{wait} = 0;
165
166 $last_proc_stat = $res if !$last_proc_stat;
167
168 my $diff = ($ctime - $last_proc_stat->{ctime}) * $clock_ticks * $cpucount;
169
170 if ($diff > 1000) { # don't update too often
171 my $useddiff = $res->{used} - $last_proc_stat->{used};
172 $useddiff = $diff if $useddiff > $diff;
173 $res->{cpu} = $useddiff/$diff;
174
175 my $waitdiff = $res->{iowait} - $last_proc_stat->{iowait};
176 $waitdiff = $diff if $waitdiff > $diff;
177 $res->{wait} = $waitdiff/$diff;
178
179 $last_proc_stat = $res;
180 } else {
181 $res->{cpu} = $last_proc_stat->{cpu};
182 $res->{wait} = $last_proc_stat->{wait};
183 }
184
185 return $res;
186 }
187
188 sub read_proc_pid_stat {
189 my $pid = shift;
190
191 my $statstr = PVE::Tools::file_read_firstline("/proc/$pid/stat");
192
193 if ($statstr && $statstr =~ m/^$pid \(.*\) (\S) (-?\d+) -?\d+ -?\d+ -?\d+ -?\d+ \d+ \d+ \d+ \d+ \d+ (\d+) (\d+) (-?\d+) (-?\d+) -?\d+ -?\d+ -?\d+ 0 (\d+) (\d+) (-?\d+) \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ -?\d+ -?\d+ \d+ \d+ \d+/) {
194 return {
195 status => $1,
196 ppid => $2,
197 utime => $3,
198 stime => $4,
199 starttime => $7,
200 vsize => $8,
201 rss => $9 * 4096,
202 };
203 }
204
205 return undef;
206 }
207
208 sub check_process_running {
209 my ($pid, $pstart) = @_;
210
211 # note: waitpid only work for child processes, but not
212 # for processes spanned by other processes.
213 # kill(0, pid) return succes for zombies.
214 # So we read the status form /proc/$pid/stat instead
215
216 my $info = read_proc_pid_stat($pid);
217
218 return $info && (!$pstart || ($info->{starttime} eq $pstart)) && ($info->{status} ne 'Z') ? $info : undef;
219 }
220
221 sub read_proc_starttime {
222 my $pid = shift;
223
224 my $info = read_proc_pid_stat($pid);
225 return $info ? $info->{starttime} : 0;
226 }
227
228 sub read_meminfo {
229
230 my $res = {
231 memtotal => 0,
232 memfree => 0,
233 memused => 0,
234 memshared => 0,
235 swaptotal => 0,
236 swapfree => 0,
237 swapused => 0,
238 };
239
240 my $fh = IO::File->new ("/proc/meminfo", "r");
241 return $res if !$fh;
242
243 my $d = {};
244 while (my $line = <$fh>) {
245 if ($line =~ m/^(\S+):\s+(\d+)\s*kB/i) {
246 $d->{lc ($1)} = $2 * 1024;
247 }
248 }
249 close($fh);
250
251 $res->{memtotal} = $d->{memtotal};
252 $res->{memfree} = $d->{memfree} + $d->{buffers} + $d->{cached};
253 $res->{memused} = $res->{memtotal} - $res->{memfree};
254
255 $res->{swaptotal} = $d->{swaptotal};
256 $res->{swapfree} = $d->{swapfree};
257 $res->{swapused} = $res->{swaptotal} - $res->{swapfree};
258
259 my $spages = PVE::Tools::file_read_firstline("/sys/kernel/mm/ksm/pages_sharing") // 0 ;
260 $res->{memshared} = int($spages) * 4096;
261
262 return $res;
263 }
264
265 # memory usage of current process
266 sub read_memory_usage {
267
268 my $res = { size => 0, resident => 0, shared => 0 };
269
270 my $ps = 4096;
271
272 my $line = PVE::Tools::file_read_firstline("/proc/$$/statm");
273
274 if ($line =~ m/^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*/) {
275 $res->{size} = $1*$ps;
276 $res->{resident} = $2*$ps;
277 $res->{shared} = $3*$ps;
278 }
279
280 return $res;
281 }
282
283 sub read_proc_net_dev {
284
285 my $res = {};
286
287 my $fh = IO::File->new ("/proc/net/dev", "r");
288 return $res if !$fh;
289
290 while (defined (my $line = <$fh>)) {
291 if ($line =~ m/^\s*(.*):\s*(\d+)\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+/) {
292 $res->{$1} = {
293 receive => $2,
294 transmit => $3,
295 };
296 }
297 }
298
299 close($fh);
300
301 return $res;
302 }
303
304 sub write_proc_entry {
305 my ($filename, $data) = @_;#
306
307 my $fh = IO::File->new($filename, O_WRONLY);
308 die "unable to open file '$filename' - $!\n" if !$fh;
309 die "unable to write '$filename' - $!\n" unless print $fh $data;
310 die "closing file '$filename' failed - $!\n" unless close $fh;
311 $fh->close();
312 }
313
314 sub read_proc_net_route {
315 my $filename = "/proc/net/route";
316
317 my $res = [];
318
319 my $fh = IO::File->new ($filename, "r");
320 return $res if !$fh;
321
322 my $int_to_quad = sub {
323 return join '.' => map { ($_[0] >> 8*(3-$_)) % 256 } (3, 2, 1, 0);
324 };
325
326 while (defined(my $line = <$fh>)) {
327 next if $line =~/^Iface\s+Destination/; # skip head
328 my ($iface, $dest, $gateway, $metric, $mask, $mtu) = (split(/\s+/, $line))[0,1,2,6,7,8];
329 push @$res, {
330 dest => &$int_to_quad(hex($dest)),
331 gateway => &$int_to_quad(hex($gateway)),
332 mask => &$int_to_quad(hex($mask)),
333 metric => $metric,
334 mtu => $mtu,
335 iface => $iface,
336 };
337 }
338
339 return $res;
340 }
341
342 sub read_proc_mounts {
343 return PVE::Tools::file_get_contents("/proc/mounts", 512*1024);
344 }
345
346 # mounts encode spaces (\040), tabs (\011), newlines (\012), backslashes (\\ or \134)
347 sub decode_mount {
348 my ($str) = @_;
349 return $str =~ s/\\(?:040|01[12]|134|\\)/"\"$&\""/geer;
350 }
351
352 sub parse_mounts {
353 my ($mounts) = @_;
354 my $mntent = [];
355 while ($mounts =~ /^\s*([^#].*)$/gm) {
356 # lines from the file are encoded so we can just split at spaces
357 my ($what, $dir, $fstype, $opts) = split(/[ \t]/, $1, 4);
358 my ($freq, $passno) = (0, 0);
359 # in glibc's parser frequency and pass seem to be optional
360 $freq = $1 if $opts =~ s/\s+(\d+)$//;
361 $passno = $1 if $opts =~ s/\s+(\d+)$//;
362 push @$mntent, [decode_mount($what),
363 decode_mount($dir),
364 decode_mount($fstype),
365 decode_mount($opts),
366 $freq, $passno];
367 }
368 return $mntent;
369 }
370
371 sub parse_proc_mounts {
372 return parse_mounts(read_proc_mounts());
373 }
374
375 sub is_mounted {
376 my ($mountpoint) = @_;
377
378 $mountpoint = Cwd::realpath($mountpoint);
379
380 return 0 if !defined($mountpoint); # path does not exist
381
382 my $mounts = parse_proc_mounts();
383 return (grep { $_->[1] eq $mountpoint } @$mounts) ? 1 : 0;
384 }
385
386 sub read_proc_net_ipv6_route {
387 my $filename = "/proc/net/ipv6_route";
388
389 my $res = [];
390
391 my $fh = IO::File->new ($filename, "r");
392 return $res if !$fh;
393
394 my $read_v6addr = sub { $_[0] =~ s/....(?!$)/$&:/gr };
395
396 # ipv6_route has no header
397 while (defined(my $line = <$fh>)) {
398 my ($dest, $prefix, $nexthop, $metric, $iface) = (split(/\s+/, $line))[0,1,4,5,9];
399 push @$res, {
400 dest => &$read_v6addr($dest),
401 prefix => hex("$prefix"),
402 gateway => &$read_v6addr($nexthop),
403 metric => hex("$metric"),
404 iface => $iface
405 };
406 }
407
408 return $res;
409 }
410
411 sub upid_wait {
412 my ($upid, $waitfunc, $sleep_intervall) = @_;
413
414 my $task = PVE::Tools::upid_decode($upid);
415
416 $sleep_intervall = $sleep_intervall ? $sleep_intervall : 1;
417
418 my $next_time = time + $sleep_intervall;
419
420 while (check_process_running($task->{pid}, $task->{pstart})) {
421
422 if (time >= $next_time && $waitfunc && ref($waitfunc) eq 'CODE'){
423 &$waitfunc($task);
424 $next_time = time + $sleep_intervall;
425 }
426
427 CORE::sleep(1);
428 }
429 }
430
431 # struct ifreq { // FOR SIOCGIFFLAGS:
432 # char ifrn_name[IFNAMSIZ]
433 # short ifru_flags
434 # };
435 my $STRUCT_IFREQ_SIOCGIFFLAGS = 'Z' . IFNAMSIZ . 's1';
436 sub get_active_network_interfaces {
437 # Use the interface name list from /proc/net/dev
438 open my $fh, '<', '/proc/net/dev'
439 or die "failed to open /proc/net/dev: $!\n";
440 # And filter by IFF_UP flag fetched via a PF_INET6 socket ioctl:
441 my $sock;
442 socket($sock, PF_INET6, SOCK_DGRAM, &IPPROTO_IP)
443 or socket($sock, PF_INET, SOCK_DGRAM, &IPPROTO_IP)
444 or return [];
445
446 my $ifaces = [];
447 while(defined(my $line = <$fh>)) {
448 next if $line !~ /^\s*([^:\s]+):/;
449 my $ifname = $1;
450 my $ifreq = pack($STRUCT_IFREQ_SIOCGIFFLAGS, $ifname, 0);
451 if (!defined(ioctl($sock, SIOCGIFFLAGS, $ifreq))) {
452 warn "failed to get interface flags for: $ifname\n";
453 next;
454 }
455 my ($name, $flags) = unpack($STRUCT_IFREQ_SIOCGIFFLAGS, $ifreq);
456 push @$ifaces, $ifname if ($flags & IFF_UP);
457 }
458 close $fh;
459 close $sock;
460 return $ifaces;
461 }
462
463 1;