try to keep comments in /etc/network/interfaces
[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
695 # always add the vmbr0 bridge device
696 $ifaces->{vmbr0}->{exists} = 1;
697
698 if (my $fd2 = IO::File->new("/proc/net/if_inet6", "r")) {
699 while (defined ($line = <$fd2>)) {
700 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+)$/) {
701 $ifaces->{$1}->{active} = 1;
702 }
703 }
704 close ($fd2);
705 }
706
707 my $gateway = 0;
708
709 while (defined ($line = <$fh>)) {
710 chomp ($line);
711 next if $line =~ m/^#/;
712
713 if ($line =~ m/^auto\s+(.*)$/) {
714 my @aa = split (/\s+/, $1);
715
716 foreach my $a (@aa) {
717 $ifaces->{$a}->{autostart} = 1;
718 }
719
720 } elsif ($line =~ m/^iface\s+(\S+)\s+inet\s+(\S+)\s*$/) {
721 my $i = $1;
722 $ifaces->{$i}->{method} = $2;
723
724 my $d = $ifaces->{$i};
72ca6520
DM
725 while (defined ($line = <$fh>)) {
726 if ($line =~ m/^#(.*)\s*$/) {
727 $d->{comment} = '' if !$d->{comment};
728 $d->{comment} .= PVE::Tools::decode_text($1) . "\n";
729 } elsif ($line =~ m/^\s+((\S+)\s+(.+))$/) {
730 my $option = $1;
731 my ($id, $value) = ($2, $3);
732 if (($id eq 'address') || ($id eq 'netmask') || ($id eq 'broadcast')) {
733 $d->{$id} = $value;
734 } elsif ($id eq 'gateway') {
735 $d->{$id} = $value;
736 $gateway = 1;
737 } elsif ($id eq 'slaves' || $id eq 'bridge_ports') {
738 my $devs = {};
739 foreach my $p (split (/\s+/, $value)) {
740 next if $p eq 'none';
741 $devs->{$p} = 1;
e143e9d8 742 }
72ca6520
DM
743 my $str = join (' ', sort keys %{$devs});
744 $d->{$id} = $str || '';
745 } elsif ($id eq 'bridge_stp') {
746 if ($value =~ m/^\s*(on|yes)\s*$/i) {
747 $d->{$id} = 'on';
748 } else {
749 $d->{$id} = 'off';
750 }
751 } elsif ($id eq 'bridge_fd') {
752 $d->{$id} = $value;
753 } elsif ($id eq 'bond_miimon') {
754 $d->{$id} = $value;
755 } elsif ($id eq 'bond_mode') {
756 # always use names
757 foreach my $bm (keys %$bond_modes) {
758 my $id = $bond_modes->{$bm};
759 if ($id eq $value) {
760 $value = $bm;
761 last;
762 }
763 }
764 $d->{$id} = $value;
765 } else {
766 push @{$d->{options}}, $option;
e143e9d8 767 }
e143e9d8 768 } else {
72ca6520 769 last;
e143e9d8
DM
770 }
771 }
772 }
773 }
774
775
776 if (!$gateway) {
777 $ifaces->{vmbr0}->{gateway} = '';
778 }
779
780 if (!$ifaces->{lo}) {
781 $ifaces->{lo}->{method} = 'loopback';
782 $ifaces->{lo}->{type} = 'loopback';
783 $ifaces->{lo}->{autostart} = 1;
784 }
785
786 foreach my $iface (keys %$ifaces) {
787 my $d = $ifaces->{$iface};
788 if ($iface =~ m/^bond\d+$/) {
789 $d->{type} = 'bond';
790 } elsif ($iface =~ m/^vmbr\d+$/) {
791 $d->{type} = 'bridge';
792 if (!defined ($d->{bridge_fd})) {
793 $d->{bridge_fd} = 0;
794 }
795 if (!defined ($d->{bridge_stp})) {
796 $d->{bridge_stp} = 'off';
797 }
798 } elsif ($iface =~ m/^(\S+):\d+$/) {
799 $d->{type} = 'alias';
800 if (defined ($ifaces->{$1})) {
801 $d->{exists} = $ifaces->{$1}->{exists};
802 } else {
803 $ifaces->{$1}->{exists} = 0;
804 $d->{exists} = 0;
805 }
806 } elsif ($iface =~ m/^eth[0-9]$/) {
807 $d->{type} = 'eth';
808 } elsif ($iface =~ m/^lo$/) {
809 $d->{type} = 'loopback';
810 } else {
811 $d->{type} = 'unknown';
812 }
813
814 $d->{method} = 'manual' if !$d->{method};
815 }
816
817 return $ifaces;
818}
819
820sub __interface_to_string {
821 my ($iface, $d) = @_;
822
823 return '' if !($d && $d->{method});
824
825 my $raw = '';
826
827 if ($d->{autostart}) {
828 $raw .= "auto $iface\n";
829 }
830 $raw .= "iface $iface inet $d->{method}\n";
831 $raw .= "\taddress $d->{address}\n" if $d->{address};
832 $raw .= "\tnetmask $d->{netmask}\n" if $d->{netmask};
833 $raw .= "\tgateway $d->{gateway}\n" if $d->{gateway};
834 $raw .= "\tbroadcast $d->{broadcast}\n" if $d->{broadcast};
835
836 if ($d->{bridge_ports} || ($iface =~ m/^vmbr\d+$/)) {
837 my $ports = $d->{bridge_ports} || 'none';
838 $raw .= "\tbridge_ports $ports\n";
839 }
840
841 if ($d->{bridge_stp} || ($iface =~ m/^vmbr\d+$/)) {
842 my $v = $d->{bridge_stp};
843 $v = defined ($v) ? $v : 'off';
844 $raw .= "\tbridge_stp $v\n";
845 }
846
847 if (defined ($d->{bridge_fd}) || ($iface =~ m/^vmbr\d+$/)) {
848 my $v = $d->{bridge_fd};
849 $v = defined ($v) ? $v : 0;
850 $raw .= "\tbridge_fd $v\n";
851 }
852
853 if ($d->{slaves} || ($iface =~ m/^bond\d+$/)) {
854 my $slaves = $d->{slaves} || 'none';
855 $raw .= "\tslaves $slaves\n";
856 }
857
858 if (defined ($d->{'bond_miimon'}) || ($iface =~ m/^bond\d+$/)) {
859 my $v = $d->{'bond_miimon'};
860 $v = defined ($v) ? $v : 100;
861 $raw .= "\tbond_miimon $v\n";
862 }
863
864 if (defined ($d->{'bond_mode'}) || ($iface =~ m/^bond\d+$/)) {
865 my $v = $d->{'bond_mode'};
866 $v = defined ($v) ? $v : 'balance-rr';
867 $raw .= "\tbond_mode $v\n";
868 }
869
870 foreach my $option (@{$d->{options}}) {
871 $raw .= "\t$option\n";
872 }
873
72ca6520
DM
874 # add comments
875 my $comment = $d->{comment} || '';
876 foreach my $cl (split(/\n/, $comment)) {
877 $raw .= '#' . PVE::Tools::encode_text($cl) . "\n";
878 }
879
e143e9d8
DM
880 $raw .= "\n";
881
882 return $raw;
883}
884
885sub write_etc_network_interfaces {
886 my ($filename, $fh, $ifaces) = @_;
887
888 my $raw = "# network interface settings\n";
889
890 my $printed = {};
891
892 foreach my $t (('lo', 'eth', '')) {
893 foreach my $iface (sort keys %$ifaces) {
894 my $d = $ifaces->{$iface};
895
896 next if $printed->{$iface};
897 next if $iface !~ m/^$t/;
898
899 $printed->{$iface} = 1;
900 $raw .= __interface_to_string($iface, $d);
901 }
902 }
903
904 PVE::Tools::safe_print($filename, $fh, $raw);
905}
906
907register_file('interfaces', "/etc/network/interfaces",
908 \&read_etc_network_interfaces,
909 \&write_etc_network_interfaces);
910
9111;