]> git.proxmox.com Git - pve-common.git/blame - data/PVE/INotify.pm
remove 'name' to the list of utf8 encoded parameters.
[pve-common.git] / data / PVE / INotify.pm
CommitLineData
e143e9d8
DM
1package PVE::INotify;
2
3# todo: maybe we do not need update_file() ?
4
5use strict;
6use POSIX;
7use IO::File;
8use IO::Dir;
9use File::stat;
10use File::Basename;
11use Fcntl qw(:DEFAULT :flock);
12use PVE::SafeSyslog;
13use PVE::Exception qw(raise_param_exc);
14use PVE::Tools;
15use Storable qw(dclone);
16use Linux::Inotify2;
17use base 'Exporter';
18use JSON;
19
20our @EXPORT_OK = qw(read_file write_file register_file);
21
22my $ccache;
23my $ccachemap;
24my $ccacheregex;
25my $inotify;
26my $inotify_pid = 0;
27my $versions;
28my $shadowfiles = {
29 '/etc/network/interfaces' => '/etc/network/interfaces.new',
30};
31
32# to enable cached operation, you need to call 'inotify_init'
33# inotify handles are a limited resource, so use with care (only
34# enable the cache if you really need it)
35
36# Note: please close the inotify handle after you fork
37
38sub ccache_default_writer {
39 my ($filename, $data) = @_;
40
41 die "undefined config writer for '$filename' :ERROR";
42}
43
44sub ccache_default_parser {
45 my ($filename, $srcfd) = @_;
46
47 die "undefined config reader for '$filename' :ERROR";
48}
49
50sub ccache_compute_diff {
51 my ($filename, $shadow) = @_;
52
53 my $diff = '';
54
55 open (TMP, "diff -b -N -u '$filename' '$shadow'|");
56
57 while (my $line = <TMP>) {
58 $diff .= $line;
59 }
60
61 close (TMP);
62
63 $diff = undef if !$diff;
64
65 return $diff;
66}
67
68sub ccache_info {
69 my ($filename) = @_;
70
71 foreach my $uid (keys %$ccacheregex) {
72 my $ccinfo = $ccacheregex->{$uid};
73 my $dir = $ccinfo->{dir};
74 my $regex = $ccinfo->{regex};
75 if ($filename =~ m|^$dir/+$regex$|) {
76 if (!$ccache->{$filename}) {
77 my $cp = {};
78 while (my ($k, $v) = each %$ccinfo) {
79 $cp->{$k} = $v;
80 }
81 $ccache->{$filename} = $cp;
82 }
83 return ($ccache->{$filename}, $filename);
84 }
85 }
86
87 $filename = $ccachemap->{$filename} if defined ($ccachemap->{$filename});
88
89 die "file '$filename' not added :ERROR" if !defined ($ccache->{$filename});
90
91 return ($ccache->{$filename}, $filename);
92}
93
94sub write_file {
95 my ($fileid, $data, $full) = @_;
96
97 my ($ccinfo, $filename) = ccache_info($fileid);
98
99 my $writer = $ccinfo->{writer};
100
101 my $realname = $filename;
102
103 my $shadow;
104 if ($shadow = $shadowfiles->{$filename}) {
105 $realname = $shadow;
106 }
107
108 my $perm = $ccinfo->{perm} || 0644;
109
110 my $tmpname = "$realname.tmp.$$";
111
112 my $res;
113 eval {
114 my $fh = IO::File->new($tmpname, O_WRONLY|O_CREAT, $perm);
115 die "unable to open file '$tmpname' - $!\n" if !$fh;
116
117 $res = &$writer($filename, $fh, $data);
118
119 die "closing file '$tmpname' failed - $!\n" unless close $fh;
120 };
121 my $err = $@;
122
123 $ccinfo->{version} = undef;
124
125 if ($err) {
126 unlink $tmpname;
127 die $err;
128 }
129
130 if (!rename($tmpname, $realname)) {
131 my $msg = "close (rename) atomic file '$filename' failed: $!\n";
132 unlink $tmpname;
133 die $msg;
134 }
135
136 my $diff;
137 if ($shadow && $full) {
138 $diff = ccache_compute_diff ($filename, $shadow);
139 }
140
141 if ($full) {
142 return { data => $res, changes => $diff };
143 }
144
145 return $res;
146}
147
148sub update_file {
149 my ($fileid, $data, @args) = @_;
150
151 my ($ccinfo, $filename) = ccache_info($fileid);
152
153 my $update = $ccinfo->{update};
154
155 die "unable to update/merge data" if !$update;
156
157 my $lkfn = "$filename.lock";
158
159 my $timeout = 10;
160
161 my $fd;
162
163 my $code = sub {
164
165 $fd = IO::File->new ($filename, "r");
166
167 my $new = &$update($filename, $fd, $data, @args);
168
169 if (defined($new)) {
170 PVE::Tools::file_set_contents($filename, $new, $ccinfo->{perm});
171 } else {
172 unlink $filename;
173 }
174 };
175
176 PVE::Tools::lock_file($lkfn, $timeout, $code);
177 my $err = $@;
178
179 close($fd) if defined($fd);
180
181 die $err if $err;
182
183 return undef;
184}
185
186sub discard_changes {
187 my ($fileid, $full) = @_;
188
189 my ($ccinfo, $filename) = ccache_info($fileid);
190
191 if (my $copy = $shadowfiles->{$filename}) {
192 unlink $copy;
193 }
194
195 return read_file ($filename, $full);
196}
197
198sub read_file {
199 my ($fileid, $full) = @_;
200
201 my $parser;
202
203 my ($ccinfo, $filename) = ccache_info($fileid);
204
205 $parser = $ccinfo->{parser};
206
207 my $fd;
208 my $shadow;
209
210 poll() if $inotify; # read new inotify events
211
212 $versions->{$filename} = 0 if !defined ($versions->{$filename});
213
214 my $cver = $versions->{$filename};
215
216 if (my $copy = $shadowfiles->{$filename}) {
217 if ($fd = IO::File->new ($copy, "r")) {
218 $shadow = $copy;
219 } else {
220 $fd = IO::File->new ($filename, "r");
221 }
222 } else {
223 $fd = IO::File->new ($filename, "r");
224 }
225
226 my $acp = $ccinfo->{always_call_parser};
227
228 if (!$fd) {
229 $ccinfo->{version} = undef;
230 $ccinfo->{data} = undef;
231 $ccinfo->{diff} = undef;
232 return undef if !$acp;
233 }
234
235 my $noclone = $ccinfo->{noclone};
236
237 # file unchanged?
238 if (!$ccinfo->{nocache} &&
239 $inotify && $versions->{$filename} &&
240 defined ($ccinfo->{data}) &&
241 defined ($ccinfo->{version}) &&
242 ($ccinfo->{readonce} ||
243 ($ccinfo->{version} == $versions->{$filename}))) {
244
245 my $ret;
246 if (!$noclone && ref ($ccinfo->{data})) {
247 $ret->{data} = dclone ($ccinfo->{data});
248 } else {
249 $ret->{data} = $ccinfo->{data};
250 }
251 $ret->{changes} = $ccinfo->{diff};
252
253 return $full ? $ret : $ret->{data};
254 }
255
256 my $diff;
257
258 if ($shadow) {
259 $diff = ccache_compute_diff ($filename, $shadow);
260 }
261
262 my $res = &$parser($filename, $fd);
263
264 if (!$ccinfo->{nocache}) {
265 $ccinfo->{version} = $cver;
266 }
267
268 # we cache data with references, so we always need to
269 # dclone this data. Else the original data may get
270 # modified.
271 $ccinfo->{data} = $res;
272
273 # also store diff
274 $ccinfo->{diff} = $diff;
275
276 my $ret;
277 if (!$noclone && ref ($ccinfo->{data})) {
278 $ret->{data} = dclone ($ccinfo->{data});
279 } else {
280 $ret->{data} = $ccinfo->{data};
281 }
282 $ret->{changes} = $ccinfo->{diff};
283
284 return $full ? $ret : $ret->{data};
285}
286
287sub parse_ccache_options {
288 my ($ccinfo, %options) = @_;
289
290 foreach my $opt (keys %options) {
291 my $v = $options{$opt};
292 if ($opt eq 'readonce') {
293 $ccinfo->{$opt} = $v;
294 } elsif ($opt eq 'nocache') {
295 $ccinfo->{$opt} = $v;
296 } elsif ($opt eq 'shadow') {
297 $ccinfo->{$opt} = $v;
298 } elsif ($opt eq 'perm') {
299 $ccinfo->{$opt} = $v;
300 } elsif ($opt eq 'noclone') {
301 # noclone flag for large read-only data chunks like aplinfo
302 $ccinfo->{$opt} = $v;
303 } elsif ($opt eq 'always_call_parser') {
304 # when set, we call parser even when the file does not exists.
305 # this allows the parser to return some default
306 $ccinfo->{$opt} = $v;
307 } else {
308 die "internal error - unsupported option '$opt'";
309 }
310 }
311}
312
313sub register_file {
314 my ($id, $filename, $parser, $writer, $update, %options) = @_;
315
316 die "can't register file after initify_init" if $inotify;
317
318 die "file '$filename' already added :ERROR" if defined ($ccache->{$filename});
319 die "ID '$id' already used :ERROR" if defined ($ccachemap->{$id});
320
321 my $ccinfo = {};
322
323 $ccinfo->{id} = $id;
324 $ccinfo->{parser} = $parser || \&ccache_default_parser;
325 $ccinfo->{writer} = $writer || \&ccache_default_writer;
326 $ccinfo->{update} = $update;
327
328 parse_ccache_options($ccinfo, %options);
329
330 if ($options{shadow}) {
331 $shadowfiles->{$filename} = $options{shadow};
332 }
333
334 $ccachemap->{$id} = $filename;
335 $ccache->{$filename} = $ccinfo;
336}
337
338sub register_regex {
339 my ($dir, $regex, $parser, $writer, $update, %options) = @_;
340
341 die "can't register regex after initify_init" if $inotify;
342
343 my $uid = "$dir/$regex";
344 die "regular expression '$uid' already added :ERROR" if defined ($ccacheregex->{$uid});
345
346 my $ccinfo = {};
347
348 $ccinfo->{dir} = $dir;
349 $ccinfo->{regex} = $regex;
350 $ccinfo->{parser} = $parser || \&ccache_default_parser;
351 $ccinfo->{writer} = $writer || \&ccache_default_writer;
352 $ccinfo->{update} = $update;
353
354 parse_ccache_options($ccinfo, %options);
355
356 $ccacheregex->{$uid} = $ccinfo;
357}
358
359sub poll {
360 return if !$inotify;
361
362 if ($inotify_pid != $$) {
363 syslog ('err', "got inotify poll request in wrong process - disabling inotify");
364 $inotify = undef;
365 } else {
366 1 while $inotify && $inotify->poll;
367 }
368}
369
370sub flushcache {
371 foreach my $filename (keys %$ccache) {
372 $ccache->{$filename}->{version} = undef;
373 $ccache->{$filename}->{data} = undef;
374 $ccache->{$filename}->{diff} = undef;
375 }
376}
377
378sub inotify_close {
379 $inotify = undef;
380}
381
382sub inotify_init {
383
384 die "only one inotify instance allowed" if $inotify;
385
386 $inotify = Linux::Inotify2->new()
387 || die "Unable to create new inotify object: $!";
388
389 $inotify->blocking (0);
390
391 $versions = {};
392
393 my $dirhash = {};
394 foreach my $fn (keys %$ccache) {
395 my $dir = dirname ($fn);
396 my $base = basename ($fn);
397
398 $dirhash->{$dir}->{$base} = $fn;
399
400 if (my $sf = $shadowfiles->{$fn}) {
401 $base = basename ($sf);
402 $dir = dirname ($sf);
403 $dirhash->{$dir}->{$base} = $fn; # change version of original file!
404 }
405 }
406
407 foreach my $uid (keys %$ccacheregex) {
408 my $ccinfo = $ccacheregex->{$uid};
409 $dirhash->{$ccinfo->{dir}}->{_regex} = 1;
410 }
411
412 $inotify_pid = $$;
413
414 foreach my $dir (keys %$dirhash) {
415
416 my $evlist = IN_MODIFY|IN_ATTRIB|IN_MOVED_FROM|IN_MOVED_TO|IN_DELETE|IN_CREATE;
417 $inotify->watch ($dir, $evlist, sub {
418 my $e = shift;
419 my $name = $e->name;
420
421 if ($inotify_pid != $$) {
422 syslog ('err', "got inotify event in wrong process");
423 }
424
425 if ($e->IN_ISDIR || !$name) {
426 return;
427 }
428
429 if ($e->IN_Q_OVERFLOW) {
430 syslog ('info', "got inotify overflow - flushing cache");
431 flushcache();
432 return;
433 }
434
435 if ($e->IN_UNMOUNT) {
436 syslog ('err', "got 'unmount' event on '$name' - disabling inotify");
437 $inotify = undef;
438 }
439 if ($e->IN_IGNORED) {
440 syslog ('err', "got 'ignored' event on '$name' - disabling inotify");
441 $inotify = undef;
442 }
443
444 if ($dirhash->{$dir}->{_regex}) {
445 foreach my $uid (keys %$ccacheregex) {
446 my $ccinfo = $ccacheregex->{$uid};
447 next if $dir ne $ccinfo->{dir};
448 my $regex = $ccinfo->{regex};
449 if ($regex && ($name =~ m|^$regex$|)) {
450
451 my $fn = "$dir/$name";
452 $versions->{$fn}++;
453 #print "VERSION:$fn:$versions->{$fn}\n";
454 }
455 }
456 } elsif (my $fn = $dirhash->{$dir}->{$name}) {
457
458 $versions->{$fn}++;
459 #print "VERSION:$fn:$versions->{$fn}\n";
460 }
461 });
462 }
463
464 foreach my $dir (keys %$dirhash) {
465 foreach my $name (keys %{$dirhash->{$dir}}) {
466 if ($name eq '_regex') {
467 foreach my $uid (keys %$ccacheregex) {
468 my $ccinfo = $ccacheregex->{$uid};
469 next if $dir ne $ccinfo->{dir};
470 my $re = $ccinfo->{regex};
471 if (my $fd = IO::Dir->new ($dir)) {
472 while (defined(my $de = $fd->read)) {
473 if ($de =~ m/^$re$/) {
474 my $fn = "$dir/$de";
475 $versions->{$fn}++; # init with version
476 #print "init:$fn:$versions->{$fn}\n";
477 }
478 }
479 }
480 }
481 } else {
482 my $fn = $dirhash->{$dir}->{$name};
483 $versions->{$fn}++; # init with version
484 #print "init:$fn:$versions->{$fn}\n";
485 }
486 }
487 }
488}
489
490my $cached_nodename;
491
492sub nodename {
493
494 return $cached_nodename if $cached_nodename;
495
496 my ($sysname, $nodename) = POSIX::uname();
497
498 $nodename =~ s/\..*$//; # strip domain part, if any
499
500 die "unable to read node name\n" if !$nodename;
501
502 $cached_nodename = $nodename;
503
504 return $cached_nodename;
505}
506
507sub read_etc_hostname {
508 my ($filename, $fd) = @_;
509
510 my $hostname = <$fd>;
511
512 chomp $hostname;
513
514 $hostname =~ s/\..*$//; # strip domain part, if any
515
516 return $hostname;
517}
518
519sub write_etc_hostname {
520 my ($filename, $fh, $hostname) = @_;
521
522 die "write failed: $!" unless print $fh "$hostname\n";
523
524 return $hostname;
525}
526
527register_file('hostname', "/etc/hostname",
528 \&read_etc_hostname,
529 \&write_etc_hostname);
530
531sub read_etc_resolv_conf {
532 my ($filename, $fh) = @_;
533
534 my $res = {};
535
536 my $nscount = 0;
537 while (my $line = <$fh>) {
538 chomp $line;
539 if ($line =~ m/^(search|domain)\s+(\S+)\s*/) {
540 $res->{search} = $2;
541 } elsif ($line =~ m/^nameserver\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s*/) {
542 $nscount++;
543 if ($nscount <= 3) {
544 $res->{"dns$nscount"} = $1;
545 }
546 }
547 }
548
549 return $res;
550}
551
552sub update_etc_resolv_conf {
553 my ($filename, $fh, $resolv, @args) = @_;
554
555 my $data = "";
556
557 $data = "search $resolv->{search}\n"
558 if $resolv->{search};
559
560 my $written = {};
561 foreach my $k ("dns1", "dns2", "dns3") {
562 my $ns = $resolv->{$k};
563 if ($ns && $ns ne '0.0.0.0' && !$written->{$ns}) {
564 $written->{$ns} = 1;
565 $data .= "nameserver $ns\n";
566 }
567 }
568
569 while (my $line = <$fh>) {
570 next if $line =~ m/^(search|domain|nameserver)\s+/;
571 $data .= $line
572 }
573
574 return $data;
575}
576
577register_file('resolvconf', "/etc/resolv.conf",
578 \&read_etc_resolv_conf, undef,
579 \&update_etc_resolv_conf);
580
581sub read_etc_timezone {
582 my ($filename, $fd) = @_;
583
584 my $timezone = <$fd>;
585
586 chomp $timezone;
587
588 return $timezone;
589}
590
591sub write_etc_timezone {
592 my ($filename, $fh, $timezone) = @_;
593
594 my $tzinfo = "/usr/share/zoneinfo/$timezone";
595
596 raise_param_exc({ 'timezone' => "No such timezone" })
597 if (! -f $tzinfo);
598
599 ($timezone) = $timezone =~ m/^(.*)$/; # untaint
600
601 print $fh "$timezone\n";
602
603 unlink ("/etc/localtime");
604 symlink ("/usr/share/zoneinfo/$timezone", "/etc/localtime");
605
606}
607
608register_file('timezone', "/etc/timezone",
609 \&read_etc_timezone,
610 \&write_etc_timezone);
611
612sub read_active_workers {
613 my ($filename, $fh) = @_;
614
615 return [] if !$fh;
616
617 my $res = [];
618 while (defined (my $line = <$fh>)) {
75ed54f1 619 if ($line =~ m/^(\S+)\s(0|1)(\s([0-9A-Za-z]{8})(\s(\s*\S.*))?)?$/) {
e143e9d8
DM
620 my $upid = $1;
621 my $saved = $2;
622 my $endtime = $4;
623 my $status = $6;
624 if ((my $task = PVE::Tools::upid_decode($upid, 1))) {
625 $task->{upid} = $upid;
626 $task->{saved} = $saved;
627 $task->{endtime} = hex($endtime) if $endtime;
628 $task->{status} = $status if $status;
629 push @$res, $task;
630 }
631 } else {
632 warn "unable to parse line: $line";
633 }
634 }
635
636 return $res;
637
638}
639
640sub write_active_workers {
641 my ($filename, $fh, $tasklist) = @_;
642
643 my $raw = '';
644 foreach my $task (@$tasklist) {
645 my $upid = $task->{upid};
646 my $saved = $task->{saved} ? 1 : 0;
647 if ($task->{endtime}) {
648 if ($task->{status}) {
649 $raw .= sprintf("$upid $saved %08X $task->{status}\n", $task->{endtime});
650 } else {
651 $raw .= sprintf("$upid $saved %08X\n", $task->{endtime});
652 }
653 } else {
654 $raw .= "$upid $saved\n";
655 }
656 }
657
658 PVE::Tools::safe_print($filename, $fh, $raw) if $raw;
659}
660
661register_file('active', "/var/log/pve/tasks/active",
662 \&read_active_workers,
663 \&write_active_workers);
664
665
666my $bond_modes = { 'balance-rr' => 0,
667 'active-backup' => 1,
668 'balance-xor' => 2,
669 'broadcast' => 3,
670 '802.3ad' => 4,
671 'balance-tlb' => 5,
672 'balance-alb' => 6,
673 };
674
675#sub get_bond_modes {
676# return $bond_modes;
677#}
678
679sub read_etc_network_interfaces {
680 my ($filename, $fh) = @_;
681
682 my $ifaces = {};
683
684 my $line;
685
686 if (my $fd2 = IO::File->new("/proc/net/dev", "r")) {
687 while (defined ($line = <$fd2>)) {
688 if ($line =~ m/^\s*(eth[0-9]):.*/) {
689 $ifaces->{$1}->{exists} = 1;
690 }
691 }
692 close($fd2);
693 }
694
c9dc8645
DM
695 # we try to keep order inside the file
696 my $priority = 2; # 1 is reserved for lo
697
e143e9d8
DM
698 # always add the vmbr0 bridge device
699 $ifaces->{vmbr0}->{exists} = 1;
700
701 if (my $fd2 = IO::File->new("/proc/net/if_inet6", "r")) {
702 while (defined ($line = <$fd2>)) {
703 if ($line =~ m/^[a-f0-9]{32}\s+[a-f0-9]{2}\s+[a-f0-9]{2}\s+[a-f0-9]{2}\s+[a-f0-9]{2}\s+(lo|eth\d+|vmbr\d+|bond\d+)$/) {
704 $ifaces->{$1}->{active} = 1;
705 }
706 }
707 close ($fd2);
708 }
709
710 my $gateway = 0;
711
712 while (defined ($line = <$fh>)) {
713 chomp ($line);
714 next if $line =~ m/^#/;
715
716 if ($line =~ m/^auto\s+(.*)$/) {
717 my @aa = split (/\s+/, $1);
718
719 foreach my $a (@aa) {
720 $ifaces->{$a}->{autostart} = 1;
721 }
722
723 } elsif ($line =~ m/^iface\s+(\S+)\s+inet\s+(\S+)\s*$/) {
724 my $i = $1;
725 $ifaces->{$i}->{method} = $2;
c9dc8645 726 $ifaces->{$i}->{priority} = $priority++;
e143e9d8
DM
727
728 my $d = $ifaces->{$i};
72ca6520
DM
729 while (defined ($line = <$fh>)) {
730 if ($line =~ m/^#(.*)\s*$/) {
731 $d->{comment} = '' if !$d->{comment};
732 $d->{comment} .= PVE::Tools::decode_text($1) . "\n";
733 } elsif ($line =~ m/^\s+((\S+)\s+(.+))$/) {
734 my $option = $1;
735 my ($id, $value) = ($2, $3);
736 if (($id eq 'address') || ($id eq 'netmask') || ($id eq 'broadcast')) {
737 $d->{$id} = $value;
738 } elsif ($id eq 'gateway') {
739 $d->{$id} = $value;
740 $gateway = 1;
741 } elsif ($id eq 'slaves' || $id eq 'bridge_ports') {
742 my $devs = {};
743 foreach my $p (split (/\s+/, $value)) {
744 next if $p eq 'none';
745 $devs->{$p} = 1;
e143e9d8 746 }
72ca6520
DM
747 my $str = join (' ', sort keys %{$devs});
748 $d->{$id} = $str || '';
749 } elsif ($id eq 'bridge_stp') {
750 if ($value =~ m/^\s*(on|yes)\s*$/i) {
751 $d->{$id} = 'on';
752 } else {
753 $d->{$id} = 'off';
754 }
755 } elsif ($id eq 'bridge_fd') {
756 $d->{$id} = $value;
757 } elsif ($id eq 'bond_miimon') {
758 $d->{$id} = $value;
759 } elsif ($id eq 'bond_mode') {
760 # always use names
761 foreach my $bm (keys %$bond_modes) {
762 my $id = $bond_modes->{$bm};
763 if ($id eq $value) {
764 $value = $bm;
765 last;
766 }
767 }
768 $d->{$id} = $value;
769 } else {
770 push @{$d->{options}}, $option;
e143e9d8 771 }
e143e9d8 772 } else {
72ca6520 773 last;
e143e9d8
DM
774 }
775 }
776 }
777 }
778
779
780 if (!$gateway) {
781 $ifaces->{vmbr0}->{gateway} = '';
782 }
783
784 if (!$ifaces->{lo}) {
c9dc8645 785 $ifaces->{lo}->{priority} = 1;
e143e9d8
DM
786 $ifaces->{lo}->{method} = 'loopback';
787 $ifaces->{lo}->{type} = 'loopback';
788 $ifaces->{lo}->{autostart} = 1;
789 }
790
791 foreach my $iface (keys %$ifaces) {
792 my $d = $ifaces->{$iface};
793 if ($iface =~ m/^bond\d+$/) {
794 $d->{type} = 'bond';
795 } elsif ($iface =~ m/^vmbr\d+$/) {
796 $d->{type} = 'bridge';
797 if (!defined ($d->{bridge_fd})) {
798 $d->{bridge_fd} = 0;
799 }
800 if (!defined ($d->{bridge_stp})) {
801 $d->{bridge_stp} = 'off';
802 }
803 } elsif ($iface =~ m/^(\S+):\d+$/) {
804 $d->{type} = 'alias';
805 if (defined ($ifaces->{$1})) {
806 $d->{exists} = $ifaces->{$1}->{exists};
807 } else {
808 $ifaces->{$1}->{exists} = 0;
809 $d->{exists} = 0;
810 }
811 } elsif ($iface =~ m/^eth[0-9]$/) {
812 $d->{type} = 'eth';
813 } elsif ($iface =~ m/^lo$/) {
814 $d->{type} = 'loopback';
815 } else {
816 $d->{type} = 'unknown';
817 }
818
819 $d->{method} = 'manual' if !$d->{method};
820 }
821
822 return $ifaces;
823}
824
825sub __interface_to_string {
826 my ($iface, $d) = @_;
827
828 return '' if !($d && $d->{method});
829
830 my $raw = '';
831
832 if ($d->{autostart}) {
833 $raw .= "auto $iface\n";
834 }
835 $raw .= "iface $iface inet $d->{method}\n";
836 $raw .= "\taddress $d->{address}\n" if $d->{address};
837 $raw .= "\tnetmask $d->{netmask}\n" if $d->{netmask};
838 $raw .= "\tgateway $d->{gateway}\n" if $d->{gateway};
839 $raw .= "\tbroadcast $d->{broadcast}\n" if $d->{broadcast};
840
841 if ($d->{bridge_ports} || ($iface =~ m/^vmbr\d+$/)) {
842 my $ports = $d->{bridge_ports} || 'none';
843 $raw .= "\tbridge_ports $ports\n";
844 }
845
846 if ($d->{bridge_stp} || ($iface =~ m/^vmbr\d+$/)) {
847 my $v = $d->{bridge_stp};
848 $v = defined ($v) ? $v : 'off';
849 $raw .= "\tbridge_stp $v\n";
850 }
851
852 if (defined ($d->{bridge_fd}) || ($iface =~ m/^vmbr\d+$/)) {
853 my $v = $d->{bridge_fd};
854 $v = defined ($v) ? $v : 0;
855 $raw .= "\tbridge_fd $v\n";
856 }
857
858 if ($d->{slaves} || ($iface =~ m/^bond\d+$/)) {
859 my $slaves = $d->{slaves} || 'none';
860 $raw .= "\tslaves $slaves\n";
861 }
862
863 if (defined ($d->{'bond_miimon'}) || ($iface =~ m/^bond\d+$/)) {
864 my $v = $d->{'bond_miimon'};
865 $v = defined ($v) ? $v : 100;
866 $raw .= "\tbond_miimon $v\n";
867 }
868
869 if (defined ($d->{'bond_mode'}) || ($iface =~ m/^bond\d+$/)) {
870 my $v = $d->{'bond_mode'};
871 $v = defined ($v) ? $v : 'balance-rr';
872 $raw .= "\tbond_mode $v\n";
873 }
874
875 foreach my $option (@{$d->{options}}) {
876 $raw .= "\t$option\n";
877 }
878
72ca6520
DM
879 # add comments
880 my $comment = $d->{comment} || '';
881 foreach my $cl (split(/\n/, $comment)) {
882 $raw .= '#' . PVE::Tools::encode_text($cl) . "\n";
883 }
884
e143e9d8
DM
885 $raw .= "\n";
886
887 return $raw;
888}
889
890sub write_etc_network_interfaces {
891 my ($filename, $fh, $ifaces) = @_;
892
893 my $raw = "# network interface settings\n";
894
895 my $printed = {};
896
c9dc8645
DM
897 foreach my $iface (sort {
898 my $ref1 = $ifaces->{$a};
899 my $ref2 = $ifaces->{$b};
900 my $p1 = $ref1->{priority} || 100000;
901 my $p2 = $ref2->{priority} || 100000;
e143e9d8 902
c9dc8645 903 return $p1 <=> $p2 if $p1 != $p2;
e143e9d8 904
c9dc8645
DM
905
906 return $a cmp $b;
907 } keys %$ifaces) {
908
909 my $d = $ifaces->{$iface};
910
911 next if $printed->{$iface};
912
913 $printed->{$iface} = 1;
914 $raw .= __interface_to_string($iface, $d);
e143e9d8
DM
915 }
916
917 PVE::Tools::safe_print($filename, $fh, $raw);
918}
919
920register_file('interfaces', "/etc/network/interfaces",
921 \&read_etc_network_interfaces,
922 \&write_etc_network_interfaces);
923
9241;