]> git.sur5r.net Git - i3/i3/blob - testcases/lib/SocketActivation.pm
Merge branch 'master' into next
[i3/i3] / testcases / lib / SocketActivation.pm
1 package SocketActivation;
2 # vim:ts=4:sw=4:expandtab
3
4 use strict;
5 use warnings;
6 use IO::Socket::UNIX; # core
7 use Cwd qw(abs_path); # core
8 use POSIX qw(:fcntl_h); # core
9 use AnyEvent::Handle; # not core
10 use AnyEvent::Util; # not core
11 use Exporter 'import';
12 use v5.10;
13
14 our @EXPORT = qw(activate_i3);
15
16 #
17 # Starts i3 using socket activation. Creates a listening socket (with bind +
18 # listen) which is then passed to i3, who in turn calls accept and handles the
19 # requests.
20 #
21 # Since the kernel buffers the connect, the parent process can connect to the
22 # socket immediately after forking. It then sends a request and waits until it
23 # gets an answer. Obviously, i3 has to be initialized to actually answer the
24 # request.
25 #
26 # This way, we can wait *precisely* the amount of time which i3 waits to get
27 # ready, which is a *HUGE* speed gain (and a lot more robust) in comparison to
28 # using sleep() with a fixed amount of time.
29 #
30 # unix_socket_path: Location of the socket to use for the activation
31 # display: X11 $ENV{DISPLAY}
32 # configfile: path to the configuration file to use
33 # logpath: path to the logfile to which i3 will append
34 # cv: an AnyEvent->condvar which will be triggered once i3 is ready
35 #
36 sub activate_i3 {
37     my %args = @_;
38
39     # remove the old unix socket
40     unlink($args{unix_socket_path});
41
42     my $socket = IO::Socket::UNIX->new(
43         Listen => 1,
44         Local => $args{unix_socket_path},
45     );
46
47     my $pid = fork;
48     if (!defined($pid)) {
49         die "could not fork()";
50     }
51     if ($pid == 0) {
52         $ENV{LISTEN_PID} = $$;
53         $ENV{LISTEN_FDS} = 1;
54         delete $ENV{DESKTOP_STARTUP_ID};
55         unless ($args{dont_create_temp_dir}) {
56             $ENV{XDG_RUNTIME_DIR} = '/tmp/i3-testsuite/';
57             mkdir $ENV{XDG_RUNTIME_DIR};
58         }
59         $ENV{DISPLAY} = $args{display};
60         $ENV{PATH} = join(':',
61             '../i3-nagbar',
62             '../i3-msg',
63             '../i3-config-wizard',
64             '../i3bar',
65             '..',
66             $ENV{PATH}
67         );
68
69         # We are about to exec, but we did not modify $^F to include $socket
70         # when creating the socket (because the file descriptor could have a
71         # number != 3 which would lead to i3 leaking a file descriptor). This
72         # caused Perl to set the FD_CLOEXEC flag, which would close $socket on
73         # exec(), effectively *NOT* passing $socket to the new process.
74         # Therefore, we explicitly clear FD_CLOEXEC (the only flag right now)
75         # by setting the flags to 0.
76         POSIX::fcntl($socket, F_SETFD, 0) or die "Could not clear fd flags: $!";
77
78         # If the socket does not use file descriptor 3 by chance already, we
79         # close fd 3 and dup2() the socket to 3.
80         if (fileno($socket) != 3) {
81             POSIX::close(3);
82             POSIX::dup2(fileno($socket), 3);
83             POSIX::close(fileno($socket));
84         }
85
86         # Make sure no file descriptors are open. Strangely, I got an open file
87         # descriptor pointing to AnyEvent/Impl/EV.pm when testing.
88         AnyEvent::Util::close_all_fds_except(0, 1, 2, 3);
89
90         # Construct the command to launch i3. Use maximum debug level, disable
91         # the interactive signalhandler to make it crash immediately instead.
92         # Also disable logging to SHM since we redirect the logs anyways.
93         # Force Xinerama because we use Xdmx for multi-monitor tests.
94         my $i3cmd = abs_path("../i3") . q| -V -d all --disable-signalhandler| .
95                                         q| --shmlog-size=0 --force-xinerama|;
96
97         # For convenience:
98         my $outdir = $args{outdir};
99         my $test = $args{testname};
100
101         if ($args{restart}) {
102             $i3cmd .= ' -L ' . abs_path('restart-state.golden');
103         }
104
105         if ($args{valgrind}) {
106             $i3cmd =
107                 qq|valgrind -v --log-file="$outdir/valgrind-for-$test.log" | .
108                 qq|--leak-check=full --track-origins=yes --num-callers=20 | .
109                 qq|--tool=memcheck -- $i3cmd|;
110         }
111
112         my $logfile = "$outdir/i3-log-for-$test";
113         # Append to $logfile instead of overwriting because i3 might be
114         # run multiple times in one testcase.
115         my $cmd = "exec $i3cmd -c $args{configfile} >>$logfile 2>&1";
116
117         if ($args{strace}) {
118             my $out = "$outdir/strace-for-$test.log";
119
120             # We overwrite LISTEN_PID with the correct process ID to make
121             # socket activation work (LISTEN_PID has to match getpid(),
122             # otherwise the LISTEN_FDS will be treated as a left-over).
123             $cmd = qq|strace -fF -s2048 -v -o "$out" -- | .
124                      'sh -c "export LISTEN_PID=\$\$; ' . $cmd . '"';
125         }
126
127         if ($args{xtrace}) {
128             my $out = "$outdir/xtrace-for-$test.log";
129
130             # See comment in $args{strace} branch.
131             $cmd = qq|xtrace -n -o "$out" -- | .
132                      'sh -c "export LISTEN_PID=\$\$; ' . $cmd . '"';
133         }
134
135         # We need to use the shell due to using output redirections.
136         exec '/bin/sh', '-c', $cmd;
137
138         # if we are still here, i3 could not be found or exec failed. bail out.
139         exit 1;
140     }
141
142     # close the socket, the child process should be the only one which keeps a file
143     # descriptor on the listening socket.
144     $socket->close;
145
146     # We now connect (will succeed immediately) and send a request afterwards.
147     # As soon as the reply is there, i3 is considered ready.
148     my $cl = IO::Socket::UNIX->new(Peer => $args{unix_socket_path});
149     my $hdl;
150     $hdl = AnyEvent::Handle->new(
151         fh => $cl,
152         on_error => sub {
153             $hdl->destroy;
154             $args{cv}->send(0);
155         });
156
157     # send a get_tree message without payload
158     $hdl->push_write('i3-ipc' . pack("LL", 0, 4));
159
160     # wait for the reply
161     $hdl->push_read(chunk => 1, => sub {
162         my ($h, $line) = @_;
163         $args{cv}->send(1);
164         undef $hdl;
165     });
166
167     return $pid;
168 }
169
170 1