OpenVZ.pm 25.1 KB
Newer Older
1 2 3
package PVE::OpenVZ;

use strict;
4 5 6
use LockFile::Simple;
use File::stat qw();
use POSIX qw (LONG_MAX);
7 8
use IO::Dir;
use IO::File;
9 10 11 12 13 14
use PVE::Tools qw(extract_param);
use PVE::ProcFSTools;
use PVE::Cluster qw(cfs_register_file cfs_read_file);
use PVE::SafeSyslog;
use PVE::INotify;
use PVE::JSONSchema;
15

16 17
my $cpuinfo = PVE::ProcFSTools::read_cpuinfo();
my $nodename = PVE::INotify::nodename();
18

19 20 21 22 23
sub config_list {
    my $vmlist = PVE::Cluster::get_vmlist();
    my $res = {};
    return $res if !$vmlist || !$vmlist->{ids};
    my $ids = $vmlist->{ids};
24

25 26 27 28 29 30 31 32 33
    foreach my $vmid (keys %$ids) {
	next if !$vmid; # skip VE0
	my $d = $ids->{$vmid};
	next if !$d->{node} || $d->{node} ne $nodename;
	next if !$d->{type} || $d->{type} ne 'openvz';
	$res->{$vmid}->{type} = 'openvz';
    }
    return $res;
}
34

35 36
sub cfs_config_path {
    my ($vmid, $node) = @_;
37

38 39 40
    $node = $nodename if !$node;
    return "nodes/$node/openvz/$vmid.conf";
}
41

42 43 44 45 46 47
sub config_file {
    my ($vmid, $node) = @_;

    my $cfspath = cfs_config_path($vmid, $node);
    return "/etc/pve/$cfspath";
}
48 49 50 51

sub load_config {
    my ($vmid) = @_;

52
    my $cfspath = cfs_config_path($vmid);
53

54 55
    my $conf = PVE::Cluster::cfs_read_file($cfspath);
    die "container $vmid does not exists\n" if !defined($conf);
56

57
    return $conf;
58 59
}

60
my $last_proc_vestat = {};
61

62
sub vmstatus {
63
    my ($opt_vmid) = @_;
64

65
    my $list = config_list();
66

67
    foreach my $vmid (keys %$list) {
68 69
	next if $opt_vmid && ($vmid ne $opt_vmid);

70 71
	my $d = $list->{$vmid};
	$d->{status} = 'stopped';
72

73 74 75 76
	my $cfspath = cfs_config_path($vmid);
	if (my $conf = PVE::Cluster::cfs_read_file($cfspath)) {
	    $d->{name} = $conf->{hostname}->{value} || "VM$vmid";
	    $d->{name} =~ s/[\s]//g;
77

78
	    $d->{cpus} = $conf->{cpus}->{value} || 1;
79

80 81
	    $d->{disk} = 0;
	    $d->{maxdisk} = int($conf->{diskspace}->{bar} * 1024);
82

83 84 85
	    $d->{mem} = 0;
	    $d->{maxmem} = int((($conf->{physpages}->{lim} + $conf->{swappages}->{lim})* 4096));
	    $d->{nproc} = 0;
86

87 88 89 90 91 92 93 94 95
	    $d->{uptime} = 0;
	    $d->{pctcpu} = 0;
	    $d->{relcpu} = 0;

	    if (my $ip = $conf->{ip_address}->{value}) {
		$ip =~ s/,;/ /g;
		$d->{ip} = (split(/\s+/, $ip))[0];
	    } else {
		$d->{ip} = '-';
96 97 98 99
	    }
	}
    }

100
    if (my $fh = IO::File->new ("/proc/mounts", "r")) {
101 102
	while (defined (my $line = <$fh>)) {
	    if ($line =~ m|^/var/lib/vz/private/(\d+)\s+/var/lib/vz/root/|) {
103
		$list->{$1}->{status} = 'mounted' if defined($list->{$1});
104 105
	    }
	}
106
	close($fh);
107 108
    }

109 110
    if (my $fh = IO::File->new ("/proc/user_beancounters", "r")) {
	my $vmid;
111 112
	while (defined (my $line = <$fh>)) {
	    if ($line =~ m|\s*((\d+):\s*)?([a-z]+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$|) {
113 114
		$vmid = $2 if defined($2);
		next if !$vmid;
115
		my ($name, $held, $maxheld, $bar, $lim, $failcnt) = ($3, $4, $5, $6, $7, $8);
116 117 118 119 120
		if (my $d = $list->{$vmid}) {
		    if ($name eq 'physpages') {
			$d->{mem} += int($held * 4096);
		    } elsif ($name eq 'swappages') {
			$d->{mem} += int($held * 4096);
121 122 123 124 125 126
		    } elsif ($name eq 'numproc') {
			$d->{nproc} = $held;
		    }
		}
	    }
	}
127
	close($fh);
128 129
    }

130
    if (my $fh = IO::File->new ("/proc/vz/vzquota", "r")) {
131 132
	while (defined (my $line = <$fh>)) {
	    if ($line =~ m|^(\d+):\s+/var/lib/vz/private/\d+$|) {
133
		if (my $d = $list->{$1}) {
134 135
		    $line = <$fh>;
		    if ($line =~ m|^\s*1k-blocks\s+(\d+)\s+(\d+)\s|) {
136 137
			$d->{disk} = int ($1 * 1024);
			$d->{maxdisk} = int ($2 * 1024);
138 139 140 141
		    }
		}
	    }
	}
142
	close($fh);
143 144 145
    }

    my $cpus = $cpuinfo->{cpus} || 1;
146 147
    # Note: OpenVZ does not use POSIX::_SC_CLK_TCK
    my $hz = 1000;
148 149

    # see http://wiki.openvz.org/Vestat
150
    if (my $fh = new IO::File ("/proc/vz/vestat", "r")) {
151 152
	while (defined (my $line = <$fh>)) {
	    if ($line =~ m/^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+/) {
153
		my $vmid = $1;
154 155 156 157 158 159 160
		my $user = $2;
		my $nice = $3;
		my $system = $4;
		my $ut = $5;
		my $sum = $8*$cpus; # uptime in jiffies * cpus = available jiffies
		my $used = $9; # used time in jiffies

161
		my $uptime = int ($ut / $hz);
162

163
		my $d = $list->{$vmid};
164 165 166 167 168
		next if !$d;

		$d->{status} = 'running';
		$d->{uptime} = $uptime;

169 170 171
		if (!defined ($last_proc_vestat->{$vmid}) ||
		    ($last_proc_vestat->{$vmid}->{sum} > $sum)) {
		    $last_proc_vestat->{$vmid} = { used => 0, sum => 0, pctcpu => 0, relcpu => 0};
172 173
		}

174
		my $diff = $sum - $last_proc_vestat->{$vmid}->{sum};
175 176

		if ($diff > 1000) { # don't update too often
177
		    my $useddiff = $used - $last_proc_vestat->{$vmid}->{used};
178
		    my $pctcpu = int ($useddiff*100/$diff);
179 180 181
		    $last_proc_vestat->{$vmid}->{sum} = $sum;
		    $last_proc_vestat->{$vmid}->{used} = $used;
		    $last_proc_vestat->{$vmid}->{pctcpu} = $d->{pctcpu} = $pctcpu;
182 183

		    my $relcpu = $pctcpu;
184
		    $last_proc_vestat->{$vmid}->{relcpu} = $d->{relcpu} = $relcpu;
185 186

		} else {
187 188
		    $d->{pctcpu} = $last_proc_vestat->{$vmid}->{pctcpu};
		    $d->{relcpu} = $last_proc_vestat->{$vmid}->{relcpu};
189 190 191
		}
	    }
	}
192 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
	close($fh);
    }

    return $list;

}

my $confdesc = {
    onboot => {
	optional => 1,
	type => 'boolean',
	description => "Specifies whether a VM will be started during system bootup.",
	default => 0,
    },
    cpus => {
	optional => 1,
	type => 'integer',
	description => "The number of CPUs for this container.",
	minimum => 1,
	default => 1,
    },
    cpuunits => {
	optional => 1,
	type => 'integer',
	description => "CPU weight for a VM. Argument is used in the kernel fair scheduler. The larger the number is, the more CPU time this VM gets. Number is relative to weights of all the other running VMs.\n\nNOTE: You can disable fair-scheduler configuration by setting this to 0.",
	minimum => 0,
	maximum => 500000,
	default => 1000,
    },
    memory => {
	optional => 1,
	type => 'integer',
	description => "Amount of RAM for the VM in MB.",
	minimum => 16,
	default => 512,
    },
    swap => {
	optional => 1,
	type => 'integer',
	description => "Amount of SWAP for the VM in MB.",
	minimum => 16,
	default => 512,
    },
    disk => {
	optional => 1,
	type => 'number',
238 239
	description => "Amount of disk space for the VM in GB. A zero indicates no limits.",
	minimum => 0,
240 241 242 243 244 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
	default => 2,
    },
    quotatime => {
	optional => 1,
	type => 'integer',
	description => "Set quota grace period (seconds).",
	minimum => 0,
	default => 0,
    },
    quotaugidlimit => {
	optional => 1,
	type => 'integer',
	description => "Set maximum number of user/group IDs in a container for which disk quota inside the container will be accounted. If this value is set to 0, user and group quotas inside the container will not.",
	minimum => 0,
	default => 0,
    },
    hostname => {
	optional => 1,
	description => "Set a host name for the container.",
	type => 'string',
	maxLength => 255,
    },
    description => {
	optional => 1,
	type => 'string',
	description => "Container description. Only used on the configuration web interface.",
    },
    searchdomain => {
	optional => 1,
	type => 'string',
270
	description => "Sets DNS search domains for a container. Create will automatically use the setting from the host if you neither set searchdomain or nameserver.",
271 272 273 274
    },
    nameserver => {
	optional => 1,
	type => 'string',
275
	description => "Sets DNS server IP address for a container. Create will automatically use the setting from the host if you neither set searchdomain or nameserver.",
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    },
    ip_address => {
	optional => 1,
	type => 'string',
	description => "Specifies the address the container will be assigned.",
    },
    netif => {
	optional => 1,
	type => 'string', format => 'pve-openvz-netif',
	description => "Specifies network interfaces for the container.",
    },
};

# add JSON properties for create and set function
sub json_config_properties {
    my $prop = shift;

    foreach my $opt (keys %$confdesc) {
	$prop->{$opt} = $confdesc->{$opt};
    }

    return $prop;
}

# read global vz.conf
my $read_global_vz_config  = sub {

    my $res = {
	rootdir => '/var/lib/vz/root/$VEID', # note '$VEID' is a place holder
	privatedir => '/var/lib/vz/private/$VEID', # note '$VEID' is a place holder
306
	dumpdir => '/var/lib/vz/dump',
307 308 309
	lockdir => '/var/lib/vz/lock',
    };
    
310 311 312 313 314
    my $filename = "/etc/vz/vz.conf";

    return $res if ! -f $filename;

    my $data = PVE::Tools::file_get_contents($filename);
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

    if ($data =~ m/^\s*VE_PRIVATE=(.*)$/m) {
	my $dir = $1;
	$dir =~ s/^\"(.*)\"/$1/;
	if ($dir !~ m/\$VEID/) {
	    warn "VE_PRIVATE does not contain '\$VEID' ('$dir')\n";
	} else {
	    $res->{privatedir} = $dir;
	}
    }
    if ($data =~ m/^\s*VE_ROOT=(.*)$/m) {
	my $dir = $1;
	$dir =~ s/^\"(.*)\"/$1/;
	if ($dir !~ m/\$VEID/) {
	    warn "VE_ROOT does not contain '\$VEID' ('$dir')\n";
	} else {
	    $res->{rootdir} = $dir;
	}
    }
    if ($data =~ m/^\s*DUMPDIR=(.*)$/m) {
	my $dir = $1;
	$dir =~ s/^\"(.*)\"/$1/;
	$dir =~ s|/\$VEID$||;
	$res->{dumpdir} = $dir;
    }
    if ($data =~ m/^\s*LOCKDIR=(.*)$/m) {
	my $dir = $1;
	$dir =~ s/^\"(.*)\"/$1/;
	$res->{lockdir} = $dir;
344 345 346
    }

    return $res;
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 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 514 515 516 517 518 519 520 521 522 523 524 525 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
};

my $global_vzconf =  &$read_global_vz_config();
my $res_unlimited = LONG_MAX;

sub parse_netif {
    my ($data) = @_;

    my $res = {};
    return $res if !$data;

    foreach my $iface (split (/;/, $data)) {
	my $d = {};
	foreach my $pv (split (/,/, $iface)) {
	    if ($pv =~ m/^(ifname|mac|bridge|host_ifname|host_mac)=(.+)$/) {
		$d->{$1} = $2;
	    }
	}
	if ($d->{ifname}) {
	    $d->{raw} = $data;
	    $res->{$d->{ifname}} = $d;
	} else {
	    return undef;
	}
    }

    return $res;
}

PVE::JSONSchema::register_format('pve-openvz-netif', \&verify_netif);
sub verify_netif {
    my ($value, $noerr) = @_;

    return $value if parse_netif($value);

    return undef if $noerr;

    die "unable to parse --netif value";
}

sub parse_res_num_ignore {
    my ($key, $text) = @_;

    if ($text =~ m/^(\d+|unlimited)(:.*)?$/) {
	return { bar => $1 eq 'unlimited' ? $res_unlimited : $1 };
    }

    return undef;
}

sub parse_res_num_num {
    my ($key, $text) = @_;

    if ($text =~ m/^(\d+|unlimited)(:(\d+|unlimited))?$/) {
	my $res = { bar => $1 eq 'unlimited' ? $res_unlimited : $1 };
	if (defined($3)) {
	    $res->{lim} = $3 eq 'unlimited' ? $res_unlimited : $3;
	} else {
	    $res->{lim} = $res->{bar};
	}
	return $res;
    }

    return undef;
}

sub parse_res_bar_limit {
    my ($text, $base) = @_;

    return $res_unlimited if $text eq 'unlimited';

    if ($text =~ m/^(\d+)([TGMKP])?$/i) {
	my $val = $1;
	my $mult = lc($2);
	if ($mult eq 'k') {
	    $val = $val * 1024;
	} elsif ($mult eq 'm') {
	    $val = $val * 1024 * 1024;
	} elsif ($mult eq 'g') {
	    $val = $val * 1024 * 1024 * 1024;
	} elsif ($mult eq 't') {
	    $val = $val * 1024 * 1024 * 1024 * 1024;
	} elsif ($mult eq 'p') {
	    $val = $val * 4096;
	} else {
	    return $val;
	}
	return int($val/$base);
    }

    return undef;
}

sub parse_res_bytes_bytes {
    my ($key, $text) = @_;

    my @a = split(/:/, $text);
    $a[1] = $a[0] if !defined($a[1]);
    
    my $bar = parse_res_bar_limit($a[0], 1);
    my $lim = parse_res_bar_limit($a[1], 1);

    if (defined($bar) && defined($lim)) {
	return { bar => $bar, lim => $lim };
    }

    return undef;
}

sub parse_res_block_block {
    my ($key, $text) = @_;

    my @a = split(/:/, $text);
    $a[1] = $a[0] if !defined($a[1]);
    
    my $bar = parse_res_bar_limit($a[0], 1024);
    my $lim = parse_res_bar_limit($a[1], 1024);

    if (defined($bar) && defined($lim)) {
	return { bar => $bar, lim => $lim };
    }

    return undef;
}

sub parse_res_pages_pages {
    my ($key, $text) = @_;

    my @a = split(/:/, $text);
    $a[1] = $a[0] if !defined($a[1]);
    
    my $bar = parse_res_bar_limit($a[0], 4096);
    my $lim = parse_res_bar_limit($a[1], 4096);

    if (defined($bar) && defined($lim)) {
	return { bar => $bar, lim => $lim };
    }

    return undef;
}

sub parse_res_pages_unlimited {
    my ($key, $text) = @_;

    my @a = split(/:/, $text);
    
    my $bar = parse_res_bar_limit($a[0], 4096);
 
    if (defined($bar)) {
	return { bar => $bar, lim => $res_unlimited };
    }

    return undef;
}

sub parse_res_pages_ignore {
    my ($key, $text) = @_;

    my @a = split(/:/, $text);
    
    my $bar = parse_res_bar_limit($a[0], 4096);
 
    if (defined($bar)) {
	return { bar => $bar };
    }

    return undef;
}

sub parse_res_ignore_pages {
    my ($key, $text) = @_;

    my @a = split(/:/, $text);
    $a[1] = $a[0] if !defined($a[1]);
    
    my $lim = parse_res_bar_limit($a[1] , 4096);
 
    if (defined($lim)) {
	return { bar => 0, lim => $lim };
    }

    return undef;
}

sub parse_boolean {
    my ($key, $text) = @_;

    return { value => "yes" } if $text =~ m/^(yes|true|on|1)$/i;
    return { value => "no" } if $text =~ m/^(no|false|off|0)$/i;

    return undef;
};

sub parse_integer {
    my ($key, $text) = @_;

    if ($text =~ m/^(\d+)$/) {
	return { value => int($1) };
    }

    return undef;
};

my $ovz_ressources = {
    numproc => \&parse_res_num_ignore,
    numtcpsock => \&parse_res_num_ignore,
    numothersock => \&parse_res_num_ignore,
    numfile => \&parse_res_num_ignore,    
    numflock => \&parse_res_num_num,
    numpty => \&parse_res_num_ignore,
    numsiginfo => \&parse_res_num_ignore,
    numiptent => \&parse_res_num_ignore,

    vmguarpages => \&parse_res_pages_unlimited,
    oomguarpages => \&parse_res_pages_unlimited,
    lockedpages => \&parse_res_pages_ignore,
    privvmpages => \&parse_res_pages_pages,
    shmpages => \&parse_res_pages_ignore,
    physpages => \&parse_res_pages_pages,
    swappages => \&parse_res_ignore_pages,

    kmemsize => \&parse_res_bytes_bytes,
    tcpsndbuf => \&parse_res_bytes_bytes,
    tcprcvbuf => \&parse_res_bytes_bytes,
    othersockbuf => \&parse_res_bytes_bytes,
    dgramrcvbuf => \&parse_res_bytes_bytes,
    dcachesize => \&parse_res_bytes_bytes,

    diskquota => \&parse_boolean,
    diskspace => \&parse_res_block_block,
    diskinodes => \&parse_res_num_num,
    quotatime => \&parse_integer,
    quotaugidlimit => \&parse_integer,

    cpuunits => \&parse_integer,
    cpulimit => \&parse_integer,
    cpus => \&parse_integer,
    cpumask => 'string',
    meminfo => 'string',
    iptables => 'string',

    ip_address => 'string',
    netif => 'string',
    hostname => 'string',
    nameserver => 'string',
    searchdomain => 'string',

    name => 'string',
    description => 'string',
    onboot => \&parse_boolean,
    initlog => \&parse_boolean,
    bootorder => \&parse_integer,
    ostemplate => 'string',
    ve_root => 'string',
    ve_private => 'string',
    disabled => \&parse_boolean,
    origin_sample => 'string',
    noatime => \&parse_boolean,
    capability => 'string',
    devnodes => 'string',
    devices => 'string',
    pci => 'string',
    features => 'string',
    ioprio => \&parse_integer,

};

sub parse_ovz_config {
    my ($filename, $raw) = @_;

    return undef if !defined($raw);

    my $data = {
	digest => Digest::SHA1::sha1_hex($raw),
    };

    $filename =~ m|/openvz/(\d+)\.conf$|
	|| die "got strange filename '$filename'";

    my $vmid = $1;

    while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
	my $line = $1;

	next if $line =~ m/^\#/;
	next if $line =~ m/^\s*$/;

	if ($line =~ m/^\s*([A-Z][A-Z0-9_]*)\s*=\s*\"(.*)\"\s*$/i) {
	    my $name = lc($1);
	    my $text = $2;

	    my $parser = $ovz_ressources->{$name};
	    if (!$parser || !ref($parser)) {
		$data->{$name}->{value} = $text;
		next;
	    } else {
		if (my $res = &$parser($name, $text)) {
		    $data->{$name} = $res;
		    next;
		}
	    }
	}
	die "unable to parse config line: $line\n";
    }

    return $data;
}

cfs_register_file('/openvz/', \&parse_ovz_config);

sub format_res_value {
    my ($key, $value) = @_;

    return 'unlimited' if $value == $res_unlimited;

    return 0 if $value == 0;

    if ($key =~ m/pages$/) {
        my $bytes = $value * 4096;
	my $mb = int ($bytes / (1024 * 1024));
	return "${mb}M" if $mb * 1024 * 1024 == $bytes;
    } elsif ($key =~ m/space$/) {
        my $bytes = $value * 1024;
	my $gb = int ($bytes / (1024 * 1024 * 1024));
	return "${gb}G" if $gb * 1024 * 1024 * 1024 == $bytes;
	my $mb = int ($bytes / (1024 * 1024));
	return "${mb}M" if $mb * 1024 * 1024 == $bytes;
    } elsif ($key =~ m/size$/) {
        my $bytes = $value;
	my $mb = int ($bytes / (1024 * 1024));
	return "${mb}M" if $mb * 1024 * 1024 == $bytes;
    }
679

680
    return $value;
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

sub format_res_bar_lim {
    my ($key, $data) = @_;

    if (defined($data->{lim}) && ($data->{lim} ne $data->{bar})) {
	return format_res_value($key, $data->{bar}) . ":" . format_res_value($key, $data->{lim});     
    } else {
	return format_res_value($key, $data->{bar}); 
    }
}

sub create_config_line {
    my ($key, $data) = @_;

    my $text;

    if (defined($data->{value})) {
	$text .= uc($key) . "=\"$data->{value}\"\n";
    } elsif (defined($data->{bar})) {
	my $tmp = format_res_bar_lim($key, $data);
	$text .=  uc($key) . "=\"$tmp\"\n";     
    }
}

sub update_ovz_config {
    my ($veconf, $param) = @_;

    my $changes = [];

    # test if barrier or limit changed
    my $push_bl_changes = sub {
	my ($name, $bar, $lim) = @_;

	my $old = format_res_bar_lim($name, $veconf->{$name});
	my $new = format_res_bar_lim($name, { bar => $bar, lim => $lim });
	if ($old ne $new) {
	    $veconf->{$name}->{bar} = $bar; 
	    $veconf->{$name}->{lim} = $lim;
	    push @$changes, "--$name", $new;
	}
    };

724 725 726 727
    my $mem = $veconf->{physpages}->{lim} ? 
	int (($veconf->{physpages}->{lim} * 4) / 1024) : 512;
    my $swap = $veconf->{swappages}->{lim} ?
	int (($veconf->{swappages}->{lim} * 4) / 1024) : 0;
728
 
729
    my $disk = ($veconf->{diskspace}->{bar} || $res_unlimited) / (1024*1024);
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 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
    my $cpuunits = $veconf->{cpuunits}->{value} || 1000;
    my $quotatime = $veconf->{quotatime}->{value} || 0;
    my $quotaugidlimit = $veconf->{quotaugidlimit}->{value} || 0;
    my $cpus = $veconf->{cpus}->{value} || 1;

    if ($param->{memory}) {
	$mem = $param->{memory};
    }

    if (defined ($param->{swap})) {
	$swap = $param->{swap};
    }

    if ($param->{disk}) {
	$disk = $param->{disk};
    }

    if ($param->{cpuunits}) {
	$cpuunits = $param->{cpuunits};
    }

    if (defined($param->{quotatime})) {
	$quotatime = $param->{quotatime};
    }

    if (defined($param->{quotaugidlimit})) {
	$quotaugidlimit = $param->{quotaugidlimit};
    }

    if ($param->{cpus}) {
	$cpus = $param->{cpus};
    }

    # memory related parameter 

    &$push_bl_changes('vmguarpages', 0, $res_unlimited);
    &$push_bl_changes('oomguarpages', 0, $res_unlimited);
    &$push_bl_changes('privvmpages', $res_unlimited, $res_unlimited);

    # lock half of $mem
    my $lockedpages = int($mem*1024/8);
    &$push_bl_changes('lockedpages', $lockedpages, undef);

    my $kmemsize = int($mem/2);
    &$push_bl_changes('kmemsize', int($kmemsize/1.1)*1024*1024, $kmemsize*1024*1024);

    my $dcachesize = int($mem/4);
    &$push_bl_changes('dcachesize', int($dcachesize/1.1)*1024*1024, $dcachesize*1024*1024);

    my $physpages = int($mem*1024/4);
    &$push_bl_changes('physpages', 0, $physpages);

    my $swappages = int($swap*1024/4);
    &$push_bl_changes('swappages', 0, $swappages);


    # disk quota parameters
787
    if (!$disk || ($disk * 1.1) >= ($res_unlimited / (1024 * 1024))) {
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 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 846 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 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
	&$push_bl_changes('diskspace', $res_unlimited, $res_unlimited);
	&$push_bl_changes('diskinodes', $res_unlimited, $res_unlimited);
    } else {
	my $diskspace = int ($disk * 1024 * 1024);
	my $diskspace_lim = int ($diskspace * 1.1);
	&$push_bl_changes('diskspace', $diskspace, $diskspace_lim);
	my $diskinodes = int ($disk * 200000);
	my $diskinodes_lim = int ($disk * 220000);
	&$push_bl_changes('diskinodes', $diskinodes, $diskinodes_lim);
    }
    if ($veconf->{'quotatime'}->{value} != $quotatime) {
	$veconf->{'quotatime'}->{value} = $quotatime;
	push @$changes, '--quotatime', "$quotatime";
    }

    if ($veconf->{'quotaugidlimit'}->{value} != $quotaugidlimit) {
	$veconf->{'quotaugidlimit'}->{value} = $quotaugidlimit;
	push @$changes, '--quotaugidlimit', "$quotaugidlimit";
    }

    # cpu settings

    if ($veconf->{'cpuunits'}->{value} != $cpuunits) {
	$veconf->{'cpuunits'}->{value} = $cpuunits;
	push @$changes, '--cpuunits', "$cpuunits";
    }

    if ($veconf->{'cpus'}->{value} != $cpus) {
	$veconf->{'cpus'}->{value} = $cpus;
	push @$changes, '--cpus', "$cpus";
    }

    my $cond_set_boolean = sub {
	my ($name) = @_;

	return if !defined($param->{$name});

	my $newvalue = $param->{$name} ? 'yes' : 'no';
	my $oldvalue = $veconf->{$name}->{value};
	if (!defined($oldvalue) || ($oldvalue ne $newvalue)) {
	    $veconf->{$name}->{value} = $newvalue;
	    push @$changes, "--$name", $newvalue;
	}
    };

    my $cond_set_value = sub {
	my ($name, $newvalue) = @_;

	$newvalue = defined($newvalue) ? $newvalue : $param->{$name};
	return if !defined($newvalue);

	my $oldvalue = $veconf->{$name}->{value};
	if (!defined($oldvalue) || ($oldvalue ne $newvalue)) {
	    $veconf->{$name}->{value} = $newvalue;
	    push @$changes, "--$name", $newvalue;
	}
    };

    &$cond_set_boolean('onboot');
    
    &$cond_set_value('hostname');
 
    &$cond_set_value('searchdomain');

    if ($param->{'description'}) {
	&$cond_set_value('description', PVE::Tools::encode_text($param->{'description'}));
    }

    if (defined($param->{ip_address})) {
	my $iphash = {};
	if (defined($veconf->{'ip_address'}) && $veconf->{'ip_address'}->{value}) {
	    foreach my $ip (split (/\s+/, $veconf->{ip_address}->{value})) {
		$iphash->{$ip} = 1;
	    }
	}
	my $newhash = {};
	foreach my $ip (PVE::Tools::split_list($param->{'ip_address'})) {
	    next if $ip !~ m|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(/\d+)?$|;
	    $newhash->{$ip} = 1;
	    if (!$iphash->{$ip}) {
		push @$changes, '--ipadd', $ip;
		$iphash->{$ip} = 1; # only add once
	    }
	}
	foreach my $ip (keys %$iphash) {
	    if (!$newhash->{$ip}) {
		push @$changes, '--ipdel', $ip;
	    }
	}
	$veconf->{'ip_address'}->{value} = join(' ', keys %$iphash);
    }

    if (defined($param->{netif})) {
	my $ifaces = {};
	if (defined ($veconf->{netif}) && $veconf->{netif}->{value}) {
	    $ifaces = parse_netif($veconf->{netif}->{value});
	}
	my $newif = parse_netif($param->{netif});

	foreach my $ifname (sort keys %$ifaces) {
	    if (!$newif->{$ifname}) {
		push @$changes, '--netif_del', $ifname;
	    }
	}

	my $newvalue = '';
	foreach my $ifname (sort keys %$newif) {
	    $newvalue .= ';' if $newvalue;
	    $newvalue .= $ifname;
	    $newvalue .= $newif->{$ifname}->{mac} ? ",$newif->{$ifname}->{mac}" : ',';
	    $newvalue .= $newif->{$ifname}->{host_ifname} ? ",$newif->{$ifname}->{host_ifname}" : ',';
	    $newvalue .= $newif->{$ifname}->{host_mac} ? ",$newif->{$ifname}->{host_mac}" : ',';
	    $newvalue .= $newif->{$ifname}->{bridge} ? ",$newif->{$ifname}->{bridge}" : '';

	    if (!$ifaces->{$ifname} || ($ifaces->{$ifname}->{raw} ne $newif->{$ifname}->{raw})) {
		push @$changes, '--netif_add', $newvalue;
	    }
	}
	$veconf->{netif}->{value} = $newvalue;
    }

    if (defined($param->{'nameserver'})) {
	my $nshash = {};
	foreach my $ns (PVE::Tools::split_list($param->{'nameserver'})) {
	    if (!$nshash->{$ns}) {
		push @$changes, '--nameserver', $ns;
		$nshash->{$ns} = 1;
	    }
	}
	$veconf->{'nameserver'}->{value} = join(' ', keys %$nshash);
    }

920
    # foreach my $nv (@$changes) { print "CHANGE: $nv\n"; }
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 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 974 975 976 977 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 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049

    return $changes;
}

sub generate_raw_config {
    my ($raw, $conf) = @_;

    my $text = '';

    my $found = {};

    while ($raw && $raw =~ s/^(.*?)(\n|$)//) {
	my $line = $1;

	if ($line =~ m/^\#/ || $line =~ m/^\s*$/) {
	    $text .= "$line\n";
	    next;
	}

	if ($line =~ m/^\s*([A-Z][A-Z0-9_]*)\s*=\s*\"(.*)\"\s*$/i) {
	    my $name = lc($1);
	    if ($conf->{$name}) {
		$found->{$name} = 1;
		if (my $line = create_config_line($name, $conf->{$name})) {
		    $text .= $line;
		}
	    }
	}
    }

    foreach my $key (keys %$conf) {
	next if $found->{$key};
	next if $key eq 'digest';
	if (my $line = create_config_line($key, $conf->{$key})) {
	    $text .= $line;
	}
    }

    return $text;
}

sub lock_container {
    my ($vmid, $code, @param) = @_;

    my $filename = $global_vzconf->{lockdir} . "/${vmid}.lck";
    my $lock;
    my $res;

    eval {

	my $lockmgr = LockFile::Simple->make(-format => '%f',
					     -autoclean => 1,
					     -max => 30, 
					     -delay => 2, 
					     -stale => 1,
					     -nfs => 0);

	$lock = $lockmgr->lock($filename) || die "can't lock container $vmid\n";

        $res = &$code(@param);

    };
    my $err = $@;

    $lock->release() if $lock;

    die $err if $err;

    return $res;
}

sub replacepw {
    my ($file, $epw) = @_;

    my $tmpfile = "$file.$$";

    eval  {
	open (SRC, "<$file") ||
	    die "unable to open file '$file' - $!";

	my $st = File::stat::stat(\*SRC) ||
	    die "unable to stat file - $!";

	open (DST, ">$tmpfile") ||
	    die "unable to open file '$tmpfile' - $!";

	# copy owner and permissions
	chmod $st->mode, \*DST;
	chown $st->uid, $st->gid, \*DST;
	
	while (defined (my $line = <SRC>)) {
	    $line =~ s/^root:[^:]*:/root:${epw}:/;
	    print DST $line;
	}
    };

    my $err = $@;

    close (SRC);
    close (DST);

    if ($err) {
	unlink $tmpfile;
    } else {
	rename $tmpfile, $file;
	unlink $tmpfile; # in case rename fails
    }	
}

sub set_rootpasswd {
    my ($vmid, $opt_rootpasswd) = @_;

    my $vmdir = $global_vzconf->{privatedir};
    $vmdir =~ s/\$VEID/$vmid/;

    my $pwfile = "$vmdir/etc/passwd";

    return if ! -f $pwfile;

    my $shadow = "$vmdir/etc/shadow";

    if (-f $shadow) {
	replacepw ($shadow, $opt_rootpasswd);
	replacepw ($pwfile, 'x');
    } else {
	replacepw ($pwfile, $opt_rootpasswd);
    }
}