2582581d40fc951017eda0fc7111268c7244d67f
[pxelator] / lib / PXElator / kvm.pm
1 package kvm;
2
3 use warnings;
4 use strict;
5 use autodie;
6
7 use server;
8
9 use Data::Dump qw/dump/;
10
11 our $memory_size = 512;
12
13 # AC = private, AD = multicast, AE = local
14
15 sub nr { $ENV{nr} || 0 };
16
17 sub port {
18         my ($port,$del) = @_;
19         $port += nr();
20         return join( $del, $server::ip, $port );
21 }
22
23 sub fork_if_active { qw/monitor serial/ }
24
25 use x11;
26
27 sub monitor {
28         x11::xterm( 'monitor ' . nr() => 'nc ' . port(10000,' ') );
29 }
30
31 sub serial {
32         x11::xterm( 'serial ' . nr() => 'nc ' . port(11000,' ') );
33 }
34
35 sub actions { qw/reset activate/ }
36
37 sub reset {
38         my $sock = IO::Socket::INET->new( port(10000,':') );
39         print $sock "system_reset\n";
40         close $sock;
41 }
42
43 sub activate {
44         system "xdotool windowactivate `xdotool search --class kvm`"
45 }
46
47 sub start {
48         my $nr = $ENV{nr} || 0;
49
50         my $mac = sprintf('AC:DE:48:00:00:%02x', $nr);
51         my $mon = port(10000,':');
52         my $ser = port(11000,':');
53
54         my $ifname = 'kvm' . $nr;
55
56         warn "# kvm start $nr $mac $mon $ser $ifname";
57
58 #       system "ifconfig $ifname down";
59 #       system "brctl delif virtual $ifname";
60 #       system "tunctl -d $ifname";
61
62         my $ifconfig = `/sbin/ifconfig $ifname`;
63
64         # FIXME tunctl -u $server::user
65         system "tunctl -t $ifname"
66                 unless $ifconfig =~ m{$ifname};
67         system "ifconfig $ifname up"
68                 unless $ifconfig =~ m{UP};
69         system "brctl addif virtual $ifname"
70                 unless `brctl show` =~ m{$ifname};
71
72         my $ip = client::ip_from_mac $mac;
73
74         my $name = client::conf( $ip, 'hostname' );
75         $name ||= $nr;
76
77         my $kvm_bin = client::conf( $ip => 'kvm.bin' ) || 'kvm';
78         my $boot = client::conf( $ip, 'kvm.boot' ) || 'n'; # network by default
79
80         my $kvm = qq|
81                 $kvm_bin
82                 -name "$name"
83                 -m $memory_size -net nic,macaddr=$mac
84                 -net tap,ifname=$ifname,script=no
85                 -boot $boot
86                 -monitor tcp:$mon,server,nowait
87                 -serial  tcp:$ser,server,nowait
88         |;
89
90         $kvm .= ' -vnc ' . port(0,':') unless $ENV{DISPLAY};
91
92         #       -runas $server::user
93         $kvm =~ s{\s+}{ }gs;
94
95         warn $kvm;
96         exec $kvm;
97
98 }
99
100 sub nr_from_mac {
101         my $mac = shift;
102         my $nr = (split(/:/,$mac,6))[-1];
103         $nr = hex($nr);
104         return $nr;
105 }
106
107 sub next_nr {
108         my @kvms = glob "$server::conf/mac/AC:DE:48:00:00:*";
109         my $nr = nr_from_mac( pop @kvms );
110         return $nr + 1;
111 }
112
113 warn 'loaded';
114
115 1;