]> git.sur5r.net Git - i3/i3.github.io/blob - docs/4.2/testsuite.html
repositories: revert to apt install ./keyring.deb
[i3/i3.github.io] / docs / 4.2 / testsuite.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"\r
2     "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\r
3 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">\r
4 <head>\r
5 <link rel="icon" type="image/png" href="/favicon.png">\r
6 <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />\r
7 <meta name="generator" content="AsciiDoc 8.6.4" />\r
8 <title>i3: i3 testsuite</title>\r
9 <link rel="stylesheet" href="/css/style.css" type="text/css" />\r
10 <link rel="stylesheet" href="/css/xhtml11.css" type="text/css" />\r
11 <script type="text/javascript">\r
12 /*<![CDATA[*/\r
13 window.onload = function(){asciidoc.footnotes(); asciidoc.toc(2);}\r
14 /*]]>*/\r
15 </script>\r
16 <script type="text/javascript" src="/js/asciidoc-xhtml11.js"></script>\r
17 </head>\r
18 <body class="article">\r
19 \r
20         <div id="main">\r
21             <a href="/"><h1 id="title">i3 - improved tiling WM</h1></a>\r
22                         <ul id="nav">\r
23                                 <li><a style="border-bottom: 2px solid #fff" href="/docs">Docs</a></li>\r
24                                 <li><a href="/screenshots">Screens</a></li>\r
25                                 <li><a href="/contact">Contact</a></li>\r
26                                 <li><a href="http://bugs.i3wm.org/">Bugs</a></li>\r
27                         </ul>\r
28         <br style="clear: both">\r
29 <div id="content">\r
30 <div id="header">\r
31 <h1>i3 testsuite</h1>\r
32 <span id="author">Michael Stapelberg</span><br />\r
33 <span id="email"><tt>&lt;<a href="mailto:michael+i3@stapelberg.de">michael+i3@stapelberg.de</a>&gt;</tt></span><br />\r
34 <span id="revdate">September 2011</span>\r
35 <div id="toc">
36   <div id="toctitle">Table of Contents</div>
37   <noscript><p><b>JavaScript must be enabled in your browser to display the table of contents.</b></p></noscript>
38 </div>\r
39 </div>\r
40 <div id="preamble">\r
41 <div class="sectionbody">\r
42 <div class="paragraph"><p>This document explains how the i3 testsuite works, how to use it and extend it.\r
43 It is targeted at developers who not necessarily have been doing testing before\r
44 or have not been testing in Perl before. In general, the testsuite is not of\r
45 interest for end users.</p></div>\r
46 </div>\r
47 </div>\r
48 <div class="sect1">\r
49 <h2 id="_introduction">1. Introduction</h2>\r
50 <div class="sectionbody">\r
51 <div class="paragraph"><p>The i3 testsuite is a collection of files which contain testcases for various\r
52 i3 features. Some of them test if a certain workflow works correctly (moving\r
53 windows, focus behaviour, …). Others are regression tests and contain code\r
54 which previously made i3 crash or lead to unexpected behaviour. They then check\r
55 if i3 still runs (meaning it did not crash) and if it handled everything\r
56 correctly.</p></div>\r
57 <div class="paragraph"><p>The goal of having these tests is to automatically find problems and to\r
58 automatically get a feel for whether a change in the source code breaks any\r
59 existing feature. After every modification of the i3 sourcecode, the developer\r
60 should run the full testsuite. If one of the tests fails, the corresponding\r
61 problem should be fixed (or, in some cases, the testcase has to be modified).\r
62 For every bugreport, a testcase should be written to test the correct\r
63 behaviour. Initially, it will fail, but after fixing the bug, it will pass.\r
64 This ensures (or increases the chance) that bugs which have been fixed once\r
65 will never be found again.</p></div>\r
66 <div class="paragraph"><p>Also, when implementing a new feature, a testcase might be a good way to be\r
67 able to easily test if the feature is working correctly. Many developers will\r
68 test manually if everything works. Having a testcase not only helps you with\r
69 that, but it will also be useful for every future change.</p></div>\r
70 </div>\r
71 </div>\r
72 <div class="sect1">\r
73 <h2 id="_implementation">2. Implementation</h2>\r
74 <div class="sectionbody">\r
75 <div class="paragraph"><p>For several reasons, the i3 testsuite has been implemented in Perl:</p></div>\r
76 <div class="olist arabic"><ol class="arabic">\r
77 <li>\r
78 <p>\r
79 Perl has a long tradition of testing. Every popular/bigger Perl module which\r
80    you can find on CPAN will not only come with documentation, but also with\r
81    tests. Therefore, the available infrastructure for tests is comprehensive.\r
82    See for example the excellent <a href="http://search.cpan.org/perldoc?Test::More">http://search.cpan.org/perldoc?Test::More</a>\r
83    and the referenced <a href="http://search.cpan.org/perldoc?Test::Tutorial">http://search.cpan.org/perldoc?Test::Tutorial</a>.\r
84 </p>\r
85 </li>\r
86 <li>\r
87 <p>\r
88 Perl is widely available and has a well-working package infrastructure.\r
89 </p>\r
90 </li>\r
91 <li>\r
92 <p>\r
93 The author is familiar with Perl :).\r
94 </p>\r
95 </li>\r
96 </ol></div>\r
97 <div class="paragraph"><p>Please do not start programming language flamewars at this point.</p></div>\r
98 <div class="sect2">\r
99 <h3 id="_mechanisms">2.1. Mechanisms</h3>\r
100 <div class="sect3">\r
101 <h4 id="_script_complete_run">2.1.1. Script: complete-run</h4>\r
102 <div class="paragraph"><p>The testcases are run by a script called <tt>complete-run.pl</tt>. It runs all\r
103 testcases by default, but you can be more specific and let it only run one or\r
104 more testcases. Also, it takes care of starting up a separate instance of i3\r
105 with an appropriate configuration file and creates a folder for each run\r
106 containing the appropriate i3 logfile for each testcase. The latest folder can\r
107 always be found under the symlink <tt>latest/</tt>. Unless told differently, it will\r
108 run the tests on a separate X server instance (using the Xdummy script).</p></div>\r
109 <div class="listingblock">\r
110 <div class="title">Example invocation of complete-run.pl+</div>\r
111 <div class="content">\r
112 <pre><tt>$ cd ~/i3/testcases\r
113 \r
114 $ ./complete-run.pl\r
115 # output omitted because it is very long\r
116 All tests successful.\r
117 Files=78, Tests=734, 27 wallclock secs ( 0.38 usr  0.48 sys + 17.65 cusr  3.21 csys = 21.72 CPU)\r
118 Result: PASS\r
119 \r
120 $ ./complete-run.pl t/04-floating.t\r
121 [:3] i3 startup: took 0.07s, status = 1\r
122 [:3] Running t/04-floating.t with logfile testsuite-2011-09-24-16-06-04-4.0.2-226-g1eb011a/i3-log-for-04-floating.t\r
123 [:3] t/04-floating.t finished\r
124 [:3] killing i3\r
125 output for t/04-floating.t:\r
126 ok 1 - use X11::XCB::Window;\r
127 ok 2 - The object isa X11::XCB::Window\r
128 ok 3 - Window is mapped\r
129 ok 4 - i3 raised the width to 75\r
130 ok 5 - i3 raised the height to 50\r
131 ok 6 - i3 did not map it to (0x0)\r
132 ok 7 - The object isa X11::XCB::Window\r
133 ok 8 - i3 let the width at 80\r
134 ok 9 - i3 let the height at 90\r
135 ok 10 - i3 mapped it to x=1\r
136 ok 11 - i3 mapped it to y=18\r
137 ok 12 - The object isa X11::XCB::Window\r
138 ok 13 - i3 let the width at 80\r
139 ok 14 - i3 let the height at 90\r
140 1..14\r
141 \r
142 All tests successful.\r
143 Files=1, Tests=14,  0 wallclock secs ( 0.01 usr  0.00 sys +  0.19 cusr  0.03 csys =  0.23 CPU)\r
144 Result: PASS\r
145 \r
146 $ less latest/i3-log-for-04-floating.t</tt></pre>\r
147 </div></div>\r
148 </div>\r
149 <div class="sect3">\r
150 <h4 id="_ipc_interface">2.1.2. IPC interface</h4>\r
151 <div class="paragraph"><p>The testsuite makes extensive use of the IPC (Inter-Process Communication)\r
152 interface which i3 provides. It is used for the startup process of i3, for\r
153 terminating it cleanly and (most importantly) for modifying and getting the\r
154 current state (layout tree).</p></div>\r
155 <div class="paragraph"><p>See [<a href="http://i3wm.org/docs/ipc.html">http://i3wm.org/docs/ipc.html</a>] for documentation on the IPC interface.</p></div>\r
156 </div>\r
157 <div class="sect3">\r
158 <h4 id="_x11_xcb">2.1.3. X11::XCB</h4>\r
159 <div class="paragraph"><p>In order to open new windows, change attributes, get events, etc., the\r
160 testsuite uses X11::XCB, a new (and quite specific to i3 at the moment) Perl\r
161 module which uses the XCB protocol description to generate Perl bindings to\r
162 X11. They work in a very similar way to libxcb (which i3 uses) and provide\r
163 relatively high-level interfaces (objects such as <tt>X11::XCB::Window</tt>) aswell as\r
164 access to the low-level interface, which is very useful when testing a window\r
165 manager.</p></div>\r
166 </div>\r
167 </div>\r
168 <div class="sect2">\r
169 <h3 id="_filesystem_structure">2.2. Filesystem structure</h3>\r
170 <div class="paragraph"><p>In the git root of i3, the testcases live in the folder <tt>testcases</tt>. This\r
171 folder contains the <tt>complete-run.pl</tt> and <tt>Xdummy</tt> scripts and a base\r
172 configuration file which will be used for the tests. The different testcases\r
173 (their file extension is .t, not .pl) themselves can be found in the\r
174 conventionally named subfolder <tt>t</tt>:</p></div>\r
175 <div class="listingblock">\r
176 <div class="title">Filesystem structure</div>\r
177 <div class="content">\r
178 <pre><tt>├── testcases\r
179 │   ├── complete-run.pl\r
180 │   ├── i3-test.config\r
181 │   ├── lib\r
182 │   │   ├── i3test.pm\r
183 │   │   ├── SocketActivation.pm\r
184 │   │   └── StartXDummy.pm\r
185 │   ├── t\r
186 │   │   ├── 00-load.t\r
187 │   │   ├── 01-tile.t\r
188 │   │   ├── 02-fullscreen.t\r
189 │   │   ├── ...\r
190 │   │   ├── omitted for brevity\r
191 │   │   ├── ...\r
192 │   │   └── 74-regress-focus-toggle.t\r
193 │   └── Xdummy</tt></pre>\r
194 </div></div>\r
195 </div>\r
196 </div>\r
197 </div>\r
198 <div class="sect1">\r
199 <h2 id="_anatomy_of_a_testcase">3. Anatomy of a testcase</h2>\r
200 <div class="sectionbody">\r
201 <div class="paragraph"><p>Learning by example is definitely a good strategy when you are wondering how to\r
202 write a testcase. Let&#8217;s take <tt>t/11-goto.t</tt> as an easy example and go through it\r
203 step by step:</p></div>\r
204 <div class="listingblock">\r
205 <div class="title">t/11-goto.t: Boilerplate</div>\r
206 <div class="content">\r
207 <pre><tt>#!perl\r
208 # vim:ts=4:sw=4:expandtab\r
209 \r
210 use i3test;\r
211 use File::Temp;\r
212 \r
213 my $x = X11::XCB::Connection-&gt;new;</tt></pre>\r
214 </div></div>\r
215 <div class="paragraph"><p>This is what we call boilerplate. It exists at the top of every test file (to\r
216 some extent). The first line is the shebang, which specifies that this file is\r
217 a Perl script. The second line contains VIM specific settings on how to\r
218 edit/format this file (use spaces instead of tabs, indent using 4 spaces).\r
219 Afterwards, the <tt>i3test</tt> module is used. This module contains i3 testsuite\r
220 specific functions which you are strongly encouraged to use. They make writing\r
221 testcases a lot easier and will make it easier for other people to read your\r
222 tests.</p></div>\r
223 <div class="paragraph"><p>The next line uses the <tt>File::Temp</tt> module. This is specific to this testcase,\r
224 because it needs to generate a temporary name during the test. Many testcases\r
225 use only the <tt>i3test</tt> module.</p></div>\r
226 <div class="paragraph"><p>The last line opens a connection to X11. You might or might not need this in\r
227 your testcase, depending on whether you are going to open windows (etc.) or\r
228 only use i3 commands.</p></div>\r
229 <div class="listingblock">\r
230 <div class="title">t/11-goto.t: Setup</div>\r
231 <div class="content">\r
232 <pre><tt>my $tmp = fresh_workspace;\r
233 \r
234 cmd 'split h';</tt></pre>\r
235 </div></div>\r
236 <div class="paragraph"><p>The first line calls i3test&#8217;s <tt>fresh_workspace</tt> function which looks for a\r
237 currently unused workspace, switches to it, and returns its name. The variable\r
238 <tt>$tmp</tt> will end up having a value such as <tt>"/tmp/87kBVcHbA9"</tt>. Note that this\r
239 is not (necessarily) a valid path, it&#8217;s just a random workspace name.</p></div>\r
240 <div class="paragraph"><p>So, now that we are on a new workspace, we ensure that the workspace uses\r
241 horizontal orientation by issuing the <tt>split h</tt> command (see the i3 User&#8217;s\r
242 Guide for a list of commands). This is not strictly necessary, but good style.\r
243 In general, the <tt>cmd</tt> function executes the specified i3 command by using the\r
244 IPC interface and returns once i3 acknowledged the command.</p></div>\r
245 <div class="listingblock">\r
246 <div class="title">t/11-goto.t: Setup</div>\r
247 <div class="content">\r
248 <pre><tt>#####################################################################\r
249 # Create two windows and make sure focus switching works\r
250 #####################################################################\r
251 \r
252 my $top = open_window($x);\r
253 my $mid = open_window($x);\r
254 my $bottom = open_window($x);</tt></pre>\r
255 </div></div>\r
256 <div class="paragraph"><p>In every major section of a testcase, you should put a comment like the one\r
257 above. This makes it immediately clear how the file is structured.</p></div>\r
258 <div class="paragraph"><p>The <tt>open_window</tt> function opens a standard window, which will then be put into\r
259 tiling mode by i3. If you want a floating window, use the\r
260 <tt>open_floating_window</tt> function. These functions accept the same parameters as\r
261 <tt>X11::XCB::Window&#8594;new</tt>, see the i3test documentation at TODO.</p></div>\r
262 <div class="listingblock">\r
263 <div class="title">t/11-goto.t: Helper function</div>\r
264 <div class="content">\r
265 <pre><tt>#\r
266 # Returns the input focus after sending the given command to i3 via IPC\r
267 # and syncing with i3\r
268 #\r
269 sub focus_after {\r
270     my $msg = shift;\r
271 \r
272     cmd $msg;\r
273     sync_with_i3 $x;\r
274     return $x-&gt;input_focus;\r
275 }</tt></pre>\r
276 </div></div>\r
277 <div class="paragraph"><p>This section defines a helper function which will be used over and over in this\r
278 testcase. If you have code which gets executed more than once or twice\r
279 (depending on the length of your test, use your best judgement), please put it\r
280 in a function. Tests should be short, concise and clear.</p></div>\r
281 <div class="paragraph"><p>The <tt>focus_after</tt> function executes a command and returns the X11 focus after\r
282 the command was executed. The <tt>sync_with_i3</tt> command makes sure that i3 could\r
283 push its state to X11. See <a href="#i3_sync">[i3_sync]</a> to learn how this works exactly.</p></div>\r
284 <div class="listingblock">\r
285 <div class="title">t/11-goto.t: Test assumptions</div>\r
286 <div class="content">\r
287 <pre><tt>$focus = $x-&gt;input_focus;\r
288 is($focus, $bottom-&gt;id, "Latest window focused");\r
289 \r
290 $focus = focus_after('focus left');\r
291 is($focus, $mid-&gt;id, "Middle window focused");</tt></pre>\r
292 </div></div>\r
293 <div class="paragraph"><p>Now, we run the first two real tests. They use <tt>Test::More</tt>'s <tt>is</tt> function,\r
294 which compares two values and prints the differences if they are not the same.\r
295 After the arguments, we supply a short comment to indicate what we are testing\r
296 here. This makes it vastly more easy for the developer to spot which testcase\r
297 is the problem in case one fails.</p></div>\r
298 <div class="paragraph"><p>The first test checks that the most recently opened window is focused.\r
299 Afterwards, the command <tt>focus left</tt> is issued and it is verified that the\r
300 middle window now has focus.</p></div>\r
301 <div class="paragraph"><p>Note that this is not a comprehensive test of the <tt>focus</tt> command&#8201;&#8212;&#8201;we would\r
302 have to test wrapping, focus when using a more complex layout, focusing the\r
303 parent/child containers, etc. But that is not the point of this testcase.\r
304 Instead, we just want to know if <tt>$x&#8594;input_focus</tt> corresponds with what we are\r
305 expecting. If not, something is completely wrong with the test environment and\r
306 this trivial test will fail.</p></div>\r
307 <div class="listingblock">\r
308 <div class="title">t/11-goto.t: Test that the feature does not work (yet)</div>\r
309 <div class="content">\r
310 <pre><tt>#####################################################################\r
311 # Now goto a mark which does not exist\r
312 #####################################################################\r
313 \r
314 my $random_mark = mktemp('mark.XXXXXX');\r
315 \r
316 $focus = focus_after(qq|[con_mark="$random_mark"] focus|);\r
317 is($focus, $mid-&gt;id, "focus unchanged");</tt></pre>\r
318 </div></div>\r
319 <div class="paragraph"><p>Syntax hint: The qq keyword is the interpolating quote operator. It lets you\r
320 chose a quote character (in this case the <tt>|</tt> character, a pipe). This makes\r
321 having double quotes in our string easy.</p></div>\r
322 <div class="paragraph"><p>In this new major section, a random mark (mark is an identifier for a window,\r
323 see "VIM-like marks" in the i3 User’s Guide) will be generated. Afterwards, we\r
324 test that trying to focus that mark will not do anything. This is important: Do\r
325 not only test that using a feature has the expected outcome, but also test that\r
326 using it without properly initializing it does no harm. This command could for\r
327 example have changed focus anyways (a bug) or crash i3 (obviously a bug).</p></div>\r
328 <div class="listingblock">\r
329 <div class="title">t/11-goto.t: Test that the feature does work</div>\r
330 <div class="content">\r
331 <pre><tt>cmd "mark $random_mark";\r
332 \r
333 $focus = focus_after('focus left');\r
334 is($focus, $top-&gt;id, "Top window focused");\r
335 \r
336 $focus = focus_after(qq|[con_mark="$random_mark"] focus|);\r
337 is($focus, $mid-&gt;id, "goto worked");</tt></pre>\r
338 </div></div>\r
339 <div class="paragraph"><p>Remember: Focus was on the middle window (we verified that earlier in "Test\r
340 assumptions"). We now mark the middle window with our randomly generated mark.\r
341 Afterwards, we switch focus away from the middle window to be able to tell if\r
342 focusing it via its mark will work. If the test works, the goto command seems\r
343 to be working.</p></div>\r
344 <div class="listingblock">\r
345 <div class="title">t/11-goto.t: Test corner case</div>\r
346 <div class="content">\r
347 <pre><tt># check that we can specify multiple criteria\r
348 \r
349 $focus = focus_after('focus left');\r
350 is($focus, $top-&gt;id, "Top window focused");\r
351 \r
352 $focus = focus_after(qq|[con_mark="$random_mark" con_mark="$random_mark"] focus|);\r
353 is($focus, $mid-&gt;id, "goto worked");</tt></pre>\r
354 </div></div>\r
355 <div class="paragraph"><p>Now we test the same feature, but specifying the mark twice in the command.\r
356 This should have no effect, but let’s be sure: test it and see if things go\r
357 wrong.</p></div>\r
358 <div class="listingblock">\r
359 <div class="title">t/11-goto.t: Test second code path</div>\r
360 <div class="content">\r
361 <pre><tt>#####################################################################\r
362 # Check whether the focus command will switch to a different\r
363 # workspace if necessary\r
364 #####################################################################\r
365 \r
366 my $tmp2 = fresh_workspace;\r
367 \r
368 is(focused_ws(), $tmp2, 'tmp2 now focused');\r
369 \r
370 cmd qq|[con_mark="$random_mark"] focus|;\r
371 \r
372 is(focused_ws(), $tmp, 'tmp now focused');</tt></pre>\r
373 </div></div>\r
374 <div class="paragraph"><p>This part of the test checks that focusing windows by mark works across\r
375 workspaces. It uses i3test&#8217;s <tt>focused_ws</tt> function to get the current\r
376 workspace.</p></div>\r
377 <div class="listingblock">\r
378 <div class="title">t/11-goto.t: Test second code path</div>\r
379 <div class="content">\r
380 <pre><tt>done_testing;</tt></pre>\r
381 </div></div>\r
382 <div class="paragraph"><p>The end of every testcase has to contain the <tt>done_testing</tt> line. This tells\r
383 <tt>complete-run.pl</tt> that the test was finished successfully. If it does not\r
384 occur, the test might have crashed during execution&#8201;&#8212;&#8201;some of the reasons why\r
385 that could happen are bugs in the used modules, bugs in the testcase itself or\r
386 an i3 crash resulting in the testcase being unable to communicate with i3 via\r
387 IPC anymore.</p></div>\r
388 </div>\r
389 </div>\r
390 <div class="sect1">\r
391 <h2 id="i3_sync">4. Appendix A: The i3 sync protocol</h2>\r
392 <div class="sectionbody">\r
393 <div class="paragraph"><p>Consider the following situation: You open two windows in your testcase, then\r
394 you use <tt>focus left</tt> and want to verify that the X11 focus has been updated\r
395 properly. Sounds simple, right? Let’s assume you use this straight-forward\r
396 implementation:</p></div>\r
397 <div class="listingblock">\r
398 <div class="title">Racey focus testcase</div>\r
399 <div class="content">\r
400 <pre><tt>my $left = open_window($x);\r
401 my $right = open_window($x);\r
402 cmd 'focus left';\r
403 is($x-&gt;input_focus, $left-&gt;id, 'left window focused');</tt></pre>\r
404 </div></div>\r
405 <div class="paragraph"><p>However, the test fails. Sometimes. Apparantly, there is a race condition in\r
406 your test. If you think about it, this is because you are using two different\r
407 pieces of software: You tell i3 to update focus, i3 confirms that, and then you\r
408 ask X11 to give you the current focus. There is a certain time i3 needs to\r
409 update the X11 state. If the testcase gets CPU time before X11 processed i3&#8217;s\r
410 requests, the test will fail.</p></div>\r
411 <div class="imageblock">\r
412 <div class="content">\r
413 <img src="i3-sync.png" alt="Diagram of the race condition" />\r
414 </div>\r
415 <div class="title">Figure 1. Diagram of the race condition</div>\r
416 </div>\r
417 <div class="paragraph"><p>One way to "solve" this would be to add <tt>sleep 0.5;</tt> after the <tt>cmd</tt> call.\r
418 After 0.5 seconds it should be safe to assume that focus has been updated,\r
419 right?</p></div>\r
420 <div class="paragraph"><p>In practice, this usually works. However, it has several problems:</p></div>\r
421 <div class="olist arabic"><ol class="arabic">\r
422 <li>\r
423 <p>\r
424 This is obviously not a clean solution, but a workaround. Ugly.\r
425 </p>\r
426 </li>\r
427 <li>\r
428 <p>\r
429 On very slow machines, this might not work. Unlikely, but in different\r
430    situations (a delay to wait for i3 to startup) the necessary time is much\r
431    harder to guess, even for fast machines.\r
432 </p>\r
433 </li>\r
434 <li>\r
435 <p>\r
436 This <strong>wastes a lot of time</strong>. Usually, your computer is much faster than 0.5s\r
437    to update the status. However, sometimes, it might take 0.4s, so we can’t\r
438    make it <tt>sleep 0.1</tt>.\r
439 </p>\r
440 </li>\r
441 </ol></div>\r
442 <div class="paragraph"><p>To illustrate how grave the problem with wasting time actually is: Before\r
443 removing all sleeps from the testsuite, a typical run using 4 separate X\r
444 servers took around 50 seconds on my machine. After removing all the sleeps,\r
445 we achieved times of about 25 seconds. This is very significant and influences\r
446 the way you think about tests&#8201;&#8212;&#8201;the faster they are, the more likely you are\r
447 to check whether everything still works quite often (which you should).</p></div>\r
448 <div class="paragraph"><p>What I am trying to say is: Delays adds up quickly and make the test suite\r
449 less robust.</p></div>\r
450 <div class="paragraph"><p>The real solution for this problem is a mechanism which I call "the i3 sync\r
451 protocol". The idea is to send a request (which does not modify state) via X11\r
452 to i3 which will then be answered. Due to the request&#8217;s position in the event\r
453 queue (<strong>after</strong> all previous events), you can be sure that by the time you\r
454 receive the reply, all other events have been dealt with by i3 (and, more\r
455 importantly, X11).</p></div>\r
456 <div class="imageblock">\r
457 <div class="content">\r
458 <img src="i3-sync-working.png" alt="Diagram of the i3 sync solution" />\r
459 </div>\r
460 <div class="title">Figure 2. Diagram of the i3 sync solution</div>\r
461 </div>\r
462 <div class="sect2">\r
463 <h3 id="_implementation_details">4.1. Implementation details</h3>\r
464 <div class="paragraph"><p>The client which wants to sync with i3 initiates the protocol by sending a\r
465 ClientMessage to the X11 root window:</p></div>\r
466 <div class="listingblock">\r
467 <div class="title">Send ClientMessage</div>\r
468 <div class="content">\r
469 <pre><tt># Generate a ClientMessage, see xcb_client_message_t\r
470 my $msg = pack "CCSLLLLLLL",\r
471     CLIENT_MESSAGE, # response_type\r
472     32,     # format\r
473     0,      # sequence\r
474     $root,  # destination window\r
475     $x-&gt;atom(name =&gt; 'I3_SYNC')-&gt;id,\r
476 \r
477     $_sync_window-&gt;id,    # data[0]: our own window id\r
478     $myrnd, # data[1]: a random value to identify the request\r
479     0,\r
480     0,\r
481     0;\r
482 \r
483 # Send it to the root window -- since i3 uses the SubstructureRedirect\r
484 # event mask, it will get the ClientMessage.\r
485 $x-&gt;send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);</tt></pre>\r
486 </div></div>\r
487 <div class="paragraph"><p>i3 will then reply with the same ClientMessage, sent to the window specified in\r
488 <tt>data[0]</tt>. In the reply, <tt>data[0]</tt> and <tt>data[1]</tt> are exactly the same as in the\r
489 request. You should use a random value in <tt>data[1]</tt> and check that you received\r
490 the same one when getting the reply.</p></div>\r
491 </div>\r
492 </div>\r
493 </div>\r
494 <div class="sect1">\r
495 <h2 id="_appendix_b_socket_activation">5. Appendix B: Socket activation</h2>\r
496 <div class="sectionbody">\r
497 <div class="paragraph"><p>Socket activation is a mechanism which was made popular by systemd, an init\r
498 replacement. It basically describes creating a listening socket before starting\r
499 a program.  systemd will invoke the program only when an actual connection to\r
500 the socket is made, hence the term socket activation.</p></div>\r
501 <div class="paragraph"><p>The interesting part of this (in the i3 context) is that you can very precisely\r
502 detect when the program is ready (finished its initialization).</p></div>\r
503 <div class="sect2">\r
504 <h3 id="_preparing_the_listening_socket">5.1. Preparing the listening socket</h3>\r
505 <div class="paragraph"><p><tt>complete-run.pl</tt> will create a listening UNIX socket which it will then pass\r
506 to i3. This socket will be used by i3 as an additional IPC socket, just like\r
507 the one it will create on its own. Passing the socket happens implicitly\r
508 because children will inherit the parent’s sockets when fork()ing and sockets\r
509 will continue to exist after an exec() call (unless CLOEXEC is set of course).</p></div>\r
510 <div class="paragraph"><p>The only explicit things <tt>complete-run.pl</tt> has to do is setting the <tt>LISTEN_FDS</tt>\r
511 environment variable to the number of sockets which exist (1 in our case) and\r
512 setting the <tt>LISTEN_PID</tt> environment variable to the current process ID. Both\r
513 variables are necessary so that the program (i3) knows how many sockets it\r
514 should use and if the environment variable is actually intended for it. i3 will\r
515 then start looking for sockets at file descriptor 3 (since 0, 1 and 2 are used\r
516 for stdin, stdout and stderr, respectively).</p></div>\r
517 <div class="paragraph"><p>The actual Perl code which sets up the socket, fork()s, makes sure the socket\r
518 has file descriptor 3 and sets up the environment variables follows (shortened\r
519 a bit):</p></div>\r
520 <div class="listingblock">\r
521 <div class="title">Setup socket and environment</div>\r
522 <div class="content">\r
523 <pre><tt>my $socket = IO::Socket::UNIX-&gt;new(\r
524     Listen =&gt; 1,\r
525     Local =&gt; $args{unix_socket_path},\r
526 );\r
527 \r
528 my $pid = fork;\r
529 if ($pid == 0) {\r
530     $ENV{LISTEN_PID} = $$;\r
531     $ENV{LISTEN_FDS} = 1;\r
532 \r
533     # Only pass file descriptors 0 (stdin), 1 (stdout),\r
534     # 2 (stderr) and 3 (socket) to the child.\r
535     $^F = 3;\r
536 \r
537     # If the socket does not use file descriptor 3 by chance\r
538     # already, we close fd 3 and dup2() the socket to 3.\r
539     if (fileno($socket) != 3) {\r
540         POSIX::close(3);\r
541         POSIX::dup2(fileno($socket), 3);\r
542     }\r
543 \r
544     exec "/usr/bin/i3";\r
545 }</tt></pre>\r
546 </div></div>\r
547 </div>\r
548 <div class="sect2">\r
549 <h3 id="_waiting_for_a_reply">5.2. Waiting for a reply</h3>\r
550 <div class="paragraph"><p>In the parent process, we want to know when i3 is ready to answer our IPC\r
551 requests and handle our windows. Therefore, after forking, we immediately close\r
552 the listening socket (i3 will handle this side of the socket) and connect to it\r
553 (remember, we are talking about a named UNIX socket) as a client. This connect\r
554 call will immediately succeed because the kernel buffers it. Then, we send a\r
555 request (of type GET_TREE, but that is not really relevant). Writing data to\r
556 the socket will also succeed immediately because, again, the kernel buffers it\r
557 (only up to a certain amount of data of course).</p></div>\r
558 <div class="paragraph"><p>Afterwards, we just blockingly wait until we get an answer. In the child\r
559 process, i3 will setup the listening socket in its event loop. Immediately\r
560 after actually starting the event loop, it will notice a new client connecting\r
561 (the parent process) and handle its request. Since all initialization has been\r
562 completed successfully by the time the event loop is entered, we can now assume\r
563 that i3 is ready.</p></div>\r
564 </div>\r
565 <div class="sect2">\r
566 <h3 id="_timing_and_conclusion">5.3. Timing and conclusion</h3>\r
567 <div class="paragraph"><p>A beautiful feature of this mechanism is that it does not depend on timing. It\r
568 does not matter when the child process gets CPU time or when the parent process\r
569 gets CPU time. On heavily loaded machines (or machines with multiple CPUs,\r
570 cores or unreliable schedulers), this makes waiting for i3 much more robust.</p></div>\r
571 <div class="paragraph"><p>Before using socket activation, we typically used a <tt>sleep(1)</tt> and hoped that\r
572 i3 was initialized by that time. Of course, this breaks on some (slow)\r
573 computers and wastes a lot of time on faster computers. By using socket\r
574 activation, we decreased the total amount of time necessary to run all tests\r
575 (72 files at the time of writing) from &gt; 100 seconds to 16 seconds. This makes\r
576 it significantly more attractive to run the test suite more often (or at all)\r
577 during development.</p></div>\r
578 <div class="paragraph"><p>An alternative approach to using socket activation is polling for the existance\r
579 of the IPC socket and connecting to it. While this might be slightly easier to\r
580 implement, it wastes CPU time and is considerably uglier than this solution\r
581 :). After all, <tt>lib/SocketActivation.pm</tt> contains only 54 SLOC.</p></div>\r
582 </div>\r
583 </div>\r
584 </div>\r
585 </div>\r
586 <div id="footnotes"><hr /></div>\r
587 <div id="footer" lang="de">\r
588 © 2009-2011 Michael Stapelberg, <a href="/impress.html">Impressum</a>\r
589 </div>\r
590 </body>\r
591 </html>\r