]> git.proxmox.com Git - pve-container.git/blame - src/PVE/LXC/Config.pm
config: whitelist lxc.limit.*
[pve-container.git] / src / PVE / LXC / Config.pm
CommitLineData
67afe46e
FG
1package PVE::LXC::Config;
2
3use strict;
4use warnings;
5
6use PVE::AbstractConfig;
7use PVE::Cluster qw(cfs_register_file);
8use PVE::INotify;
9use PVE::JSONSchema qw(get_standard_option);
10use PVE::Tools;
11
12use base qw(PVE::AbstractConfig);
13
14my $nodename = PVE::INotify::nodename();
15my $lock_handles = {};
16my $lockdir = "/run/lock/lxc";
17mkdir $lockdir;
18mkdir "/etc/pve/nodes/$nodename/lxc";
19my $MAX_MOUNT_POINTS = 10;
20my $MAX_UNUSED_DISKS = $MAX_MOUNT_POINTS;
21
22# BEGIN implemented abstract methods from PVE::AbstractConfig
23
24sub guest_type {
25 return "CT";
26}
27
4518000b
FG
28sub __config_max_unused_disks {
29 my ($class) = @_;
30
31 return $MAX_UNUSED_DISKS;
32}
33
67afe46e
FG
34sub config_file_lock {
35 my ($class, $vmid) = @_;
36
37 return "$lockdir/pve-config-${vmid}.lock";
38}
39
40sub cfs_config_path {
41 my ($class, $vmid, $node) = @_;
42
43 $node = $nodename if !$node;
44 return "nodes/$node/lxc/$vmid.conf";
45}
46
1a8269bc 47sub mountpoint_backup_enabled {
ec7f0f09 48 my ($class, $mp_key, $mountpoint) = @_;
1a8269bc
DM
49
50 return 1 if $mp_key eq 'rootfs';
51
f59c9670
FG
52 return 0 if $mountpoint->{type} ne 'volume';
53
1a8269bc
DM
54 return 1 if $mountpoint->{backup};
55
56 return 0;
57}
58
4518000b
FG
59sub has_feature {
60 my ($class, $feature, $conf, $storecfg, $snapname, $running, $backup_only) = @_;
61 my $err;
62
d250604f 63 $class->foreach_mountpoint($conf, sub {
4518000b
FG
64 my ($ms, $mountpoint) = @_;
65
66 return if $err; # skip further test
ec7f0f09 67 return if $backup_only && !$class->mountpoint_backup_enabled($ms, $mountpoint);
4518000b
FG
68
69 $err = 1
70 if !PVE::Storage::volume_has_feature($storecfg, $feature,
71 $mountpoint->{volume},
72 $snapname, $running);
73 });
74
75 return $err ? 0 : 1;
76}
77
78sub __snapshot_save_vmstate {
79 my ($class, $vmid, $conf, $snapname, $storecfg) = @_;
80 die "implement me - snapshot_save_vmstate\n";
81}
82
83sub __snapshot_check_running {
84 my ($class, $vmid) = @_;
85 return PVE::LXC::check_running($vmid);
86}
87
88sub __snapshot_check_freeze_needed {
89 my ($class, $vmid, $config, $save_vmstate) = @_;
90
91 my $ret = $class->__snapshot_check_running($vmid);
92 return ($ret, $ret);
93}
94
95sub __snapshot_freeze {
96 my ($class, $vmid, $unfreeze) = @_;
97
98 if ($unfreeze) {
99 eval { PVE::Tools::run_command(['/usr/bin/lxc-unfreeze', '-n', $vmid]); };
100 warn $@ if $@;
101 } else {
102 PVE::Tools::run_command(['/usr/bin/lxc-freeze', '-n', $vmid]);
103 PVE::LXC::sync_container_namespace($vmid);
104 }
105}
106
107sub __snapshot_create_vol_snapshot {
108 my ($class, $vmid, $ms, $mountpoint, $snapname) = @_;
109
110 my $storecfg = PVE::Storage::config();
111
1a8269bc 112 return if $snapname eq 'vzdump' &&
ec7f0f09 113 !$class->mountpoint_backup_enabled($ms, $mountpoint);
1a8269bc 114
4518000b
FG
115 PVE::Storage::volume_snapshot($storecfg, $mountpoint->{volume}, $snapname);
116}
117
118sub __snapshot_delete_remove_drive {
119 my ($class, $snap, $remove_drive) = @_;
120
121 if ($remove_drive eq 'vmstate') {
122 die "implement me - saving vmstate\n";
123 } else {
124 my $value = $snap->{$remove_drive};
1b4cf758 125 my $mountpoint = $remove_drive eq 'rootfs' ? $class->parse_ct_rootfs($value, 1) : $class->parse_ct_mountpoint($value, 1);
4518000b 126 delete $snap->{$remove_drive};
d103721f
FG
127
128 $class->add_unused_volume($snap, $mountpoint->{volume})
129 if ($mountpoint->{type} eq 'volume');
4518000b
FG
130 }
131}
132
133sub __snapshot_delete_vmstate_file {
134 my ($class, $snap, $force) = @_;
135
136 die "implement me - saving vmstate\n";
137}
138
139sub __snapshot_delete_vol_snapshot {
a8e9a4ea 140 my ($class, $vmid, $ms, $mountpoint, $snapname, $unused) = @_;
4518000b 141
d103721f
FG
142 return if $snapname eq 'vzdump' &&
143 !$class->mountpoint_backup_enabled($ms, $mountpoint);
144
4518000b
FG
145 my $storecfg = PVE::Storage::config();
146 PVE::Storage::volume_snapshot_delete($storecfg, $mountpoint->{volume}, $snapname);
a8e9a4ea 147 push @$unused, $mountpoint->{volume};
4518000b
FG
148}
149
150sub __snapshot_rollback_vol_possible {
151 my ($class, $mountpoint, $snapname) = @_;
152
153 my $storecfg = PVE::Storage::config();
154 PVE::Storage::volume_rollback_is_possible($storecfg, $mountpoint->{volume}, $snapname);
155}
156
157sub __snapshot_rollback_vol_rollback {
158 my ($class, $mountpoint, $snapname) = @_;
159
160 my $storecfg = PVE::Storage::config();
161 PVE::Storage::volume_snapshot_rollback($storecfg, $mountpoint->{volume}, $snapname);
162}
163
164sub __snapshot_rollback_vm_stop {
165 my ($class, $vmid) = @_;
166
167 PVE::Tools::run_command(['/usr/bin/lxc-stop', '-n', $vmid, '--kill'])
168 if $class->__snapshot_check_running($vmid);
169}
170
171sub __snapshot_rollback_vm_start {
172 my ($class, $vmid, $vmstate, $forcemachine);
173
174 die "implement me - save vmstate\n";
175}
176
a8656869
FG
177sub __snapshot_rollback_get_unused {
178 my ($class, $conf, $snap) = @_;
179
180 my $unused = [];
181
182 $class->__snapshot_foreach_volume($conf, sub {
183 my ($vs, $volume) = @_;
184
185 return if $volume->{type} ne 'volume';
186
187 my $found = 0;
188 my $volid = $volume->{volume};
189
190 $class->__snapshot_foreach_volume($snap, sub {
191 my ($ms, $mountpoint) = @_;
192
193 return if $found;
194 return if ($mountpoint->{type} ne 'volume');
195
196 $found = 1
197 if ($mountpoint->{volume} && $mountpoint->{volume} eq $volid);
198 });
199
200 push @$unused, $volid if !$found;
201 });
202
203 return $unused;
204}
205
4518000b
FG
206sub __snapshot_foreach_volume {
207 my ($class, $conf, $func) = @_;
208
d250604f 209 $class->foreach_mountpoint($conf, $func);
4518000b
FG
210}
211
67afe46e
FG
212# END implemented abstract methods from PVE::AbstractConfig
213
1b4cf758
FG
214# BEGIN JSON config code
215
216cfs_register_file('/lxc/', \&parse_pct_config, \&write_pct_config);
217
218my $rootfs_desc = {
219 volume => {
220 type => 'string',
221 default_key => 1,
222 format => 'pve-lxc-mp-string',
223 format_description => 'volume',
224 description => 'Volume, device or directory to mount into the container.',
225 },
1b4cf758
FG
226 size => {
227 type => 'string',
228 format => 'disk-size',
229 format_description => 'DiskSize',
230 description => 'Volume size (read only value).',
231 optional => 1,
232 },
233 acl => {
234 type => 'boolean',
1b4cf758
FG
235 description => 'Explicitly enable or disable ACL support.',
236 optional => 1,
237 },
238 ro => {
239 type => 'boolean',
235dbdf3 240 description => 'Read-only mount point',
1b4cf758
FG
241 optional => 1,
242 },
243 quota => {
244 type => 'boolean',
1b4cf758
FG
245 description => 'Enable user quotas inside the container (not supported with zfs subvolumes)',
246 optional => 1,
247 },
552e168f
FG
248 shared => {
249 type => 'boolean',
250 description => 'Mark this non-volume mount point as available on multiple nodes (see \'nodes\')',
251 verbose_description => "Mark this non-volume mount point as available on all nodes.\n\nWARNING: This option does not share the mount point automatically, it assumes it is shared already!",
252 optional => 1,
253 default => 0,
254 },
1b4cf758
FG
255};
256
257PVE::JSONSchema::register_standard_option('pve-ct-rootfs', {
258 type => 'string', format => $rootfs_desc,
259 description => "Use volume as container root.",
260 optional => 1,
261});
262
263PVE::JSONSchema::register_standard_option('pve-lxc-snapshot-name', {
264 description => "The name of the snapshot.",
265 type => 'string', format => 'pve-configid',
266 maxLength => 40,
267});
268
269my $confdesc = {
270 lock => {
271 optional => 1,
272 type => 'string',
273 description => "Lock/unlock the VM.",
274 enum => [qw(migrate backup snapshot rollback)],
275 },
276 onboot => {
277 optional => 1,
278 type => 'boolean',
279 description => "Specifies whether a VM will be started during system bootup.",
280 default => 0,
281 },
282 startup => get_standard_option('pve-startup-order'),
283 template => {
284 optional => 1,
285 type => 'boolean',
286 description => "Enable/disable Template.",
287 default => 0,
288 },
289 arch => {
290 optional => 1,
291 type => 'string',
292 enum => ['amd64', 'i386'],
293 description => "OS architecture type.",
294 default => 'amd64',
295 },
296 ostype => {
297 optional => 1,
298 type => 'string',
ed027b58 299 enum => [qw(debian ubuntu centos fedora opensuse archlinux alpine gentoo unmanaged)],
1b4cf758
FG
300 description => "OS type. This is used to setup configuration inside the container, and corresponds to lxc setup scripts in /usr/share/lxc/config/<ostype>.common.conf. Value 'unmanaged' can be used to skip and OS specific setup.",
301 },
302 console => {
303 optional => 1,
304 type => 'boolean',
305 description => "Attach a console device (/dev/console) to the container.",
306 default => 1,
307 },
308 tty => {
309 optional => 1,
310 type => 'integer',
311 description => "Specify the number of tty available to the container",
312 minimum => 0,
313 maximum => 6,
314 default => 2,
315 },
f2357408
DM
316 cores => {
317 optional => 1,
318 type => 'integer',
319 description => "The number of cores assigned to the container. A container can use all available cores by default.",
320 minimum => 1,
321 maximum => 128,
322 },
1b4cf758
FG
323 cpulimit => {
324 optional => 1,
325 type => 'number',
064529c3 326 description => "Limit of CPU usage.\n\nNOTE: If the computer has 2 CPUs, it has a total of '2' CPU time. Value '0' indicates no CPU limit.",
1b4cf758
FG
327 minimum => 0,
328 maximum => 128,
329 default => 0,
330 },
331 cpuunits => {
332 optional => 1,
333 type => 'integer',
334 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 the weights of all the other running VMs.\n\nNOTE: You can disable fair-scheduler configuration by setting this to 0.",
335 minimum => 0,
336 maximum => 500000,
337 default => 1024,
338 },
339 memory => {
340 optional => 1,
341 type => 'integer',
342 description => "Amount of RAM for the VM in MB.",
343 minimum => 16,
344 default => 512,
345 },
346 swap => {
347 optional => 1,
348 type => 'integer',
349 description => "Amount of SWAP for the VM in MB.",
350 minimum => 0,
351 default => 512,
352 },
353 hostname => {
354 optional => 1,
355 description => "Set a host name for the container.",
356 type => 'string', format => 'dns-name',
357 maxLength => 255,
358 },
359 description => {
360 optional => 1,
361 type => 'string',
a069f163 362 description => "Container description. Only used on the configuration web interface.",
1b4cf758
FG
363 },
364 searchdomain => {
365 optional => 1,
366 type => 'string', format => 'dns-name-list',
367 description => "Sets DNS search domains for a container. Create will automatically use the setting from the host if you neither set searchdomain nor nameserver.",
368 },
369 nameserver => {
370 optional => 1,
371 type => 'string', format => 'address-list',
372 description => "Sets DNS server IP address for a container. Create will automatically use the setting from the host if you neither set searchdomain nor nameserver.",
373 },
374 rootfs => get_standard_option('pve-ct-rootfs'),
375 parent => {
376 optional => 1,
377 type => 'string', format => 'pve-configid',
378 maxLength => 40,
379 description => "Parent snapshot name. This is used internally, and should not be modified.",
380 },
381 snaptime => {
382 optional => 1,
383 description => "Timestamp for snapshots.",
384 type => 'integer',
385 minimum => 0,
386 },
387 cmode => {
388 optional => 1,
389 description => "Console mode. By default, the console command tries to open a connection to one of the available tty devices. By setting cmode to 'console' it tries to attach to /dev/console instead. If you set cmode to 'shell', it simply invokes a shell inside the container (no login).",
390 type => 'string',
391 enum => ['shell', 'console', 'tty'],
392 default => 'tty',
393 },
394 protection => {
395 optional => 1,
396 type => 'boolean',
397 description => "Sets the protection flag of the container. This will prevent the CT or CT's disk remove/update operation.",
398 default => 0,
399 },
400 unprivileged => {
401 optional => 1,
402 type => 'boolean',
403 description => "Makes the container run as unprivileged user. (Should not be modified manually.)",
404 default => 0,
405 },
406};
407
408my $valid_lxc_conf_keys = {
409 'lxc.include' => 1,
410 'lxc.arch' => 1,
411 'lxc.utsname' => 1,
412 'lxc.haltsignal' => 1,
413 'lxc.rebootsignal' => 1,
414 'lxc.stopsignal' => 1,
415 'lxc.init_cmd' => 1,
416 'lxc.network.type' => 1,
417 'lxc.network.flags' => 1,
418 'lxc.network.link' => 1,
419 'lxc.network.mtu' => 1,
420 'lxc.network.name' => 1,
421 'lxc.network.hwaddr' => 1,
422 'lxc.network.ipv4' => 1,
423 'lxc.network.ipv4.gateway' => 1,
424 'lxc.network.ipv6' => 1,
425 'lxc.network.ipv6.gateway' => 1,
426 'lxc.network.script.up' => 1,
427 'lxc.network.script.down' => 1,
428 'lxc.pts' => 1,
429 'lxc.console.logfile' => 1,
430 'lxc.console' => 1,
431 'lxc.tty' => 1,
432 'lxc.devttydir' => 1,
433 'lxc.hook.autodev' => 1,
434 'lxc.autodev' => 1,
435 'lxc.kmsg' => 1,
436 'lxc.mount' => 1,
437 'lxc.mount.entry' => 1,
438 'lxc.mount.auto' => 1,
439 'lxc.rootfs' => 'lxc.rootfs is auto generated from rootfs',
440 'lxc.rootfs.mount' => 1,
441 'lxc.rootfs.options' => 'lxc.rootfs.options is not supported' .
235dbdf3 442 ', please use mount point options in the "rootfs" key',
1b4cf758 443 # lxc.cgroup.*
51cb6715 444 # lxc.limit.*
1b4cf758
FG
445 'lxc.cap.drop' => 1,
446 'lxc.cap.keep' => 1,
447 'lxc.aa_profile' => 1,
448 'lxc.aa_allow_incomplete' => 1,
449 'lxc.se_context' => 1,
450 'lxc.seccomp' => 1,
451 'lxc.id_map' => 1,
452 'lxc.hook.pre-start' => 1,
453 'lxc.hook.pre-mount' => 1,
454 'lxc.hook.mount' => 1,
455 'lxc.hook.start' => 1,
456 'lxc.hook.stop' => 1,
457 'lxc.hook.post-stop' => 1,
458 'lxc.hook.clone' => 1,
459 'lxc.hook.destroy' => 1,
460 'lxc.loglevel' => 1,
461 'lxc.logfile' => 1,
462 'lxc.start.auto' => 1,
463 'lxc.start.delay' => 1,
464 'lxc.start.order' => 1,
465 'lxc.group' => 1,
466 'lxc.environment' => 1,
467};
468
5e5915c5 469our $netconf_desc = {
1b4cf758
FG
470 type => {
471 type => 'string',
472 optional => 1,
473 description => "Network interface type.",
474 enum => [qw(veth)],
475 },
476 name => {
477 type => 'string',
a069f163
DM
478 format_description => 'string',
479 description => 'Name of the network device as seen from inside the container. (lxc.network.name)',
1b4cf758
FG
480 pattern => '[-_.\w\d]+',
481 },
482 bridge => {
483 type => 'string',
a069f163 484 format_description => 'bridge',
1b4cf758
FG
485 description => 'Bridge to attach the network device to.',
486 pattern => '[-_.\w\d]+',
487 optional => 1,
488 },
489 hwaddr => {
490 type => 'string',
a069f163 491 format_description => "XX:XX:XX:XX:XX:XX",
e6f20294 492 description => 'The interface MAC address. This is dynamically allocated by default, but you can set that statically if needed, for example to always have the same link-local IPv6 address. (lxc.network.hwaddr)',
1b4cf758
FG
493 pattern => qr/(?:[a-f0-9]{2}:){5}[a-f0-9]{2}/i,
494 optional => 1,
495 },
496 mtu => {
497 type => 'integer',
1b4cf758
FG
498 description => 'Maximum transfer unit of the interface. (lxc.network.mtu)',
499 minimum => 64, # minimum ethernet frame is 64 bytes
500 optional => 1,
501 },
502 ip => {
503 type => 'string',
504 format => 'pve-ipv4-config',
505 format_description => 'IPv4Format/CIDR',
506 description => 'IPv4 address in CIDR format.',
507 optional => 1,
508 },
509 gw => {
510 type => 'string',
511 format => 'ipv4',
512 format_description => 'GatewayIPv4',
513 description => 'Default gateway for IPv4 traffic.',
514 optional => 1,
515 },
516 ip6 => {
517 type => 'string',
518 format => 'pve-ipv6-config',
519 format_description => 'IPv6Format/CIDR',
520 description => 'IPv6 address in CIDR format.',
521 optional => 1,
522 },
523 gw6 => {
524 type => 'string',
525 format => 'ipv6',
526 format_description => 'GatewayIPv6',
527 description => 'Default gateway for IPv6 traffic.',
528 optional => 1,
529 },
530 firewall => {
531 type => 'boolean',
1b4cf758
FG
532 description => "Controls whether this interface's firewall rules should be used.",
533 optional => 1,
534 },
535 tag => {
536 type => 'integer',
6b202dd5
DM
537 minimum => 1,
538 maximum => 4094,
1b4cf758
FG
539 description => "VLAN tag for this interface.",
540 optional => 1,
541 },
542 trunks => {
543 type => 'string',
544 pattern => qr/\d+(?:;\d+)*/,
545 format_description => 'vlanid[;vlanid...]',
546 description => "VLAN ids to pass through the interface",
547 optional => 1,
548 },
380962c7
WB
549 rate => {
550 type => 'number',
551 format_description => 'mbps',
552 description => "Apply rate limiting to the interface",
553 optional => 1,
554 },
1b4cf758
FG
555};
556PVE::JSONSchema::register_format('pve-lxc-network', $netconf_desc);
557
558my $MAX_LXC_NETWORKS = 10;
559for (my $i = 0; $i < $MAX_LXC_NETWORKS; $i++) {
560 $confdesc->{"net$i"} = {
561 optional => 1,
562 type => 'string', format => $netconf_desc,
563 description => "Specifies network interfaces for the container.",
564 };
565}
566
567PVE::JSONSchema::register_format('pve-lxc-mp-string', \&verify_lxc_mp_string);
568sub verify_lxc_mp_string {
569 my ($mp, $noerr) = @_;
570
571 # do not allow:
572 # /./ or /../
573 # /. or /.. at the end
574 # ../ at the beginning
575
576 if($mp =~ m@/\.\.?/@ ||
577 $mp =~ m@/\.\.?$@ ||
578 $mp =~ m@^\.\./@) {
579 return undef if $noerr;
580 die "$mp contains illegal character sequences\n";
581 }
582 return $mp;
583}
584
585my $mp_desc = {
586 %$rootfs_desc,
84820d40
DM
587 backup => {
588 type => 'boolean',
235dbdf3
FG
589 description => 'Whether to include the mount point in backups.',
590 verbose_description => 'Whether to include the mount point in backups '.
591 '(only used for volume mount points).',
84820d40
DM
592 optional => 1,
593 },
1b4cf758
FG
594 mp => {
595 type => 'string',
596 format => 'pve-lxc-mp-string',
597 format_description => 'Path',
235dbdf3 598 description => 'Path to the mount point as seen from inside the container '.
52b6f941 599 '(must not contain symlinks).',
235dbdf3 600 verbose_description => "Path to the mount point as seen from inside the container.\n\n".
52b6f941 601 "NOTE: Must not contain any symlinks for security reasons."
1b4cf758
FG
602 },
603};
604PVE::JSONSchema::register_format('pve-ct-mountpoint', $mp_desc);
605
606my $unuseddesc = {
607 optional => 1,
608 type => 'string', format => 'pve-volume-id',
2928e616 609 description => "Reference to unused volumes. This is used internally, and should not be modified manually.",
1b4cf758
FG
610};
611
612for (my $i = 0; $i < $MAX_MOUNT_POINTS; $i++) {
613 $confdesc->{"mp$i"} = {
614 optional => 1,
615 type => 'string', format => $mp_desc,
2928e616 616 description => "Use volume as container mount point.",
1b4cf758
FG
617 optional => 1,
618 };
619}
620
621for (my $i = 0; $i < $MAX_MOUNT_POINTS; $i++) {
622 $confdesc->{"unused$i"} = $unuseddesc;
623}
624
625sub parse_pct_config {
626 my ($filename, $raw) = @_;
627
628 return undef if !defined($raw);
629
630 my $res = {
631 digest => Digest::SHA::sha1_hex($raw),
632 snapshots => {},
633 };
634
635 $filename =~ m|/lxc/(\d+).conf$|
636 || die "got strange filename '$filename'";
637
638 my $vmid = $1;
639
640 my $conf = $res;
641 my $descr = '';
642 my $section = '';
643
644 my @lines = split(/\n/, $raw);
645 foreach my $line (@lines) {
646 next if $line =~ m/^\s*$/;
647
648 if ($line =~ m/^\[([a-z][a-z0-9_\-]+)\]\s*$/i) {
649 $section = $1;
650 $conf->{description} = $descr if $descr;
651 $descr = '';
652 $conf = $res->{snapshots}->{$section} = {};
653 next;
654 }
655
656 if ($line =~ m/^\#(.*)\s*$/) {
657 $descr .= PVE::Tools::decode_text($1) . "\n";
658 next;
659 }
660
661 if ($line =~ m/^(lxc\.[a-z0-9_\-\.]+)(:|\s*=)\s*(.*?)\s*$/) {
662 my $key = $1;
663 my $value = $3;
664 my $validity = $valid_lxc_conf_keys->{$key} || 0;
51cb6715 665 if ($validity eq 1 || $key =~ m/^lxc\.(?:cgroup|limit)\./) {
1b4cf758
FG
666 push @{$conf->{lxc}}, [$key, $value];
667 } elsif (my $errmsg = $validity) {
668 warn "vm $vmid - $key: $errmsg\n";
669 } else {
670 warn "vm $vmid - unable to parse config: $line\n";
671 }
672 } elsif ($line =~ m/^(description):\s*(.*\S)\s*$/) {
673 $descr .= PVE::Tools::decode_text($2);
674 } elsif ($line =~ m/snapstate:\s*(prepare|delete)\s*$/) {
675 $conf->{snapstate} = $1;
676 } elsif ($line =~ m/^([a-z][a-z_]*\d*):\s*(\S.*)\s*$/) {
677 my $key = $1;
678 my $value = $2;
679 eval { $value = PVE::LXC::Config->check_type($key, $value); };
680 warn "vm $vmid - unable to parse value of '$key' - $@" if $@;
681 $conf->{$key} = $value;
682 } else {
683 warn "vm $vmid - unable to parse config: $line\n";
684 }
685 }
686
687 $conf->{description} = $descr if $descr;
688
689 delete $res->{snapstate}; # just to be sure
690
691 return $res;
692}
693
694sub write_pct_config {
695 my ($filename, $conf) = @_;
696
697 delete $conf->{snapstate}; # just to be sure
698
699 my $volidlist = PVE::LXC::Config->get_vm_volumes($conf);
700 my $used_volids = {};
701 foreach my $vid (@$volidlist) {
702 $used_volids->{$vid} = 1;
703 }
704
705 # remove 'unusedX' settings if the volume is still used
706 foreach my $key (keys %$conf) {
707 my $value = $conf->{$key};
708 if ($key =~ m/^unused/ && $used_volids->{$value}) {
709 delete $conf->{$key};
710 }
711 }
712
713 my $generate_raw_config = sub {
714 my ($conf) = @_;
715
716 my $raw = '';
717
718 # add description as comment to top of file
719 my $descr = $conf->{description} || '';
720 foreach my $cl (split(/\n/, $descr)) {
721 $raw .= '#' . PVE::Tools::encode_text($cl) . "\n";
722 }
723
724 foreach my $key (sort keys %$conf) {
725 next if $key eq 'digest' || $key eq 'description' ||
726 $key eq 'pending' || $key eq 'snapshots' ||
727 $key eq 'snapname' || $key eq 'lxc';
728 my $value = $conf->{$key};
729 die "detected invalid newline inside property '$key'\n"
730 if $value =~ m/\n/;
731 $raw .= "$key: $value\n";
732 }
733
734 if (my $lxcconf = $conf->{lxc}) {
735 foreach my $entry (@$lxcconf) {
736 my ($k, $v) = @$entry;
737 $raw .= "$k: $v\n";
738 }
739 }
740
741 return $raw;
742 };
743
744 my $raw = &$generate_raw_config($conf);
745
746 foreach my $snapname (sort keys %{$conf->{snapshots}}) {
747 $raw .= "\n[$snapname]\n";
748 $raw .= &$generate_raw_config($conf->{snapshots}->{$snapname});
749 }
750
751 return $raw;
752}
753
754sub update_pct_config {
755 my ($class, $vmid, $conf, $running, $param, $delete) = @_;
756
757 my @nohotplug;
758
759 my $new_disks = 0;
760 my @deleted_volumes;
761
762 my $rootdir;
763 if ($running) {
764 my $pid = PVE::LXC::find_lxc_pid($vmid);
765 $rootdir = "/proc/$pid/root";
766 }
767
768 my $hotplug_error = sub {
769 if ($running) {
770 push @nohotplug, @_;
771 return 1;
772 } else {
773 return 0;
774 }
775 };
776
777 if (defined($delete)) {
778 foreach my $opt (@$delete) {
779 if (!exists($conf->{$opt})) {
a4a75420 780 # silently ignore
1b4cf758
FG
781 next;
782 }
783
e96a0ceb 784 if ($opt eq 'memory' || $opt eq 'rootfs') {
1b4cf758 785 die "unable to delete required option '$opt'\n";
e96a0ceb
DC
786 } elsif ($opt eq 'hostname') {
787 delete $conf->{$opt};
1b4cf758
FG
788 } elsif ($opt eq 'swap') {
789 delete $conf->{$opt};
790 PVE::LXC::write_cgroup_value("memory", $vmid,
791 "memory.memsw.limit_in_bytes", -1);
792 } elsif ($opt eq 'description' || $opt eq 'onboot' || $opt eq 'startup') {
793 delete $conf->{$opt};
794 } elsif ($opt eq 'nameserver' || $opt eq 'searchdomain' ||
795 $opt eq 'tty' || $opt eq 'console' || $opt eq 'cmode') {
796 next if $hotplug_error->($opt);
797 delete $conf->{$opt};
f2357408
DM
798 } elsif ($opt eq 'cores') {
799 delete $conf->{$opt}; # rest is handled by pvestatd
d13b770f 800 } elsif ($opt eq 'cpulimit') {
213d70e6 801 PVE::LXC::write_cgroup_value("cpu", $vmid, "cpu.cfs_quota_us", -1);
d13b770f
WB
802 delete $conf->{$opt};
803 } elsif ($opt eq 'cpuunits') {
804 PVE::LXC::write_cgroup_value("cpu", $vmid, "cpu.shares", $confdesc->{cpuunits}->{default});
805 delete $conf->{$opt};
1b4cf758
FG
806 } elsif ($opt =~ m/^net(\d)$/) {
807 delete $conf->{$opt};
808 next if !$running;
809 my $netid = $1;
810 PVE::Network::veth_delete("veth${vmid}i$netid");
811 } elsif ($opt eq 'protection') {
812 delete $conf->{$opt};
813 } elsif ($opt =~ m/^unused(\d+)$/) {
814 next if $hotplug_error->($opt);
815 PVE::LXC::Config->check_protection($conf, "can't remove CT $vmid drive '$opt'");
816 push @deleted_volumes, $conf->{$opt};
817 delete $conf->{$opt};
818 } elsif ($opt =~ m/^mp(\d+)$/) {
819 next if $hotplug_error->($opt);
820 PVE::LXC::Config->check_protection($conf, "can't remove CT $vmid drive '$opt'");
821 my $mp = PVE::LXC::Config->parse_ct_mountpoint($conf->{$opt});
822 delete $conf->{$opt};
823 if ($mp->{type} eq 'volume') {
824 PVE::LXC::Config->add_unused_volume($conf, $mp->{volume});
825 }
826 } elsif ($opt eq 'unprivileged') {
827 die "unable to delete read-only option: '$opt'\n";
828 } else {
829 die "implement me (delete: $opt)"
830 }
831 PVE::LXC::Config->write_config($vmid, $conf) if $running;
832 }
833 }
834
835 # There's no separate swap size to configure, there's memory and "total"
836 # memory (iow. memory+swap). This means we have to change them together.
837 my $wanted_memory = PVE::Tools::extract_param($param, 'memory');
838 my $wanted_swap = PVE::Tools::extract_param($param, 'swap');
839 if (defined($wanted_memory) || defined($wanted_swap)) {
840
841 my $old_memory = ($conf->{memory} || 512);
842 my $old_swap = ($conf->{swap} || 0);
843
844 $wanted_memory //= $old_memory;
845 $wanted_swap //= $old_swap;
846
847 my $total = $wanted_memory + $wanted_swap;
848 if ($running) {
849 my $old_total = $old_memory + $old_swap;
850 if ($total > $old_total) {
851 PVE::LXC::write_cgroup_value("memory", $vmid,
852 "memory.memsw.limit_in_bytes",
853 int($total*1024*1024));
854 PVE::LXC::write_cgroup_value("memory", $vmid,
855 "memory.limit_in_bytes",
856 int($wanted_memory*1024*1024));
857 } else {
858 PVE::LXC::write_cgroup_value("memory", $vmid,
859 "memory.limit_in_bytes",
860 int($wanted_memory*1024*1024));
861 PVE::LXC::write_cgroup_value("memory", $vmid,
862 "memory.memsw.limit_in_bytes",
863 int($total*1024*1024));
864 }
865 }
866 $conf->{memory} = $wanted_memory;
867 $conf->{swap} = $wanted_swap;
868
869 PVE::LXC::Config->write_config($vmid, $conf) if $running;
870 }
871
872 my $used_volids = {};
1b3213ae
FG
873 my $check_content_type = sub {
874 my ($mp) = @_;
875 my $sid = PVE::Storage::parse_volume_id($mp->{volume});
876 my $scfg = PVE::Storage::config();
877 my $storage_config = PVE::Storage::storage_config($scfg, $sid);
878 die "storage '$sid' does not allow content type 'rootdir' (Container)\n"
879 if !$storage_config->{content}->{rootdir};
880 };
1b4cf758
FG
881
882 foreach my $opt (keys %$param) {
883 my $value = $param->{$opt};
884 my $check_protection_msg = "can't update CT $vmid drive '$opt'";
f31bd6ae 885 if ($opt eq 'hostname' || $opt eq 'arch') {
1b4cf758
FG
886 $conf->{$opt} = $value;
887 } elsif ($opt eq 'onboot') {
888 $conf->{$opt} = $value ? 1 : 0;
889 } elsif ($opt eq 'startup') {
890 $conf->{$opt} = $value;
891 } elsif ($opt eq 'tty' || $opt eq 'console' || $opt eq 'cmode') {
892 next if $hotplug_error->($opt);
893 $conf->{$opt} = $value;
894 } elsif ($opt eq 'nameserver') {
895 next if $hotplug_error->($opt);
896 my $list = PVE::LXC::verify_nameserver_list($value);
897 $conf->{$opt} = $list;
898 } elsif ($opt eq 'searchdomain') {
899 next if $hotplug_error->($opt);
900 my $list = PVE::LXC::verify_searchdomain_list($value);
901 $conf->{$opt} = $list;
f2357408
DM
902 } elsif ($opt eq 'cores') {
903 $conf->{$opt} = $value;# rest is handled by pvestatd
1b4cf758 904 } elsif ($opt eq 'cpulimit') {
115e5862
FG
905 if ($value == 0) {
906 PVE::LXC::write_cgroup_value("cpu", $vmid, "cpu.cfs_quota_us", -1);
907 } else {
908 PVE::LXC::write_cgroup_value("cpu", $vmid, "cpu.cfs_quota_us", int(100000*$value));
909 }
1b4cf758
FG
910 $conf->{$opt} = $value;
911 } elsif ($opt eq 'cpuunits') {
912 $conf->{$opt} = $value;
913 PVE::LXC::write_cgroup_value("cpu", $vmid, "cpu.shares", $value);
914 } elsif ($opt eq 'description') {
915 $conf->{$opt} = PVE::Tools::encode_text($value);
916 } elsif ($opt =~ m/^net(\d+)$/) {
917 my $netid = $1;
918 my $net = PVE::LXC::Config->parse_lxc_network($value);
919 if (!$running) {
920 $conf->{$opt} = PVE::LXC::Config->print_lxc_network($net);
921 } else {
922 PVE::LXC::update_net($vmid, $conf, $opt, $net, $netid, $rootdir);
923 }
924 } elsif ($opt eq 'protection') {
925 $conf->{$opt} = $value ? 1 : 0;
926 } elsif ($opt =~ m/^mp(\d+)$/) {
927 next if $hotplug_error->($opt);
928 PVE::LXC::Config->check_protection($conf, $check_protection_msg);
929 my $old = $conf->{$opt};
56d7fc1b
FG
930 my $mp = PVE::LXC::Config->parse_ct_mountpoint($value);
931 if ($mp->{type} eq 'volume') {
1b3213ae 932 &$check_content_type($mp);
56d7fc1b
FG
933 $used_volids->{$mp->{volume}} = 1;
934 }
1b4cf758
FG
935 $conf->{$opt} = $value;
936 if (defined($old)) {
937 my $mp = PVE::LXC::Config->parse_ct_mountpoint($old);
938 if ($mp->{type} eq 'volume') {
939 PVE::LXC::Config->add_unused_volume($conf, $mp->{volume});
940 }
941 }
942 $new_disks = 1;
1b4cf758
FG
943 } elsif ($opt eq 'rootfs') {
944 next if $hotplug_error->($opt);
945 PVE::LXC::Config->check_protection($conf, $check_protection_msg);
946 my $old = $conf->{$opt};
947 $conf->{$opt} = $value;
56d7fc1b
FG
948 my $mp = PVE::LXC::Config->parse_ct_rootfs($value);
949 if ($mp->{type} eq 'volume') {
1b3213ae 950 &$check_content_type($mp);
56d7fc1b
FG
951 $used_volids->{$mp->{volume}} = 1;
952 }
1b4cf758
FG
953 if (defined($old)) {
954 my $mp = PVE::LXC::Config->parse_ct_rootfs($old);
955 if ($mp->{type} eq 'volume') {
956 PVE::LXC::Config->add_unused_volume($conf, $mp->{volume});
957 }
958 }
1d9369fd 959 $new_disks = 1;
1b4cf758
FG
960 } elsif ($opt eq 'unprivileged') {
961 die "unable to modify read-only option: '$opt'\n";
962 } elsif ($opt eq 'ostype') {
963 next if $hotplug_error->($opt);
964 $conf->{$opt} = $value;
965 } else {
966 die "implement me: $opt";
967 }
968 PVE::LXC::Config->write_config($vmid, $conf) if $running;
969 }
970
971 # Apply deletions and creations of new volumes
972 if (@deleted_volumes) {
973 my $storage_cfg = PVE::Storage::config();
974 foreach my $volume (@deleted_volumes) {
975 next if $used_volids->{$volume}; # could have been re-added, too
976 # also check for references in snapshots
977 next if $class->is_volume_in_use($conf, $volume, 1);
978 PVE::LXC::delete_mountpoint_volume($storage_cfg, $vmid, $volume);
979 }
980 }
981
982 if ($new_disks) {
983 my $storage_cfg = PVE::Storage::config();
984 PVE::LXC::create_disks($storage_cfg, $vmid, $conf, $conf);
985 }
986
987 # This should be the last thing we do here
988 if ($running && scalar(@nohotplug)) {
989 die "unable to modify " . join(',', @nohotplug) . " while container is running\n";
990 }
991}
992
993sub check_type {
994 my ($class, $key, $value) = @_;
995
996 die "unknown setting '$key'\n" if !$confdesc->{$key};
997
998 my $type = $confdesc->{$key}->{type};
999
1000 if (!defined($value)) {
1001 die "got undefined value\n";
1002 }
1003
1004 if ($value =~ m/[\n\r]/) {
1005 die "property contains a line feed\n";
1006 }
1007
1008 if ($type eq 'boolean') {
1009 return 1 if ($value eq '1') || ($value =~ m/^(on|yes|true)$/i);
1010 return 0 if ($value eq '0') || ($value =~ m/^(off|no|false)$/i);
1011 die "type check ('boolean') failed - got '$value'\n";
1012 } elsif ($type eq 'integer') {
1013 return int($1) if $value =~ m/^(\d+)$/;
1014 die "type check ('integer') failed - got '$value'\n";
1015 } elsif ($type eq 'number') {
1016 return $value if $value =~ m/^(\d+)(\.\d+)?$/;
1017 die "type check ('number') failed - got '$value'\n";
1018 } elsif ($type eq 'string') {
1019 if (my $fmt = $confdesc->{$key}->{format}) {
1020 PVE::JSONSchema::check_format($fmt, $value);
1021 return $value;
1022 }
1023 return $value;
1024 } else {
1025 die "internal error"
1026 }
1027}
1028
1029
1030# add JSON properties for create and set function
1031sub json_config_properties {
1032 my ($class, $prop) = @_;
1033
1034 foreach my $opt (keys %$confdesc) {
1035 next if $opt eq 'parent' || $opt eq 'snaptime';
1036 next if $prop->{$opt};
1037 $prop->{$opt} = $confdesc->{$opt};
1038 }
1039
1040 return $prop;
1041}
1042
1043sub __parse_ct_mountpoint_full {
1044 my ($class, $desc, $data, $noerr) = @_;
1045
1046 $data //= '';
1047
1048 my $res;
1049 eval { $res = PVE::JSONSchema::parse_property_string($desc, $data) };
1050 if ($@) {
1051 return undef if $noerr;
1052 die $@;
1053 }
1054
1055 if (defined(my $size = $res->{size})) {
1056 $size = PVE::JSONSchema::parse_size($size);
1057 if (!defined($size)) {
1058 return undef if $noerr;
1059 die "invalid size: $size\n";
1060 }
1061 $res->{size} = $size;
1062 }
1063
1064 $res->{type} = $class->classify_mountpoint($res->{volume});
1065
1066 return $res;
1067};
1068
1069sub parse_ct_rootfs {
1070 my ($class, $data, $noerr) = @_;
1071
1072 my $res = $class->__parse_ct_mountpoint_full($rootfs_desc, $data, $noerr);
1073
1074 $res->{mp} = '/' if defined($res);
1075
1076 return $res;
1077}
1078
1079sub parse_ct_mountpoint {
1080 my ($class, $data, $noerr) = @_;
1081
1082 return $class->__parse_ct_mountpoint_full($mp_desc, $data, $noerr);
1083}
1084
1085sub print_ct_mountpoint {
1086 my ($class, $info, $nomp) = @_;
1087 my $skip = [ 'type' ];
1088 push @$skip, 'mp' if $nomp;
1089 return PVE::JSONSchema::print_property_string($info, $mp_desc, $skip);
1090}
1091
1092sub print_lxc_network {
1093 my ($class, $net) = @_;
1094 return PVE::JSONSchema::print_property_string($net, $netconf_desc);
1095}
1096
1097sub parse_lxc_network {
1098 my ($class, $data) = @_;
1099
1100 my $res = {};
1101
1102 return $res if !$data;
1103
1104 $res = PVE::JSONSchema::parse_property_string($netconf_desc, $data);
1105
1106 $res->{type} = 'veth';
2f19133b
WB
1107 if (!$res->{hwaddr}) {
1108 my $dc = PVE::Cluster::cfs_read_file('datacenter.cfg');
1109 $res->{hwaddr} = PVE::Tools::random_ether_addr($dc->{mac_prefix});
1110 }
1b4cf758
FG
1111
1112 return $res;
1113}
1114
1115sub option_exists {
1116 my ($class, $name) = @_;
1117
1118 return defined($confdesc->{$name});
1119}
1120# END JSON config code
1121
d250604f
FG
1122sub classify_mountpoint {
1123 my ($class, $vol) = @_;
1124 if ($vol =~ m!^/!) {
1125 return 'device' if $vol =~ m!^/dev/!;
1126 return 'bind';
1127 }
1128 return 'volume';
1129}
1130
1131sub is_volume_in_use {
1132 my ($class, $config, $volid, $include_snapshots) = @_;
1133 my $used = 0;
1134
1135 $class->foreach_mountpoint($config, sub {
1136 my ($ms, $mountpoint) = @_;
1137 return if $used;
1138 $used = $mountpoint->{type} eq 'volume' && $mountpoint->{volume} eq $volid;
1139 });
1140
1141 my $snapshots = $config->{snapshots};
1142 if ($include_snapshots && $snapshots) {
1143 foreach my $snap (keys %$snapshots) {
1144 $used ||= $class->is_volume_in_use($snapshots->{$snap}, $volid);
1145 }
1146 }
1147
1148 return $used;
1149}
1150
1151sub has_dev_console {
1152 my ($class, $conf) = @_;
1153
1154 return !(defined($conf->{console}) && !$conf->{console});
1155}
1156
be7942f0
DM
1157sub has_lxc_entry {
1158 my ($class, $conf, $keyname) = @_;
1159
1160 if (my $lxcconf = $conf->{lxc}) {
1161 foreach my $entry (@$lxcconf) {
1162 my ($key, undef) = @$entry;
1163 return 1 if $key eq $keyname;
1164 }
1165 }
1166
1167 return 0;
1168}
1169
1b4cf758
FG
1170sub get_tty_count {
1171 my ($class, $conf) = @_;
1172
1173 return $conf->{tty} // $confdesc->{tty}->{default};
1174}
1175
1176sub get_cmode {
1177 my ($class, $conf) = @_;
1178
1179 return $conf->{cmode} // $confdesc->{cmode}->{default};
1180}
1181
d250604f
FG
1182sub mountpoint_names {
1183 my ($class, $reverse) = @_;
1184
1185 my @names = ('rootfs');
1186
1187 for (my $i = 0; $i < $MAX_MOUNT_POINTS; $i++) {
1188 push @names, "mp$i";
1189 }
1190
1191 return $reverse ? reverse @names : @names;
1192}
1193
1194sub foreach_mountpoint_full {
8915b450 1195 my ($class, $conf, $reverse, $func, @param) = @_;
d250604f
FG
1196
1197 foreach my $key ($class->mountpoint_names($reverse)) {
1198 my $value = $conf->{$key};
1199 next if !defined($value);
1b4cf758 1200 my $mountpoint = $key eq 'rootfs' ? $class->parse_ct_rootfs($value, 1) : $class->parse_ct_mountpoint($value, 1);
d250604f
FG
1201 next if !defined($mountpoint);
1202
8915b450 1203 &$func($key, $mountpoint, @param);
d250604f
FG
1204 }
1205}
1206
1207sub foreach_mountpoint {
8915b450 1208 my ($class, $conf, $func, @param) = @_;
d250604f 1209
8915b450 1210 $class->foreach_mountpoint_full($conf, 0, $func, @param);
d250604f
FG
1211}
1212
1213sub foreach_mountpoint_reverse {
8915b450 1214 my ($class, $conf, $func, @param) = @_;
d250604f 1215
8915b450 1216 $class->foreach_mountpoint_full($conf, 1, $func, @param);
d250604f
FG
1217}
1218
1219sub get_vm_volumes {
1220 my ($class, $conf, $excludes) = @_;
1221
1222 my $vollist = [];
1223
1224 $class->foreach_mountpoint($conf, sub {
1225 my ($ms, $mountpoint) = @_;
1226
1227 return if $excludes && $ms eq $excludes;
1228
1229 my $volid = $mountpoint->{volume};
1230 return if !$volid || $mountpoint->{type} ne 'volume';
1231
1232 my ($sid, $volname) = PVE::Storage::parse_volume_id($volid, 1);
1233 return if !$sid;
1234
1235 push @$vollist, $volid;
1236 });
1237
1238 return $vollist;
1239}
1240
67afe46e 1241return 1;