runner.pm 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  1. #***************************************************************************
  2. # _ _ ____ _
  3. # Project ___| | | | _ \| |
  4. # / __| | | | |_) | |
  5. # | (__| |_| | _ <| |___
  6. # \___|\___/|_| \_\_____|
  7. #
  8. # Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. #
  10. # This software is licensed as described in the file COPYING, which
  11. # you should have received as part of this distribution. The terms
  12. # are also available at https://curl.se/docs/copyright.html.
  13. #
  14. # You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. # copies of the Software, and permit persons to whom the Software is
  16. # furnished to do so, under the terms of the COPYING file.
  17. #
  18. # This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. # KIND, either express or implied.
  20. #
  21. # SPDX-License-Identifier: curl
  22. #
  23. ###########################################################################
  24. # This module contains entry points to run a single test. runner_init
  25. # determines whether they will run in a separate process or in the process of
  26. # the caller. The relevant interface is asynchronous so it will work in either
  27. # case. Program arguments are marshalled and then written to the end of a pipe
  28. # (in controlleripccall) which is later read from and the arguments
  29. # unmarshalled (in ipcrecv) before the desired function is called normally.
  30. # The function return values are then marshalled and written into another pipe
  31. # (again in ipcrecv) when is later read from and unmarshalled (in runnerar)
  32. # before being returned to the caller.
  33. package runner;
  34. use strict;
  35. use warnings;
  36. use 5.006;
  37. BEGIN {
  38. use base qw(Exporter);
  39. our @EXPORT = qw(
  40. checktestcmd
  41. prepro
  42. readtestkeywords
  43. restore_test_env
  44. runner_init
  45. runnerac_clearlocks
  46. runnerac_shutdown
  47. runnerac_stopservers
  48. runnerac_test_preprocess
  49. runnerac_test_run
  50. runnerar
  51. runnerar_ready
  52. stderrfilename
  53. stdoutfilename
  54. $DBGCURL
  55. $gdb
  56. $gdbthis
  57. $gdbxwin
  58. $shallow
  59. $tortalloc
  60. $valgrind_logfile
  61. $valgrind_tool
  62. );
  63. # these are for debugging only
  64. our @EXPORT_OK = qw(
  65. singletest_preprocess
  66. );
  67. }
  68. use B qw(
  69. svref_2object
  70. );
  71. use Storable qw(
  72. freeze
  73. thaw
  74. );
  75. use pathhelp qw(
  76. exe_ext
  77. );
  78. use processhelp qw(
  79. portable_sleep
  80. );
  81. use servers qw(
  82. checkcmd
  83. clearlocks
  84. initserverconfig
  85. serverfortest
  86. stopserver
  87. stopservers
  88. subvariables
  89. );
  90. use getpart;
  91. use globalconfig;
  92. use testutil qw(
  93. clearlogs
  94. logmsg
  95. runclient
  96. shell_quote
  97. subbase64
  98. subnewlines
  99. );
  100. use valgrind;
  101. #######################################################################
  102. # Global variables set elsewhere but used only by this package
  103. # These may only be set *before* runner_init is called
  104. our $DBGCURL=$CURL; #"../src/.libs/curl"; # alternative for debugging
  105. our $valgrind_logfile="--log-file"; # the option name for valgrind >=3
  106. our $valgrind_tool="--tool=memcheck";
  107. our $gdb = checktestcmd("gdb");
  108. our $gdbthis = 0; # run test case with debugger (gdb or lldb)
  109. our $gdbxwin; # use windowed gdb when using gdb
  110. # torture test variables
  111. our $shallow;
  112. our $tortalloc;
  113. # local variables
  114. my %oldenv; # environment variables before test is started
  115. my $UNITDIR="./unit";
  116. my $CURLLOG="$LOGDIR/commands.log"; # all command lines run
  117. my $defserverlogslocktimeout = 5; # timeout to await server logs lock removal
  118. my $defpostcommanddelay = 0; # delay between command and postcheck sections
  119. my $multiprocess; # nonzero with a separate test runner process
  120. # pipes
  121. my $runnerr; # pipe that runner reads from
  122. my $runnerw; # pipe that runner writes to
  123. # per-runner variables, indexed by runner ID; these are used by controller only
  124. my %controllerr; # pipe that controller reads from
  125. my %controllerw; # pipe that controller writes to
  126. # redirected stdout/stderr to these files
  127. sub stdoutfilename {
  128. my ($logdir, $testnum)=@_;
  129. return "$logdir/stdout$testnum";
  130. }
  131. sub stderrfilename {
  132. my ($logdir, $testnum)=@_;
  133. return "$logdir/stderr$testnum";
  134. }
  135. #######################################################################
  136. # Initialize the runner and prepare it to run tests
  137. # The runner ID returned by this function must be passed into the other
  138. # runnerac_* functions
  139. # Called by controller
  140. sub runner_init {
  141. my ($logdir, $jobs)=@_;
  142. $multiprocess = !!$jobs;
  143. # enable memory debugging if curl is compiled with it
  144. $ENV{'CURL_MEMDEBUG'} = "$logdir/$MEMDUMP";
  145. $ENV{'CURL_ENTROPY'}="12345678";
  146. $ENV{'CURL_FORCETIME'}=1; # for debug NTLM magic
  147. $ENV{'CURL_GLOBAL_INIT'}=1; # debug curl_global_init/cleanup use
  148. $ENV{'HOME'}=$pwd;
  149. $ENV{'CURL_HOME'}=$ENV{'HOME'};
  150. $ENV{'XDG_CONFIG_HOME'}=$ENV{'HOME'};
  151. $ENV{'COLUMNS'}=79; # screen width!
  152. # Incorporate the $logdir into the random seed and re-seed the PRNG.
  153. # This gives each runner a unique yet consistent seed which provides
  154. # more unique port number selection in each runner, yet is deterministic
  155. # across runs.
  156. $randseed += unpack('%16C*', $logdir);
  157. srand $randseed;
  158. # create pipes for communication with runner
  159. my ($thisrunnerr, $thiscontrollerw, $thiscontrollerr, $thisrunnerw);
  160. pipe $thisrunnerr, $thiscontrollerw;
  161. pipe $thiscontrollerr, $thisrunnerw;
  162. my $thisrunnerid;
  163. if($multiprocess) {
  164. # Create a separate process in multiprocess mode
  165. my $child = fork();
  166. if(0 == $child) {
  167. # TODO: set up better signal handlers
  168. $SIG{INT} = 'IGNORE';
  169. $SIG{TERM} = 'IGNORE';
  170. eval {
  171. # some msys2 perl versions don't define SIGUSR1
  172. $SIG{USR1} = 'IGNORE';
  173. };
  174. $thisrunnerid = $$;
  175. print "Runner $thisrunnerid starting\n" if($verbose);
  176. # Here we are the child (runner).
  177. close($thiscontrollerw);
  178. close($thiscontrollerr);
  179. $runnerr = $thisrunnerr;
  180. $runnerw = $thisrunnerw;
  181. # Set this directory as ours
  182. $LOGDIR = $logdir;
  183. mkdir("$LOGDIR/$PIDDIR", 0777);
  184. mkdir("$LOGDIR/$LOCKDIR", 0777);
  185. # Initialize various server variables
  186. initserverconfig();
  187. # handle IPC calls
  188. event_loop();
  189. # Can't rely on logmsg here in case it's buffered
  190. print "Runner $thisrunnerid exiting\n" if($verbose);
  191. # To reach this point, either the controller has sent
  192. # runnerac_stopservers() and runnerac_shutdown() or we have called
  193. # runnerabort(). In both cases, there are no more of our servers
  194. # running and we can safely exit.
  195. exit 0;
  196. }
  197. # Here we are the parent (controller).
  198. close($thisrunnerw);
  199. close($thisrunnerr);
  200. $thisrunnerid = $child;
  201. } else {
  202. # Create our pid directory
  203. mkdir("$LOGDIR/$PIDDIR", 0777);
  204. # Don't create a separate process
  205. $thisrunnerid = "integrated";
  206. }
  207. $controllerw{$thisrunnerid} = $thiscontrollerw;
  208. $runnerr = $thisrunnerr;
  209. $runnerw = $thisrunnerw;
  210. $controllerr{$thisrunnerid} = $thiscontrollerr;
  211. return $thisrunnerid;
  212. }
  213. #######################################################################
  214. # Loop to execute incoming IPC calls until the shutdown call
  215. sub event_loop {
  216. while () {
  217. if(ipcrecv()) {
  218. last;
  219. }
  220. }
  221. }
  222. #######################################################################
  223. # Check for a command in the PATH of the machine running curl.
  224. #
  225. sub checktestcmd {
  226. my ($cmd)=@_;
  227. my @testpaths=("$LIBDIR/.libs", "$LIBDIR");
  228. return checkcmd($cmd, @testpaths);
  229. }
  230. # See if Valgrind should actually be used
  231. sub use_valgrind {
  232. if($valgrind) {
  233. my @valgrindoption = getpart("verify", "valgrind");
  234. if((!@valgrindoption) || ($valgrindoption[0] !~ /disable/)) {
  235. return 1;
  236. }
  237. }
  238. return 0;
  239. }
  240. # Massage the command result code into a useful form
  241. sub normalize_cmdres {
  242. my $cmdres = $_[0];
  243. my $signal_num = $cmdres & 127;
  244. my $dumped_core = $cmdres & 128;
  245. if(!$anyway && ($signal_num || $dumped_core)) {
  246. $cmdres = 1000;
  247. }
  248. else {
  249. $cmdres >>= 8;
  250. $cmdres = (2000 + $signal_num) if($signal_num && !$cmdres);
  251. }
  252. return ($cmdres, $dumped_core);
  253. }
  254. # 'prepro' processes the input array and replaces %-variables in the array
  255. # etc. Returns the processed version of the array
  256. sub prepro {
  257. my $testnum = shift;
  258. my (@entiretest) = @_;
  259. my $show = 1;
  260. my @out;
  261. my $data_crlf;
  262. my @pshow;
  263. my @altshow;
  264. my $plvl;
  265. my $line;
  266. for my $s (@entiretest) {
  267. my $f = $s;
  268. $line++;
  269. if($s =~ /^ *%if (.*)/) {
  270. my $cond = $1;
  271. my $rev = 0;
  272. if($cond =~ /^!(.*)/) {
  273. $cond = $1;
  274. $rev = 1;
  275. }
  276. $rev ^= $feature{$cond} ? 1 : 0;
  277. push @pshow, $show; # push the previous state
  278. $plvl++;
  279. if($show) {
  280. # only if this was showing before we can allow the alternative
  281. # to go showing as well
  282. push @altshow, $rev ^ 1; # push the reversed show state
  283. }
  284. else {
  285. push @altshow, 0; # the alt should still hide
  286. }
  287. if($show) {
  288. # we only allow show if already showing
  289. $show = $rev;
  290. }
  291. next;
  292. }
  293. elsif($s =~ /^ *%else/) {
  294. if(!$plvl) {
  295. print STDERR "error: test$testnum:$line: %else no %if\n";
  296. last;
  297. }
  298. $show = pop @altshow;
  299. push @altshow, $show; # put it back for consistency
  300. next;
  301. }
  302. elsif($s =~ /^ *%endif/) {
  303. if(!$plvl--) {
  304. print STDERR "error: test$testnum:$line: %endif had no %if\n";
  305. last;
  306. }
  307. $show = pop @pshow;
  308. pop @altshow; # not used here but we must pop it
  309. next;
  310. }
  311. if($show) {
  312. # The processor does CRLF replacements in the <data*> sections if
  313. # necessary since those parts might be read by separate servers.
  314. if($s =~ /^ *<data(.*)\>/) {
  315. if($1 =~ /crlf="yes"/ ||
  316. ($feature{"hyper"} && ($keywords{"HTTP"} || $keywords{"HTTPS"}))) {
  317. $data_crlf = 1;
  318. }
  319. }
  320. elsif(($s =~ /^ *<\/data/) && $data_crlf) {
  321. $data_crlf = 0;
  322. }
  323. subvariables(\$s, $testnum, "%");
  324. subbase64(\$s);
  325. subnewlines(0, \$s) if($data_crlf);
  326. push @out, $s;
  327. }
  328. }
  329. return @out;
  330. }
  331. #######################################################################
  332. # Load test keywords into %keywords hash
  333. #
  334. sub readtestkeywords {
  335. my @info_keywords = getpart("info", "keywords");
  336. # Clear the list of keywords from the last test
  337. %keywords = ();
  338. for my $k (@info_keywords) {
  339. chomp $k;
  340. $keywords{$k} = 1;
  341. }
  342. }
  343. #######################################################################
  344. # Return a list of log locks that still exist
  345. #
  346. sub logslocked {
  347. opendir(my $lockdir, "$LOGDIR/$LOCKDIR");
  348. my @locks;
  349. foreach (readdir $lockdir) {
  350. if(/^(.*)\.lock$/) {
  351. push @locks, $1;
  352. }
  353. }
  354. return @locks;
  355. }
  356. #######################################################################
  357. # Memory allocation test and failure torture testing.
  358. #
  359. sub torture {
  360. my ($testcmd, $testnum, $gdbline) = @_;
  361. # remove memdump first to be sure we get a new nice and clean one
  362. unlink("$LOGDIR/$MEMDUMP");
  363. # First get URL from test server, ignore the output/result
  364. runclient($testcmd);
  365. logmsg " CMD: $testcmd\n" if($verbose);
  366. # memanalyze -v is our friend, get the number of allocations made
  367. my $count=0;
  368. my @out = `$memanalyze -v "$LOGDIR/$MEMDUMP"`;
  369. for(@out) {
  370. if(/^Operations: (\d+)/) {
  371. $count = $1;
  372. last;
  373. }
  374. }
  375. if(!$count) {
  376. logmsg " found no functions to make fail\n";
  377. return 0;
  378. }
  379. my @ttests = (1 .. $count);
  380. if($shallow && ($shallow < $count)) {
  381. my $discard = scalar(@ttests) - $shallow;
  382. my $percent = sprintf("%.2f%%", $shallow * 100 / scalar(@ttests));
  383. logmsg " $count functions found, but only fail $shallow ($percent)\n";
  384. while($discard) {
  385. my $rm;
  386. do {
  387. # find a test to discard
  388. $rm = rand(scalar(@ttests));
  389. } while(!$ttests[$rm]);
  390. $ttests[$rm] = undef;
  391. $discard--;
  392. }
  393. }
  394. else {
  395. logmsg " $count functions to make fail\n";
  396. }
  397. for (@ttests) {
  398. my $limit = $_;
  399. my $fail;
  400. my $dumped_core;
  401. if(!defined($limit)) {
  402. # --shallow can undefine them
  403. next;
  404. }
  405. if($tortalloc && ($tortalloc != $limit)) {
  406. next;
  407. }
  408. if($verbose) {
  409. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
  410. localtime(time());
  411. my $now = sprintf("%02d:%02d:%02d ", $hour, $min, $sec);
  412. logmsg "Fail function no: $limit at $now\r";
  413. }
  414. # make the memory allocation function number $limit return failure
  415. $ENV{'CURL_MEMLIMIT'} = $limit;
  416. # remove memdump first to be sure we get a new nice and clean one
  417. unlink("$LOGDIR/$MEMDUMP");
  418. my $cmd = $testcmd;
  419. if($valgrind && !$gdbthis) {
  420. my @valgrindoption = getpart("verify", "valgrind");
  421. if((!@valgrindoption) || ($valgrindoption[0] !~ /disable/)) {
  422. my $valgrindcmd = "$valgrind ";
  423. $valgrindcmd .= "$valgrind_tool " if($valgrind_tool);
  424. $valgrindcmd .= "--quiet --leak-check=yes ";
  425. $valgrindcmd .= "--suppressions=$srcdir/valgrind.supp ";
  426. # $valgrindcmd .= "--gen-suppressions=all ";
  427. $valgrindcmd .= "--num-callers=16 ";
  428. $valgrindcmd .= "${valgrind_logfile}=$LOGDIR/valgrind$testnum";
  429. $cmd = "$valgrindcmd $testcmd";
  430. }
  431. }
  432. logmsg "*** Function number $limit is now set to fail ***\n" if($gdbthis);
  433. my $ret = 0;
  434. if($gdbthis) {
  435. runclient($gdbline);
  436. }
  437. else {
  438. $ret = runclient($cmd);
  439. }
  440. #logmsg "$_ Returned " . ($ret >> 8) . "\n";
  441. # Now clear the variable again
  442. delete $ENV{'CURL_MEMLIMIT'} if($ENV{'CURL_MEMLIMIT'});
  443. if(-r "core") {
  444. # there's core file present now!
  445. logmsg " core dumped\n";
  446. $dumped_core = 1;
  447. $fail = 2;
  448. }
  449. if($valgrind) {
  450. my @e = valgrindparse("$LOGDIR/valgrind$testnum");
  451. if(@e && $e[0]) {
  452. if($automakestyle) {
  453. logmsg "FAIL: torture $testnum - valgrind\n";
  454. }
  455. else {
  456. logmsg " valgrind ERROR ";
  457. logmsg @e;
  458. }
  459. $fail = 1;
  460. }
  461. }
  462. # verify that it returns a proper error code, doesn't leak memory
  463. # and doesn't core dump
  464. if(($ret & 255) || ($ret >> 8) >= 128) {
  465. logmsg " system() returned $ret\n";
  466. $fail=1;
  467. }
  468. else {
  469. my @memdata=`$memanalyze "$LOGDIR/$MEMDUMP"`;
  470. my $leak=0;
  471. for(@memdata) {
  472. if($_ ne "") {
  473. # well it could be other memory problems as well, but
  474. # we call it leak for short here
  475. $leak=1;
  476. }
  477. }
  478. if($leak) {
  479. logmsg "** MEMORY FAILURE\n";
  480. logmsg @memdata;
  481. logmsg `$memanalyze -l "$LOGDIR/$MEMDUMP"`;
  482. $fail = 1;
  483. }
  484. }
  485. if($fail) {
  486. logmsg " $testnum: torture FAILED: function number $limit in test.\n",
  487. " invoke with \"-t$limit\" to repeat this single case.\n";
  488. stopservers($verbose);
  489. return 1;
  490. }
  491. }
  492. logmsg "\n" if($verbose);
  493. logmsg "torture OK\n";
  494. return 0;
  495. }
  496. #######################################################################
  497. # restore environment variables that were modified in test
  498. sub restore_test_env {
  499. my $deleteoldenv = $_[0]; # 1 to delete the saved contents after restore
  500. foreach my $var (keys %oldenv) {
  501. if($oldenv{$var} eq 'notset') {
  502. delete $ENV{$var} if($ENV{$var});
  503. }
  504. else {
  505. $ENV{$var} = $oldenv{$var};
  506. }
  507. if($deleteoldenv) {
  508. delete $oldenv{$var};
  509. }
  510. }
  511. }
  512. #######################################################################
  513. # Start the servers needed to run this test case
  514. sub singletest_startservers {
  515. my ($testnum, $testtimings) = @_;
  516. # remove old test server files before servers are started/verified
  517. unlink("$LOGDIR/$SERVERCMD");
  518. unlink("$LOGDIR/$SERVERIN");
  519. unlink("$LOGDIR/$PROXYIN");
  520. # timestamp required servers verification start
  521. $$testtimings{"timesrvrini"} = Time::HiRes::time();
  522. my $why;
  523. my $error;
  524. if (!$listonly) {
  525. my @what = getpart("client", "server");
  526. if(!$what[0]) {
  527. warn "Test case $testnum has no server(s) specified";
  528. $why = "no server specified";
  529. $error = -1;
  530. } else {
  531. my $err;
  532. ($why, $err) = serverfortest(@what);
  533. if($err == 1) {
  534. # Error indicates an actual problem starting the server
  535. $error = -2;
  536. } else {
  537. $error = -1;
  538. }
  539. }
  540. }
  541. # timestamp required servers verification end
  542. $$testtimings{"timesrvrend"} = Time::HiRes::time();
  543. return ($why, $error);
  544. }
  545. #######################################################################
  546. # Generate preprocessed test file
  547. sub singletest_preprocess {
  548. my $testnum = $_[0];
  549. # Save a preprocessed version of the entire test file. This allows more
  550. # "basic" test case readers to enjoy variable replacements.
  551. my @entiretest = fulltest();
  552. my $otest = "$LOGDIR/test$testnum";
  553. @entiretest = prepro($testnum, @entiretest);
  554. # save the new version
  555. open(my $fulltesth, ">", "$otest") || die "Failure writing test file";
  556. foreach my $bytes (@entiretest) {
  557. print $fulltesth pack('a*', $bytes) or die "Failed to print '$bytes': $!";
  558. }
  559. close($fulltesth) || die "Failure writing test file";
  560. # in case the process changed the file, reload it
  561. loadtest("$LOGDIR/test${testnum}");
  562. }
  563. #######################################################################
  564. # Set up the test environment to run this test case
  565. sub singletest_setenv {
  566. my @setenv = getpart("client", "setenv");
  567. foreach my $s (@setenv) {
  568. chomp $s;
  569. if($s =~ /([^=]*)(.*)/) {
  570. my ($var, $content) = ($1, $2);
  571. # remember current setting, to restore it once test runs
  572. $oldenv{$var} = ($ENV{$var})?"$ENV{$var}":'notset';
  573. if($content =~ /^=(.*)/) {
  574. # assign it
  575. $content = $1;
  576. if($var =~ /^LD_PRELOAD/) {
  577. if(exe_ext('TOOL') && (exe_ext('TOOL') eq '.exe')) {
  578. logmsg "Skipping LD_PRELOAD due to lack of OS support\n" if($verbose);
  579. next;
  580. }
  581. if($feature{"debug"} || !$has_shared) {
  582. logmsg "Skipping LD_PRELOAD due to no release shared build\n" if($verbose);
  583. next;
  584. }
  585. }
  586. $ENV{$var} = "$content";
  587. logmsg "setenv $var = $content\n" if($verbose);
  588. }
  589. else {
  590. # remove it
  591. delete $ENV{$var} if($ENV{$var});
  592. }
  593. }
  594. }
  595. if($proxy_address) {
  596. $ENV{http_proxy} = $proxy_address;
  597. $ENV{HTTPS_PROXY} = $proxy_address;
  598. }
  599. }
  600. #######################################################################
  601. # Check that test environment is fine to run this test case
  602. sub singletest_precheck {
  603. my $testnum = $_[0];
  604. my $why;
  605. my @precheck = getpart("client", "precheck");
  606. if(@precheck) {
  607. my $cmd = $precheck[0];
  608. chomp $cmd;
  609. if($cmd) {
  610. my @p = split(/ /, $cmd);
  611. if($p[0] !~ /\//) {
  612. # the first word, the command, does not contain a slash so
  613. # we will scan the "improved" PATH to find the command to
  614. # be able to run it
  615. my $fullp = checktestcmd($p[0]);
  616. if($fullp) {
  617. $p[0] = $fullp;
  618. }
  619. $cmd = join(" ", @p);
  620. }
  621. my @o = `$cmd 2> $LOGDIR/precheck-$testnum`;
  622. if($o[0]) {
  623. $why = $o[0];
  624. $why =~ s/[\r\n]//g;
  625. }
  626. elsif($?) {
  627. $why = "precheck command error";
  628. }
  629. logmsg "prechecked $cmd\n" if($verbose);
  630. }
  631. }
  632. return $why;
  633. }
  634. #######################################################################
  635. # Prepare the test environment to run this test case
  636. sub singletest_prepare {
  637. my ($testnum) = @_;
  638. if($feature{"TrackMemory"}) {
  639. unlink("$LOGDIR/$MEMDUMP");
  640. }
  641. unlink("core");
  642. # remove server output logfiles after servers are started/verified
  643. unlink("$LOGDIR/$SERVERIN");
  644. unlink("$LOGDIR/$PROXYIN");
  645. # if this section exists, it might be FTP server instructions:
  646. my @ftpservercmd = getpart("reply", "servercmd");
  647. push @ftpservercmd, "Testnum $testnum\n";
  648. # write the instructions to file
  649. writearray("$LOGDIR/$SERVERCMD", \@ftpservercmd);
  650. # create (possibly-empty) files before starting the test
  651. for my $partsuffix (('', '1', '2', '3', '4')) {
  652. my @inputfile=getpart("client", "file".$partsuffix);
  653. my %fileattr = getpartattr("client", "file".$partsuffix);
  654. my $filename=$fileattr{'name'};
  655. if(@inputfile || $filename) {
  656. if(!$filename) {
  657. logmsg " $testnum: IGNORED: section client=>file has no name attribute\n";
  658. return -1;
  659. }
  660. my $fileContent = join('', @inputfile);
  661. # make directories if needed
  662. my $path = $filename;
  663. # cut off the file name part
  664. $path =~ s/^(.*)\/[^\/]*/$1/;
  665. my @ldparts = split(/\//, $LOGDIR);
  666. my $nparts = @ldparts;
  667. my @parts = split(/\//, $path);
  668. if(join("/", @parts[0..$nparts-1]) eq $LOGDIR) {
  669. # the file is in $LOGDIR/
  670. my $d = shift @parts;
  671. for(@parts) {
  672. $d .= "/$_";
  673. mkdir $d; # 0777
  674. }
  675. }
  676. if (open(my $outfile, ">", "$filename")) {
  677. binmode $outfile; # for crapage systems, use binary
  678. if($fileattr{'nonewline'}) {
  679. # cut off the final newline
  680. chomp($fileContent);
  681. }
  682. print $outfile $fileContent;
  683. close($outfile);
  684. } else {
  685. logmsg "ERROR: cannot write $filename\n";
  686. }
  687. }
  688. }
  689. return 0;
  690. }
  691. #######################################################################
  692. # Run the test command
  693. sub singletest_run {
  694. my ($testnum, $testtimings) = @_;
  695. # get the command line options to use
  696. my ($cmd, @blaha)= getpart("client", "command");
  697. if($cmd) {
  698. # make some nice replace operations
  699. $cmd =~ s/\n//g; # no newlines please
  700. # substitute variables in the command line
  701. }
  702. else {
  703. # there was no command given, use something silly
  704. $cmd="-";
  705. }
  706. my $CURLOUT="$LOGDIR/curl$testnum.out"; # curl output if not stdout
  707. # if stdout section exists, we verify that the stdout contained this:
  708. my $out="";
  709. my %cmdhash = getpartattr("client", "command");
  710. if((!$cmdhash{'option'}) || ($cmdhash{'option'} !~ /no-output/)) {
  711. #We may slap on --output!
  712. if (!partexists("verify", "stdout") ||
  713. ($cmdhash{'option'} && $cmdhash{'option'} =~ /force-output/)) {
  714. $out=" --output $CURLOUT ";
  715. }
  716. }
  717. my @codepieces = getpart("client", "tool");
  718. my $tool="";
  719. if(@codepieces) {
  720. $tool = $codepieces[0];
  721. chomp $tool;
  722. $tool .= exe_ext('TOOL');
  723. }
  724. my $disablevalgrind;
  725. my $CMDLINE="";
  726. my $cmdargs;
  727. my $cmdtype = $cmdhash{'type'} || "default";
  728. my $fail_due_event_based = $run_event_based;
  729. if($cmdtype eq "perl") {
  730. # run the command line prepended with "perl"
  731. $cmdargs ="$cmd";
  732. $CMDLINE = "$perl ";
  733. $tool=$CMDLINE;
  734. $disablevalgrind=1;
  735. }
  736. elsif($cmdtype eq "shell") {
  737. # run the command line prepended with "/bin/sh"
  738. $cmdargs ="$cmd";
  739. $CMDLINE = "/bin/sh ";
  740. $tool=$CMDLINE;
  741. $disablevalgrind=1;
  742. }
  743. elsif(!$tool && !$keywords{"unittest"}) {
  744. # run curl, add suitable command line options
  745. my $inc="";
  746. if((!$cmdhash{'option'}) || ($cmdhash{'option'} !~ /no-include/)) {
  747. $inc = " --include";
  748. }
  749. $cmdargs = "$out$inc ";
  750. if($cmdhash{'option'} && ($cmdhash{'option'} =~ /binary-trace/)) {
  751. $cmdargs .= "--trace $LOGDIR/trace$testnum ";
  752. }
  753. else {
  754. $cmdargs .= "--trace-ascii $LOGDIR/trace$testnum ";
  755. }
  756. $cmdargs .= "--trace-time ";
  757. if($run_event_based) {
  758. $cmdargs .= "--test-event ";
  759. $fail_due_event_based--;
  760. }
  761. $cmdargs .= $cmd;
  762. if ($proxy_address) {
  763. $cmdargs .= " --proxy $proxy_address ";
  764. }
  765. }
  766. else {
  767. $cmdargs = " $cmd"; # $cmd is the command line for the test file
  768. $CURLOUT = stdoutfilename($LOGDIR, $testnum); # sends received data to stdout
  769. # Default the tool to a unit test with the same name as the test spec
  770. if($keywords{"unittest"} && !$tool) {
  771. $tool="unit$testnum";
  772. }
  773. if($tool =~ /^lib/) {
  774. $CMDLINE="$LIBDIR/$tool";
  775. }
  776. elsif($tool =~ /^unit/) {
  777. $CMDLINE="$UNITDIR/$tool";
  778. }
  779. if(! -f $CMDLINE) {
  780. logmsg " $testnum: IGNORED: The tool set in the test case for this: '$tool' does not exist\n";
  781. return (-1, 0, 0, "", "", 0);
  782. }
  783. $DBGCURL=$CMDLINE;
  784. }
  785. if($fail_due_event_based) {
  786. logmsg " $testnum: IGNORED: This test cannot run event based\n";
  787. return (-1, 0, 0, "", "", 0);
  788. }
  789. if($gdbthis) {
  790. # gdb is incompatible with valgrind, so disable it when debugging
  791. # Perhaps a better approach would be to run it under valgrind anyway
  792. # with --db-attach=yes or --vgdb=yes.
  793. $disablevalgrind=1;
  794. }
  795. my @stdintest = getpart("client", "stdin");
  796. if(@stdintest) {
  797. my $stdinfile="$LOGDIR/stdin-for-$testnum";
  798. my %hash = getpartattr("client", "stdin");
  799. if($hash{'nonewline'}) {
  800. # cut off the final newline from the final line of the stdin data
  801. chomp($stdintest[-1]);
  802. }
  803. writearray($stdinfile, \@stdintest);
  804. $cmdargs .= " <$stdinfile";
  805. }
  806. if(!$tool) {
  807. $CMDLINE=shell_quote($CURL);
  808. if((!$cmdhash{'option'}) || ($cmdhash{'option'} !~ /no-q/)) {
  809. $CMDLINE .= " -q";
  810. }
  811. }
  812. if(use_valgrind() && !$disablevalgrind) {
  813. my $valgrindcmd = "$valgrind ";
  814. $valgrindcmd .= "$valgrind_tool " if($valgrind_tool);
  815. $valgrindcmd .= "--quiet --leak-check=yes ";
  816. $valgrindcmd .= "--suppressions=$srcdir/valgrind.supp ";
  817. # $valgrindcmd .= "--gen-suppressions=all ";
  818. $valgrindcmd .= "--num-callers=16 ";
  819. $valgrindcmd .= "${valgrind_logfile}=$LOGDIR/valgrind$testnum";
  820. $CMDLINE = "$valgrindcmd $CMDLINE";
  821. }
  822. $CMDLINE .= "$cmdargs > " . stdoutfilename($LOGDIR, $testnum) .
  823. " 2> " . stderrfilename($LOGDIR, $testnum);
  824. if($verbose) {
  825. logmsg "$CMDLINE\n";
  826. }
  827. open(my $cmdlog, ">", $CURLLOG) || die "Failure writing log file";
  828. print $cmdlog "$CMDLINE\n";
  829. close($cmdlog) || die "Failure writing log file";
  830. my $dumped_core;
  831. my $cmdres;
  832. if($gdbthis) {
  833. my $gdbinit = "$TESTDIR/gdbinit$testnum";
  834. open(my $gdbcmd, ">", "$LOGDIR/gdbcmd") || die "Failure writing gdb file";
  835. if($gdbthis == 1) {
  836. # gdb mode
  837. print $gdbcmd "set args $cmdargs\n";
  838. print $gdbcmd "show args\n";
  839. print $gdbcmd "source $gdbinit\n" if -e $gdbinit;
  840. }
  841. else {
  842. # lldb mode
  843. print $gdbcmd "set args $cmdargs\n";
  844. }
  845. close($gdbcmd) || die "Failure writing gdb file";
  846. }
  847. # Flush output.
  848. $| = 1;
  849. # timestamp starting of test command
  850. $$testtimings{"timetoolini"} = Time::HiRes::time();
  851. # run the command line we built
  852. if ($torture) {
  853. $cmdres = torture($CMDLINE,
  854. $testnum,
  855. "$gdb --directory $LIBDIR " . shell_quote($DBGCURL) . " -x $LOGDIR/gdbcmd");
  856. }
  857. elsif($gdbthis == 1) {
  858. # gdb
  859. my $GDBW = ($gdbxwin) ? "-w" : "";
  860. runclient("$gdb --directory $LIBDIR " . shell_quote($DBGCURL) . " $GDBW -x $LOGDIR/gdbcmd");
  861. $cmdres=0; # makes it always continue after a debugged run
  862. }
  863. elsif($gdbthis == 2) {
  864. # $gdb is "lldb"
  865. print "runs lldb -- $CURL $cmdargs\n";
  866. runclient("lldb -- $CURL $cmdargs");
  867. $cmdres=0; # makes it always continue after a debugged run
  868. }
  869. else {
  870. # Convert the raw result code into a more useful one
  871. ($cmdres, $dumped_core) = normalize_cmdres(runclient("$CMDLINE"));
  872. }
  873. # timestamp finishing of test command
  874. $$testtimings{"timetoolend"} = Time::HiRes::time();
  875. return (0, $cmdres, $dumped_core, $CURLOUT, $tool, use_valgrind() && !$disablevalgrind);
  876. }
  877. #######################################################################
  878. # Clean up after test command
  879. sub singletest_clean {
  880. my ($testnum, $dumped_core, $testtimings)=@_;
  881. if(!$dumped_core) {
  882. if(-r "core") {
  883. # there's core file present now!
  884. $dumped_core = 1;
  885. }
  886. }
  887. if($dumped_core) {
  888. logmsg "core dumped\n";
  889. if(0 && $gdb) {
  890. logmsg "running gdb for post-mortem analysis:\n";
  891. open(my $gdbcmd, ">", "$LOGDIR/gdbcmd2") || die "Failure writing gdb file";
  892. print $gdbcmd "bt\n";
  893. close($gdbcmd) || die "Failure writing gdb file";
  894. runclient("$gdb --directory libtest -x $LOGDIR/gdbcmd2 -batch " . shell_quote($DBGCURL) . " core ");
  895. # unlink("$LOGDIR/gdbcmd2");
  896. }
  897. }
  898. # If a server logs advisor read lock file exists, it is an indication
  899. # that the server has not yet finished writing out all its log files,
  900. # including server request log files used for protocol verification.
  901. # So, if the lock file exists the script waits here a certain amount
  902. # of time until the server removes it, or the given time expires.
  903. my $serverlogslocktimeout = $defserverlogslocktimeout;
  904. my %cmdhash = getpartattr("client", "command");
  905. if($cmdhash{'timeout'}) {
  906. # test is allowed to override default server logs lock timeout
  907. if($cmdhash{'timeout'} =~ /(\d+)/) {
  908. $serverlogslocktimeout = $1 if($1 >= 0);
  909. }
  910. }
  911. if($serverlogslocktimeout) {
  912. my $lockretry = $serverlogslocktimeout * 20;
  913. my @locks;
  914. while((@locks = logslocked()) && $lockretry--) {
  915. portable_sleep(0.05);
  916. }
  917. if(($lockretry < 0) &&
  918. ($serverlogslocktimeout >= $defserverlogslocktimeout)) {
  919. logmsg "Warning: server logs lock timeout ",
  920. "($serverlogslocktimeout seconds) expired (locks: " .
  921. join(", ", @locks) . ")\n";
  922. }
  923. }
  924. # Test harness ssh server does not have this synchronization mechanism,
  925. # this implies that some ssh server based tests might need a small delay
  926. # once that the client command has run to avoid false test failures.
  927. #
  928. # gnutls-serv also lacks this synchronization mechanism, so gnutls-serv
  929. # based tests might need a small delay once that the client command has
  930. # run to avoid false test failures.
  931. my $postcommanddelay = $defpostcommanddelay;
  932. if($cmdhash{'delay'}) {
  933. # test is allowed to specify a delay after command is executed
  934. if($cmdhash{'delay'} =~ /(\d+)/) {
  935. $postcommanddelay = $1 if($1 > 0);
  936. }
  937. }
  938. portable_sleep($postcommanddelay) if($postcommanddelay);
  939. # timestamp removal of server logs advisor read lock
  940. $$testtimings{"timesrvrlog"} = Time::HiRes::time();
  941. # test definition might instruct to stop some servers
  942. # stop also all servers relative to the given one
  943. my @killtestservers = getpart("client", "killserver");
  944. if(@killtestservers) {
  945. foreach my $server (@killtestservers) {
  946. chomp $server;
  947. if(stopserver($server)) {
  948. logmsg " $testnum: killserver FAILED\n";
  949. return 1; # normal error if asked to fail on unexpected alive
  950. }
  951. }
  952. }
  953. return 0;
  954. }
  955. #######################################################################
  956. # Verify that the postcheck succeeded
  957. sub singletest_postcheck {
  958. my ($testnum)=@_;
  959. # run the postcheck command
  960. my @postcheck= getpart("client", "postcheck");
  961. if(@postcheck) {
  962. my $cmd = join("", @postcheck);
  963. chomp $cmd;
  964. if($cmd) {
  965. logmsg "postcheck $cmd\n" if($verbose);
  966. my $rc = runclient("$cmd");
  967. # Must run the postcheck command in torture mode in order
  968. # to clean up, but the result can't be relied upon.
  969. if($rc != 0 && !$torture) {
  970. logmsg " $testnum: postcheck FAILED\n";
  971. return -1;
  972. }
  973. }
  974. }
  975. return 0;
  976. }
  977. ###################################################################
  978. # Get ready to run a single test case
  979. sub runner_test_preprocess {
  980. my ($testnum)=@_;
  981. my %testtimings;
  982. if(clearlogs()) {
  983. logmsg "Warning: log messages were lost\n";
  984. }
  985. # timestamp test preparation start
  986. # TODO: this metric now shows only a portion of the prep time; better would
  987. # be to time singletest_preprocess below instead
  988. $testtimings{"timeprepini"} = Time::HiRes::time();
  989. ###################################################################
  990. # Load test metadata
  991. # ignore any error here--if there were one, it would have been
  992. # caught during the selection phase and this test would not be
  993. # running now
  994. loadtest("${TESTDIR}/test${testnum}");
  995. readtestkeywords();
  996. ###################################################################
  997. # Restore environment variables that were modified in a previous run.
  998. # Test definition may instruct to (un)set environment vars.
  999. restore_test_env(1);
  1000. ###################################################################
  1001. # Start the servers needed to run this test case
  1002. my ($why, $error) = singletest_startservers($testnum, \%testtimings);
  1003. if(!$why) {
  1004. ###############################################################
  1005. # Generate preprocessed test file
  1006. # This must be done after the servers are started so server
  1007. # variables are available for substitution.
  1008. singletest_preprocess($testnum);
  1009. ###############################################################
  1010. # Set up the test environment to run this test case
  1011. singletest_setenv();
  1012. ###############################################################
  1013. # Check that the test environment is fine to run this test case
  1014. if (!$listonly) {
  1015. $why = singletest_precheck($testnum);
  1016. $error = -1;
  1017. }
  1018. }
  1019. return ($why, $error, clearlogs(), \%testtimings);
  1020. }
  1021. ###################################################################
  1022. # Run a single test case with an environment that already been prepared
  1023. # Returns 0=success, -1=skippable failure, -2=permanent error,
  1024. # 1=unskippable test failure, as first integer, plus any log messages,
  1025. # plus more return values when error is 0
  1026. sub runner_test_run {
  1027. my ($testnum)=@_;
  1028. if(clearlogs()) {
  1029. logmsg "Warning: log messages were lost\n";
  1030. }
  1031. #######################################################################
  1032. # Prepare the test environment to run this test case
  1033. my $error = singletest_prepare($testnum);
  1034. if($error) {
  1035. return (-2, clearlogs());
  1036. }
  1037. #######################################################################
  1038. # Run the test command
  1039. my %testtimings;
  1040. my $cmdres;
  1041. my $dumped_core;
  1042. my $CURLOUT;
  1043. my $tool;
  1044. my $usedvalgrind;
  1045. ($error, $cmdres, $dumped_core, $CURLOUT, $tool, $usedvalgrind) = singletest_run($testnum, \%testtimings);
  1046. if($error) {
  1047. return (-2, clearlogs(), \%testtimings);
  1048. }
  1049. #######################################################################
  1050. # Clean up after test command
  1051. $error = singletest_clean($testnum, $dumped_core, \%testtimings);
  1052. if($error) {
  1053. return ($error, clearlogs(), \%testtimings);
  1054. }
  1055. #######################################################################
  1056. # Verify that the postcheck succeeded
  1057. $error = singletest_postcheck($testnum);
  1058. if($error) {
  1059. return ($error, clearlogs(), \%testtimings);
  1060. }
  1061. #######################################################################
  1062. # restore environment variables that were modified
  1063. restore_test_env(0);
  1064. return (0, clearlogs(), \%testtimings, $cmdres, $CURLOUT, $tool, $usedvalgrind);
  1065. }
  1066. # Async call runner_clearlocks
  1067. # Called by controller
  1068. sub runnerac_clearlocks {
  1069. return controlleripccall(\&runner_clearlocks, @_);
  1070. }
  1071. # Async call runner_shutdown
  1072. # This call does NOT generate an IPC response and must be the last IPC call
  1073. # received.
  1074. # Called by controller
  1075. sub runnerac_shutdown {
  1076. my ($runnerid)=$_[0];
  1077. my $err = controlleripccall(\&runner_shutdown, @_);
  1078. # These have no more use
  1079. close($controllerw{$runnerid});
  1080. undef $controllerw{$runnerid};
  1081. close($controllerr{$runnerid});
  1082. undef $controllerr{$runnerid};
  1083. return $err;
  1084. }
  1085. # Async call of runner_stopservers
  1086. # Called by controller
  1087. sub runnerac_stopservers {
  1088. return controlleripccall(\&runner_stopservers, @_);
  1089. }
  1090. # Async call of runner_test_preprocess
  1091. # Called by controller
  1092. sub runnerac_test_preprocess {
  1093. return controlleripccall(\&runner_test_preprocess, @_);
  1094. }
  1095. # Async call of runner_test_run
  1096. # Called by controller
  1097. sub runnerac_test_run {
  1098. return controlleripccall(\&runner_test_run, @_);
  1099. }
  1100. ###################################################################
  1101. # Call an arbitrary function via IPC
  1102. # The first argument is the function reference, the second is the runner ID
  1103. # Returns 0 on success, -1 on error writing to runner
  1104. # Called by controller (indirectly, via a more specific function)
  1105. sub controlleripccall {
  1106. my $funcref = shift @_;
  1107. my $runnerid = shift @_;
  1108. # Get the name of the function from the reference
  1109. my $cv = svref_2object($funcref);
  1110. my $gv = $cv->GV;
  1111. # Prepend the name to the function arguments so it's marshalled along with them
  1112. unshift @_, $gv->NAME;
  1113. # Marshall the arguments into a flat string
  1114. my $margs = freeze \@_;
  1115. # Send IPC call via pipe
  1116. my $err;
  1117. while(! defined ($err = syswrite($controllerw{$runnerid}, (pack "L", length($margs)) . $margs)) || $err <= 0) {
  1118. if((!defined $err && ! $!{EINTR}) || (defined $err && $err == 0)) {
  1119. # Runner has likely died
  1120. return -1;
  1121. }
  1122. # system call was interrupted, probably by ^C; restart it so we stay in sync
  1123. }
  1124. if(!$multiprocess) {
  1125. # Call the remote function here in single process mode
  1126. ipcrecv();
  1127. }
  1128. return 0;
  1129. }
  1130. ###################################################################
  1131. # Receive async response of a previous call via IPC
  1132. # The first return value is the runner ID or undef on error
  1133. # Called by controller
  1134. sub runnerar {
  1135. my ($runnerid) = @_;
  1136. my $err;
  1137. my $datalen;
  1138. while(! defined ($err = sysread($controllerr{$runnerid}, $datalen, 4)) || $err <= 0) {
  1139. if((!defined $err && ! $!{EINTR}) || (defined $err && $err == 0)) {
  1140. # Runner is likely dead and closed the pipe
  1141. return undef;
  1142. }
  1143. # system call was interrupted, probably by ^C; restart it so we stay in sync
  1144. }
  1145. my $len=unpack("L", $datalen);
  1146. my $buf;
  1147. while(! defined ($err = sysread($controllerr{$runnerid}, $buf, $len)) || $err <= 0) {
  1148. if((!defined $err && ! $!{EINTR}) || (defined $err && $err == 0)) {
  1149. # Runner is likely dead and closed the pipe
  1150. return undef;
  1151. }
  1152. # system call was interrupted, probably by ^C; restart it so we stay in sync
  1153. }
  1154. # Decode response values
  1155. my $resarrayref = thaw $buf;
  1156. # First argument is runner ID
  1157. # TODO: remove this; it's unneeded since it's passed in
  1158. unshift @$resarrayref, $runnerid;
  1159. return @$resarrayref;
  1160. }
  1161. ###################################################################
  1162. # Returns runner ID if a response from an async call is ready or error
  1163. # First value is ready, second is error, however an error case shows up
  1164. # as ready in Linux, so you can't trust it.
  1165. # argument is 0 for nonblocking, undef for blocking, anything else for timeout
  1166. # Called by controller
  1167. sub runnerar_ready {
  1168. my ($blocking) = @_;
  1169. my $rin = "";
  1170. my %idbyfileno;
  1171. my $maxfileno=0;
  1172. foreach my $p (keys(%controllerr)) {
  1173. my $fd = fileno($controllerr{$p});
  1174. vec($rin, $fd, 1) = 1;
  1175. $idbyfileno{$fd} = $p; # save the runner ID for each pipe fd
  1176. if($fd > $maxfileno) {
  1177. $maxfileno = $fd;
  1178. }
  1179. }
  1180. $maxfileno || die "Internal error: no runners are available to wait on\n";
  1181. # Wait for any pipe from any runner to be ready
  1182. # This may be interrupted and return EINTR, but this is ignored and the
  1183. # caller will need to later call this function again.
  1184. # TODO: this is relatively slow with hundreds of fds
  1185. my $ein = $rin;
  1186. if(select(my $rout=$rin, undef, my $eout=$ein, $blocking) >= 1) {
  1187. for my $fd (0..$maxfileno) {
  1188. # Return an error condition first in case it's both
  1189. if(vec($eout, $fd, 1)) {
  1190. return (undef, $idbyfileno{$fd});
  1191. }
  1192. if(vec($rout, $fd, 1)) {
  1193. return ($idbyfileno{$fd}, undef);
  1194. }
  1195. }
  1196. die "Internal pipe readiness inconsistency\n";
  1197. }
  1198. return (undef, undef);
  1199. }
  1200. ###################################################################
  1201. # Cleanly abort and exit the runner
  1202. # This uses print since there is no longer any controller to write logs.
  1203. sub runnerabort{
  1204. print "Controller is gone: runner $$ for $LOGDIR exiting\n";
  1205. my ($error, $logs) = runner_stopservers();
  1206. print $logs;
  1207. runner_shutdown();
  1208. }
  1209. ###################################################################
  1210. # Receive an IPC call in the runner and execute it
  1211. # The IPC is read from the $runnerr pipe and the response is
  1212. # written to the $runnerw pipe
  1213. # Returns 0 if more IPC calls are expected or 1 if the runner should exit
  1214. sub ipcrecv {
  1215. my $err;
  1216. my $datalen;
  1217. while(! defined ($err = sysread($runnerr, $datalen, 4)) || $err <= 0) {
  1218. if((!defined $err && ! $!{EINTR}) || (defined $err && $err == 0)) {
  1219. # pipe has closed; controller is gone and we must exit
  1220. runnerabort();
  1221. # Special case: no response will be forthcoming
  1222. return 1;
  1223. }
  1224. # system call was interrupted, probably by ^C; restart it so we stay in sync
  1225. }
  1226. my $len=unpack("L", $datalen);
  1227. my $buf;
  1228. while(! defined ($err = sysread($runnerr, $buf, $len)) || $err <= 0) {
  1229. if((!defined $err && ! $!{EINTR}) || (defined $err && $err == 0)) {
  1230. # pipe has closed; controller is gone and we must exit
  1231. runnerabort();
  1232. # Special case: no response will be forthcoming
  1233. return 1;
  1234. }
  1235. # system call was interrupted, probably by ^C; restart it so we stay in sync
  1236. }
  1237. # Decode the function name and arguments
  1238. my $argsarrayref = thaw $buf;
  1239. # The name of the function to call is the first argument
  1240. my $funcname = shift @$argsarrayref;
  1241. # print "ipcrecv $funcname\n";
  1242. # Synchronously call the desired function
  1243. my @res;
  1244. if($funcname eq "runner_clearlocks") {
  1245. @res = runner_clearlocks(@$argsarrayref);
  1246. }
  1247. elsif($funcname eq "runner_shutdown") {
  1248. runner_shutdown(@$argsarrayref);
  1249. # Special case: no response will be forthcoming
  1250. return 1;
  1251. }
  1252. elsif($funcname eq "runner_stopservers") {
  1253. @res = runner_stopservers(@$argsarrayref);
  1254. }
  1255. elsif($funcname eq "runner_test_preprocess") {
  1256. @res = runner_test_preprocess(@$argsarrayref);
  1257. }
  1258. elsif($funcname eq "runner_test_run") {
  1259. @res = runner_test_run(@$argsarrayref);
  1260. } else {
  1261. die "Unknown IPC function $funcname\n";
  1262. }
  1263. # print "ipcrecv results\n";
  1264. # Marshall the results to return
  1265. $buf = freeze \@res;
  1266. while(! defined ($err = syswrite($runnerw, (pack "L", length($buf)) . $buf)) || $err <= 0) {
  1267. if((!defined $err && ! $!{EINTR}) || (defined $err && $err == 0)) {
  1268. # pipe has closed; controller is gone and we must exit
  1269. runnerabort();
  1270. # Special case: no response will be forthcoming
  1271. return 1;
  1272. }
  1273. # system call was interrupted, probably by ^C; restart it so we stay in sync
  1274. }
  1275. return 0;
  1276. }
  1277. ###################################################################
  1278. # Kill the server processes that still have lock files in a directory
  1279. sub runner_clearlocks {
  1280. my ($lockdir)=@_;
  1281. if(clearlogs()) {
  1282. logmsg "Warning: log messages were lost\n";
  1283. }
  1284. clearlocks($lockdir);
  1285. return clearlogs();
  1286. }
  1287. ###################################################################
  1288. # Kill all server processes
  1289. sub runner_stopservers {
  1290. my $error = stopservers($verbose);
  1291. my $logs = clearlogs();
  1292. return ($error, $logs);
  1293. }
  1294. ###################################################################
  1295. # Shut down this runner
  1296. sub runner_shutdown {
  1297. close($runnerr);
  1298. undef $runnerr;
  1299. close($runnerw);
  1300. undef $runnerw;
  1301. }
  1302. 1;