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