Skip to content

Instantly share code, notes, and snippets.

@vps2fast
Last active February 21, 2021 15:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vps2fast/5e633b9715c6b736565e to your computer and use it in GitHub Desktop.
Save vps2fast/5e633b9715c6b736565e to your computer and use it in GitHub Desktop.
openvz_swap_usage.pl
#!/usr/bin/perl
use strict;
use warnings;
###
### Скрипт для подсчета места, забитого контейнерами в swap
###
my @containers = get_running_containers_list();
for my $ctid (@containers) {
next if $ctid == 1;
my @processes = `cat /proc/vz/fairsched/$ctid/tasks`;
chomp @processes;
my $container_smaps = {};
my $total_swap_usage = 0;
for my $p (@processes) {
my $status = get_proc_status($p);
unless ($status) {
next;
}
# так как для мнонгопоточных приложений (читай - java) куча потоков отражаются как процесс
# поэтому все потоки мы выкинем, ибо swap у них общий
if (defined $status->{Tgid} && $status->{Tgid} != $status->{Pid}) {
next;
}
if (defined $status->{VmSwap}) {
if ($status->{VmSwap} =~ m/(\d+)\s+kB/) {
$total_swap_usage += $1;
}
}
}
my $vswap_usage = sprintf("%.1f", get_vswap_usage($ctid) / 1024 ** 2);
my $total_in_mb = sprintf("%.1f", $total_swap_usage / 1024);
print "Container: $ctid vswap usage for container: $vswap_usage MB swap usage for container $ctid is: $total_in_mb MB\n";
}
# Получить список запущенных контейнеров
sub get_running_containers_list {
my @list_raw = `/usr/sbin/vzlist -1`;
my @list = ();
for my $ct (@list_raw) {
$ct =~ s/^\s+//g;
$ct =~ s/\s+$//g;
push @list, $ct;
}
return @list;
}
sub get_vswap_usage {
my $ctid = shift;
my $vswap_pages = `/usr/sbin/vzlist -Hoswappages $ctid`;
chomp $vswap_pages;
$vswap_pages =~ s/\s+//g;
return $vswap_pages * 4096;
}
# Считывем файл в массив
sub read_file_contents_to_list {
my $path = shift;
my $res = open my $fl, "<", $path;
unless ($res) {
return ();
}
my @data = <$fl>;
chomp @data;
close $fl;
return @data;
}
# Получить данные статуса процесса в виде хэша
sub get_proc_status {
my $pid = shift;
my @array = read_file_contents_to_list("/proc/$pid/status");
my $status = {};
unless (scalar @array > 0) {
return '';
}
for my $line (@array) {
my @data = split /:\s+/, $line, 2;
$status->{$data[0]} = $data[1];
}
return $status;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment