Mini Shell

Direktori : /usr/share/l.v.e-manager/cpanel/original/
Upload File :
Current File : //usr/share/l.v.e-manager/cpanel/original/CloudLinux.cgi

#!/usr/local/cpanel/3rdparty/bin/perl
# CloudLinux - whostmgr/docroot/cgi/CloudLinux.cgi Copyright(c) 2010 CloudLinux, Inc.
#                                                                All rights Reserved.
#                                          		    http://www.cloudlinux.com
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#WHMADDON:lvemanager:CloudLinux Manager
#ACLS:all

use strict;
use Whostmgr::ACLS          ();
use Whostmgr::HTMLInterface ();
use Cpanel::Encoder::Tiny   ();
use Cpanel::Form            ();
use Cpanel::Locale          ('lh');
use XML::LibXML             ();
use Cpanel::SafeRun::Errors ();
use Whostmgr::Theme         ();

Whostmgr::ACLS::init_acls();

my %FORM      = Cpanel::Form::parseform();
my $cgiaction = $FORM{'cgiaction'};
if ( $cgiaction eq 'chartpng' ) {
    print "Content-type: image/png\r\n\r\n";
    drawChart( $FORM{'lveid'}, $FORM{'timeframe'} );
    exit;
}

print "Content-type: text/html\r\n\r\n";

Whostmgr::HTMLInterface::defheader( lh()->maketext('[asis,LVE] Manager'), '/themes/x/icons/cloudlinux_lve_manager.png', '/cgi/CloudLinux.cgi' );

# Check privileges
if ( !Whostmgr::ACLS::hasroot() ) {
    print qq{
<br />
<br />
<div><h1>Permission denied</h1></div>
</body>
</html>
    };
    exit;
}

my $theme = Whostmgr::Theme::gettheme();
my $self  = 'CloudLinux.cgi';

if ( $cgiaction eq 'editlve' ) {
    editLVE( $FORM{'lveid'} );
}
elsif ( $cgiaction eq 'savelve' ) {
    saveLVE();
}
elsif ( $cgiaction eq 'del' ) {
    delLVE( $FORM{'lveid'} );
}
elsif ( $cgiaction eq 'stats' ) {
    showStats( \%FORM );
}
elsif ( $cgiaction eq 'history' ) {
    showHistory( $FORM{'lveid'}, $FORM{'timeframe'}, $FORM{'username'} );
}
elsif ( $cgiaction eq 'chart' ) {
    showChart( $FORM{'lveid'}, $FORM{'timeframe'} );
}
else {
    showLVEUsage();
}

print "</body></html>\n";

sub delLVE {
    my $lveid = shift;
    Cpanel::SafeRun::Errors::saferunallerrors( '/usr/sbin/lvectl', 'delete', $lveid );
    showLVEUsage("Saved settings...");
}

# Returns true if all the characters in a string are digits
sub isnum { return $_[0] =~ /^\d+$/; }

sub saveLVE {
    my $lveid    = $FORM{'lveid'};
    my $cpu      = trim( $FORM{'cpu'} );
    my $mep      = trim( $FORM{'mep'} );
    my $persist  = $FORM{'persist'};
    my $username = trim( $FORM{'username'} );
    my $mem      = trim( $FORM{'mem'} ) . $FORM{'mem_unit'};
    my $ncpu     = trim( $FORM{'ncpu'} );

    if ( $lveid eq 'custom' ) {
        my $uid = getpwnam($username);
        $lveid = ( defined $uid ) ? $uid : $username;
        if ( !isnum($lveid) ) {
            showLVEUsage("Error! Please, enter valid LVE Id or username.");
            return;
        }
    }

    my @lvectl = ( '/usr/sbin/lvectl', 'set', $lveid );
    if ( isnum($cpu) ) {
        push @lvectl, '--cpu', $cpu;
    }
    if ( isnum($ncpu) ) {
        push @lvectl, '--ncpu', $ncpu;
    }
    if ( isnum( trim( $FORM{'mem'} ) ) ) {
        push @lvectl, '--mem', $mem;
    }
    if ( isnum($mep) ) {
        push @lvectl, '--maxEntryProcs', $mep;
    }
    if ( $persist eq 'on' ) {
        push @lvectl, '--save';
    }
    Cpanel::SafeRun::Errors::saferunallerrors(@lvectl);
    if ( $lveid eq 'default' ) {
        Cpanel::SafeRun::Errors::saferunallerrors( '/etc/init.d/lvectl', 'reload' );
    }
    showLVEUsage("Saved settings...");
}

sub editLVE {
    my $lveid = shift;
    return 1 if ( !$lveid );
    my $safe_lveid = Cpanel::Encoder::Tiny::safe_html_encode_str($lveid);
    my $LVE        = parseLVE();
    my $lve        = $LVE->{$lveid};
    my $dlve       = $LVE->{'default'};
    my $isDefault  = 'default' eq $lveid;
    my $isCustom   = 'custom' eq $lveid;
    my $isSet      = $lve;
    $lve = $lve ? $lve : $dlve;
    printHeader( '', $isDefault ? 'edit_default' : 'edit_custom' );
    print '<fieldset><legend>';

    if ($isDefault) {
        print 'Modify default LVE settings';
    }
    else {
        print "Modify settings for LVE $safe_lveid";
    }
    print <<"EOM";
</legend><form action=$self method=POST>
<table width="90%" padding="10"><tr><td>
   <input type=hidden name=cgiaction value=savelve>
   <input type=hidden name=lveid value="$safe_lveid">
EOM

    if ($isCustom) {
        print 'Username or LVE Id: <input type="text" size="20" name="username"/><br/>';
    }

    my $mem = RoundMemInt( $lve->{'mem'} << 2 );

    # Determine and select appropriate memory unit
    my $selectedK = '';
    my $selectedM = '';
    my $selectedG = '';
    my $unit      = chop($mem);
    if ( $unit eq 'K' ) {
        $selectedK = 'selected';
    }
    elsif ( $unit eq 'M' ) {
        $selectedM = 'selected';
    }
    else {
        $selectedG = 'selected';
    }

    print <<"EOM";
   CPU: <input type="text" size="5" name="cpu" value="$lve->{'cpu'}"/><br/>
   MEM: <input type="text" size="11" name="mem" value="$mem"/>
   <SELECT name="mem_unit">
   <option value="K" $selectedK>KB</option>
   <option value="M" $selectedM>MB</option>
   <option value="G" $selectedG>GB</option>
   </SELECT>
   <br/>
   Concurrent  Connections: <input type="text" size="5" name="mep" value="$lve->{'mep'}"/><br/>
   Number of Cores Per LVE*: <input type="text" size="5" name="ncpu" value="$lve->{'ncpu'}"/>  *requires server reboot for existing LVEs<br/>
   Persist: <input type="checkbox" name="persist" checked/>
   <blockquote><input class='btn-primary' type=submit value='save'>
EOM

    if ( !$isDefault && $isSet ) {
        print "<input class='btn-secondary' type='button' value='reset to default' onClick='location.href=\"$self?cgiaction=del&lveid=$safe_lveid\"'>";
    }

    print <<"EOM";
<input class='btn-cancel' type="button" value='back' onClick='location.href="$self"'>
   </blockquote>
</td><td valign="top" align="right" width="40%">
EOM

    my $dmem = RoundMemInt( $dlve->{'mem'} << 2 );

    if ( !$isDefault ) {
        print "<fieldset><legend>Defaults</legend>CPU: $dlve->{'cpu'}%<br/>MEM: $dmem<br/>Concurrent Connections: $dlve->{'mep'}<br/>Number of Cores Per LVE: $dlve->{'ncpu'}</fieldset>";
    }

    print "</td></tr></form></fielset>";
}

sub printLinks {
    my $page = shift;
    if ( $page eq 'usage' ) {
        print '[Home]';
    }
    else {
        print "[<a href=\"${self}\">Home</a>]";
    }
    print '&nbsp;&nbsp;&nbsp;';
    if ( $page eq 'edit_default' ) {
        print '[Edit Default Settings]';
    }
    else {
        print "[<a href=\"${self}?cgiaction=editlve&lveid=default\">Edit Default Settings</a>]";
    }
    print '&nbsp;&nbsp;&nbsp;';
    if ( $page eq 'edit_custom' ) {
        print '[Edit Settings For Specific LVE]';
    }
    else {
        print "[<a href=\"${self}?cgiaction=editlve&lveid=custom\">Edit Settings For Specific LVE</a>]";
    }
    print '&nbsp;&nbsp;&nbsp;';
    print "[<a href='#' onClick='toggleStats()'>Stats</a>]";
    print '&nbsp;&nbsp;&nbsp;';
    print "[<a href='#' onClick='toggleHistory()'>History</a>]";
}

sub getSelectedTimeOptions {
    my $period = shift;
    my $val    = '';
    foreach my $p ( '10m', '30m', '1h', '4h', 'today', 'yesterday', '7d', '30d' ) {
        $val = $period eq $p ? "${val}:SELECTED" : "${val}:";
    }
    return $val;
}

sub printTimeframe {
    my $opts = getSelectedTimeOptions(shift);
    my @op = split /:/, $opts;
    shift @op;
    print <<"EOM";
Timeframe: <select name='timeframe' size='1'><option value='10m' $op[0]>Last 10 minutes</option><option value='30m' $op[1]>Last 30 minutes</option><option value='1h' $op[2]>Last hour</option><option value='4h' $op[3]>Last 4 hours</option><option value='today' $op[4]>Today</option><option value='yesterday' $op[5]>Yesterday</option><option value='7d' $op[6]>Last 7 days</option><option value='30d' $op[7]>Last 30 days</option></select>
EOM
}

# sub printHistoryHeader {
#    my $lveid = shift;
#    my $cgiaction = shift;
#    my $period = shift;
#    print "<form action='${self}' method='GET'><input type='hidden' name='cgiaction' value='$cgiaction'>";
#    printTimeframe($period);
#    print "<input type=\"submit\"><input type=\"hidden\" name=\"lveid\" value=\"$lveid\"></form>";
# }

# $_[1] = message
# $_[2] = current page name
sub printHeader {
    my $safe_message = Cpanel::Encoder::Tiny::safe_html_encode_str(shift);
    my $page         = shift;
    my $period       = shift;
    my $isStats      = $page eq 'stats' ? 'true' : 'false';
    my $isHistory    = $page eq 'history' ? 'true' : 'false';

    if ($safe_message) {
        print "<h3>$safe_message</h3><br/>\n";
    }
    print <<"EOM";
    <br />
	<script type="text/javascript" src="/js/sorttable.js"></script>
<script type="text/javascript">
var shown=$isStats;
var h=$isHistory;
function toggleStats() {
    if (h) { toggleHistory(); }
    document.getElementById('stats_div').style.display=shown?'none':'block';
    document.getElementById('stats_div').style.visibility=shown?'hidden':'visible';
    shown = !shown;
}
function toggleHistory() {
    if (shown) { toggleStats(); }
    document.getElementById('history_div').style.display=h?'none':'block';
    document.getElementById('history_div').style.visibility=h?'hidden':'visible';
    h = !h;
}

</script>
	<div class="topboxmargin"></div>
        <div align="left">
EOM
    printLinks $page;
    if   ( $page eq 'stats' ) { print '</div><div id="stats_div" style="border:1px solid black">'; }
    else                      { print '</div><div id="stats_div" style="display:none;border:1px solid black">'; }
    print <<"EOM";
<form action="${self}" method="GET">
<input type='hidden' name='cgiaction' value='stats'>
EOM
    printTimeframe($period);
    print <<"EOM";
<br/>
<input type='radio' name='st' value='order-by' CHECKED>Show TOP LVEs By <select name='order-by' size='1'>
<option value=cpu_max>Max CPU</option><option value=cpu_avg>Average CPU</option><option value=mep_max>Max EP</option><option value=mep_avg>Average EP</option><option value=mem_max>Max MEM</option><option value=mem_avg>Average MEM</option>
<option value='total_mem_faults'>Memory Faults</option><option value='total_mep_faults'>Entry Procs Faults</option></select> Limit: <select name='limit' size='1'><option>10</option><option>25</option><option>50</option><option>100</option></select> <br/>
<input type='radio' name='st' value='by-usage'>Show LVEs Approaching Limit <select name='by-usage' size='1'>
<option value=cpu_max>Max CPU</option><option value=cpu_avg>Average CPU</option><option value=mep_max>Max EP</option><option value=mep_avg>Average EP</option><option value=mem_max>Max MEM</option><option value=mem_avg>Average MEM</option>
</select> Using: <select name='percentage' size='1'><option>50</option><option>75</option><option selected="selected">90</option><option>95</option></select>% <br/>
<input type='radio' name='st' value='by-fault'>By Fault <select name='by-fault' size='1'><option value='mep'>Max Entry Processes</option><option value='mem'>Max Memory Limit</option></select> Treshold: <select name='threshold' size='1'><option>1</option><option>10</option><option>50</option><option>75</option><option>1000</option>%</select><br/>
<input type="submit"><input type='reset'><br/>
</form>
</div>
<br/>
EOM

    #History div
    if ( $page eq 'history' ) {
        print '<div id="history_div" style="border:1px solid black">';
    }
    else {
        print '<div id="history_div" style="display:none;border:1px solid black">';
    }

    print <<"EOM";
<form action="$self" method="GET"><input type="hidden" name="cgiaction" value="history">
<input type='hidden' name='lveid' value='custom'>
Username or LVE Id: <input type="text" size="20" name="username"/><br/>
EOM
    printTimeframe($period);
    print '<input type="submit"></form></div>';
}

sub lveIdLink {
    my $safe_lveid  = Cpanel::Encoder::Tiny::safe_html_encode_str(shift);
    my $safe_period = Cpanel::Encoder::Tiny::safe_html_encode_str(shift);
    return "<nowrap><a href=\"$self?cgiaction=editlve&lveid=$safe_lveid\">$safe_lveid</a>&nbsp;(<a href=\"$self?cgiaction=history&timeframe=$safe_period&lveid=$safe_lveid\">?</a>)(<a href=\"$self?cgiaction=chart&timeframe=$safe_period&lveid=$safe_lveid\">c</a>)</nowrap>";
}

sub getUserDomain {
    my $id     = shift;
    my $name   = getpwuid($id);
    my $domain = '';
    if ( $name ne "" && -e "/var/cpanel/users/$name" ) {
        open FILE, "/var/cpanel/users/$name";
        while (<FILE>) {
            if (/^DNS=(.*)/) { $domain = $1; last; }
        }
    }
    return ( $name, $domain );
}

sub showChart {
    my $lveid       = shift;
    my $safe_lveid  = Cpanel::Encoder::Tiny::safe_html_encode_str($lveid);
    my $period      = shift;
    my $safe_period = Cpanel::Encoder::Tiny::safe_html_encode_str($period);
    printHeader( '', 'chart' );

    #   printHistoryHeader($lveid, 'chart', $period);
    print "<br/><a href='${self}?cgiaction=history&lveid=$safe_lveid&timeframe=$safe_period'>[History]</a><br/>";

    #    drawChart($lveid, $period);
    #    exit;
    print <<"EOM";
    <img src="${self}?cgiaction=chartpng&lveid=$safe_lveid&timeframe=$safe_period">
EOM
}

sub drawChart {
    my $lveid  = shift;
    my $period = shift;
    my @params = ( '/usr/sbin/lvechart', "--period=$period", "--id=$lveid", '--width=9', '--height=9', '--dpi=100' );
    my $out    = Cpanel::SafeRun::Errors::saferunallerrors(@params);
    print $out;
}

# Parameters: $FORM{'lveid'}, $FORM{'timeframe'}, $FORM{'username'}
sub showHistory {
    my $lveid       = shift;
    my $safe_lveid  = Cpanel::Encoder::Tiny::safe_html_encode_str($lveid);
    my $period      = shift;
    my $safe_period = Cpanel::Encoder::Tiny::safe_html_encode_str($period);
    my $username    = shift;
    printHeader( '', 'history', $period );
    if ( $lveid eq 'custom' ) {
        my $uid = getpwnam($username);
        $lveid = ( defined $uid ) ? $uid : $username;
        if ( !isnum($lveid) ) {
            print "<h3>Error! Please, enter valid LVE Id or username.</h3>";
            return;
        }
    }

    my @params  = ( '/usr/sbin/lveinfo', '--csv', "--period=$period", "--id=$lveid" );
    my $INPUT   = Cpanel::SafeRun::Errors::saferunallerrors(@params);
    my @results = split( /\n+/, $INPUT );
    my $bg      = 2;
    shift @results;

    #   printHistoryHeader($lveid, 'history', $period);
    print "<br/><a href='${self}?cgiaction=chart&lveid=$safe_lveid&timeframe=$safe_period'>[Chart]</a>";

    print <<"EOM";
	<table id="lveps" class="sortable" width="60%" cellspacing="1" cellpadding="0" border="0">
    <tr>
    <th>From</th>
    <th>To</th>
    <th>aCPU</th>
    <th>mCpu</th>
    <th>lCPU</th>
    <th>aEP</th>
    <th>mEP</th>
    <th>lEP</th>
    <th>aMem</th>
    <th>mMem</th>
    <th>lMem</th>
    <th>MemF</th>
    <th>MepF</th>
    </tr>
EOM

    foreach my $i (@results) {

        # From,To,aCPU,mCPU,lCPU,aEP,mEP,lEP,aMem,mMem,lMem,MemF,MepF
        my ( $from, $to, $acpu, $mcpu, $lcpu, $aep, $mep, $lep, $aMem, $mMem, $lMem, $memf, $mepf ) = split ',', $i;
        $aMem = RoundMemB($aMem);
        $mMem = RoundMemB($mMem);
        $lMem = RoundMemB($lMem);
        print <<"EOM";
    <tr class="tdshade${bg}">
    <td>$from</td>
    <td>$to</td>
    <td>$acpu</td>
    <td>$mcpu</td>
    <td>$lcpu</td>
    <td>$aep</td>
    <td>$mep</td>
    <td>$lep</td>
    <td>$aMem</td>
    <td>$mMem</td>
    <td>$lMem</td>
    <td>$memf</td>
    <td>$mepf</td>
  </tr>
EOM
        $bg = $bg eq '1' ? '2' : '1';
    }
    print "</table></div>\n";
}

sub showStats {
    my $FORM   = shift;
    my $period = $FORM->{'timeframe'};
    printHeader( $FORM->{'message'}, 'stats', $period );
    my $st = $FORM->{'st'};
    my @params = ( '/usr/sbin/lveinfo', '--csv', "--period=$period" );
    if ( $st eq 'order-by' ) {
        push @params, "--order-by=$FORM->{'order-by'}", "--limit=$FORM->{'limit'}";
    }
    elsif ( $st eq 'by-usage' ) {
        push @params, "--by-usage=$FORM->{'by-usage'}", "--percentage=$FORM->{'percentage'}";
    }
    elsif ( $st eq 'by-fault' ) {
        push @params, "--by-fault=$FORM->{'by-fault'}", "--threshold=$FORM->{'threshold'}";
    }
    else {
        push @params, "--id=$FORM->{'lveid'}";
    }
    my $INPUT   = Cpanel::SafeRun::Errors::saferunallerrors(@params);
    my @results = split( /\n+/, $INPUT );
    my $bg      = 2;
    shift @results;
    print <<"EOM";
	<table id="lveps" class="sortable" width="60%" cellspacing="1" cellpadding="0" border="0">
    <tr>
    <th>LVE Id</th>
    <th>User</th>
    <th>Domain</th>
    <th>aCPU</th>
    <th>mCpu</th>
    <th>lCPU</th>
    <th>aEP</th>
    <th>mEP</th>
    <th>lEP</th>
    <th>aMem</th>
    <th>mMem</th>
    <th>lMem</th>
    <th>MemF</th>
    <th>MepF</th>
    </tr>
EOM

    foreach my $i (@results) {

        # ID,aCPU,mCPU,lCPU,aEP,mEP,lEP,aMem,mMem,lMem,MemF,MepF
        my ( $lveid, $acpu, $mcpu, $lcpu, $aep, $mep, $lep, $aMem, $mMem, $lMem, $memf, $mepf ) = split ',', $i;
        $aMem = RoundMemB($aMem);
        $mMem = RoundMemB($mMem);
        $lMem = RoundMemB($lMem);
        my ( $name, $domain ) = getUserDomain($lveid);
        print "<tr class=\"tdshade${bg}\"><td>";
        print lveIdLink( $lveid, $period );
        print "</td>";
        print <<"EOM";
    <td>$name</td>
    <td>$domain</td>
    <td>$acpu</td>
    <td>$mcpu</td>
    <td>$lcpu</td>
    <td>$aep</td>
    <td>$mep</td>
    <td>$lep</td>
    <td>$aMem</td>
    <td>$mMem</td>
    <td>$lMem</td>
    <td>$memf</td>
    <td>$mepf</td>
  </tr>
EOM
        $bg = $bg eq '1' ? '2' : '1';
    }
    print "</table></div>\n";
}

# Function converts kilobytes to megabytes or gigabytes (if needed)
# and appends appropriate suffix (K, M, G). Rounds down and returns integer value of memory.
# Parameter $_[1] = memory in kilobytes
sub RoundMemInt {
    my $mem = shift;

    if ( ( $mem % ( 1024 * 1024 ) ) == 0 ) {
        $mem >>= 20;
        return "$mem" . 'G';
    }

    if ( ( $mem % 1024 ) == 0 ) {
        $mem >>= 10;
        return "$mem" . 'M';
    }

    return "$mem" . 'K';
}

# Function converts kilobytes to megabytes or gigabytes (if needed)
# and appends appropriate suffix (K, M, G)
# Parameter $_[1] = memory in kilobytes
sub RoundMemK {
    my $mem = shift;

    if ( $mem >= ( 1024 * 1024 ) ) {
        return sprintf( "%.1fG", $mem / ( 1024 * 1024 ) );
    }

    if ( $mem >= 1024 ) {
        return sprintf( "%.1fM", $mem / 1024 );
    }

    return "$mem" . 'K';
}

# Function converts bytes to kilobytes, megabytes or gigabytes (if needed)
# and appends appropriate suffix (K, M, G)
# Parameter $_[1] = memory in bytes
sub RoundMemB {
    my $mem = shift;

    if ( $mem >= ( 1024 * 1024 * 1024 ) ) {
        return sprintf( "%.1fG", $mem / ( 1024 * 1024 * 1024 ) );
    }

    if ( $mem >= 1024 * 1024 ) {
        return sprintf( "%.1fM", $mem / ( 1024 * 1024 ) );
    }

    if ( $mem >= 1024 ) {
        return sprintf( "%.0fK", $mem / 1024 );
    }

    return "$mem";
}

# $_[1] = message
sub showLVEUsage {
    printHeader( shift, 'usage' );

    print <<"EOM";
	<table id="lveps" class="sortable" width="60%" cellspacing="1" cellpadding="0" border="0">
          <tr>
             <th>LVE Id</th>
             <th>User</th>
	     <th>Domain</th>
	     <th>Concurrent Connections</th>
	     <th>Processes</th>
             <th>Threads</th>
             <th>CPU %</th>
             <th>Memory</th>
         </tr>
EOM

    my $INPUT = Cpanel::SafeRun::Errors::saferunallerrors( '/usr/sbin/lveps', '-d', '-n', '-c', '1' );
    my @results = split( /\n+/, $INPUT );
    shift @results;
    my $bg = "2";

    foreach my $i (@results) {
        my ( $lveid, $ref, $pno, $tno, $cpu, $mem, $io ) = split ' ', $i;
        my $name   = getpwuid($lveid);
        my $domain = '';
        if ( $name ne "" && -e "/var/cpanel/users/$name" ) {
            open FILE, "/var/cpanel/users/$name";
            while (<FILE>) {
                if (/^DNS=(.*)/) { $domain = $1; last; }
            }
            close FILE;
        }

        my $rmem = RoundMemK($mem);

        print "<tr class=\"tdshade${bg}\"><td>", lveIdLink( $lveid, 'today' ), "</td>";
        print <<"EOM";
    <td>$name</td>
    <td>$domain</td>
    <td>$ref</td>
    <td>$pno</td>
    <td>$tno</td>
    <td>$cpu</td>
    <td>$rmem</td>
  </tr>
EOM

        $bg = $bg eq '1' ? '2' : '1';
    }
    print "</table></div>\n";

}

sub trim {
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}

# 4:LVE   EP      lCPU    lIO     CPU     MEM     IO      lMEM    lEP     nCPU    fMEM    fEP
# 0       0       25      25      0       0       0       262144  20      1       0       0

sub parseLVE {
    my $file = '/proc/lve/list';
    my $line;
    my %lves;
    my @values;

    open( my $file_handle, '<', $file ) or die( "\n" . 'Error opening file ' . $file . " $!\n" );

    # Skip first line (header)
    $line = <$file_handle>;

    while ( defined( $line = <$file_handle> ) ) {
        @values = split( /\s+/, $line );
        my %hash = ( cpu => $values[2], mep => $values[8], mem => $values[7], ncpu => $values[9] );
        if ( $values[0] == 0 ) {
            $lves{'default'} = \%hash;
        }
        else {
            my $lveid = $values[0];
            $lves{$lveid} = \%hash;
        }
    }

    close($file_handle);

    return \%lves;
}

__END__

use strict;
use XML::LibXML;

sub parseLVEValues {
  my $lve = shift;

  my @cpu_node = $lve->getElementsByTagName('cpu');
  my $cpu = trim @cpu_node[0]->getAttribute('limit');

  my @mem_node = $lve->getElementsByTagName('mem');
  my $mem = trim @mem_node[0]->getAttribute('limit');

  my @ncpu_node = $lve->getElementsByTagName('ncpu');
  my $ncpu = trim @ncpu_node[0]->getAttribute('limit');

  my @mep_node = $lve->getElementsByTagName('other');
  my $mep = trim @mep_node[0]->getAttribute('maxentryprocs');

  my %val = ( cpu => $cpu, mep => $mep, mem => $mem, ncpu => $ncpu );
  return \%val;
}

sub parseLVE {
  my $parser = XML::LibXML->new();
  my $tree = $parser->parse_file('/etc/container/ve.cfg');
  my $root = $tree->getDocumentElement;
  my %lves;
  my @default = $root->getElementsByTagName('defaults');
  $lves{'default'} = parseLVEValues $default[0];
  my @lve_nodes = $root->getElementsByTagName('lve');
  foreach my $lve (@lve_nodes) {
    my $lve_id = trim $lve->getAttribute('id');
    $lves{$lve_id} = parseLVEValues $lve;
  }
  return \%lves;
}

Zerion Mini Shell 1.0