ProvisionedVirt.pm 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. package Trog::DataSource::ProvisionedVirt;
  2. use 5.040;
  3. use re '/aa';
  4. use parent qw{Trog::DataSource::Virt};
  5. use Cwd ();
  6. use File::Basename ();
  7. use File::Path ();
  8. use File::Slurper ();
  9. use File::Slurper::Temp ();
  10. use POSIX ();
  11. use Trog::Config ();
  12. use Trog::DataSource ();
  13. use Trog::DataSource::Virt();
  14. use Trog::Auth ();
  15. use Trog::Vault ();
  16. use Trog::Log qw{WARN INFO};
  17. =head1 Trog::DataSource::ProvisionedVirt
  18. Trog::DataSource::Virt, plus the recipe each guest was built from and a button to
  19. build it again.
  20. Everything about listing guests is inherited unchanged -- this is the same
  21. libvirt connection, the same posts, the same search and the same refusal to be
  22. cached. What it adds is the other half of the story: a guest on a Troglodyne
  23. hypervisor was provisioned from a recipe, and the recipe is on disk next to the
  24. hypervisor rather than anywhere libvirt can tell you about.
  25. One repository owns that lifecycle. trog-provisioner's bin/provision generates
  26. a guest's configuration from its recipe and then builds the machine out of it.
  27. The generator used to be a second repository and a second run; the two had to
  28. become one program once which hypervisor a guest lands on became a choice rather
  29. than whichever machine you happened to be sat at.
  30. Say where that checkout is and this becomes useful; leave it out and it degrades
  31. to plain Virt, which is what it is.
  32. [provisioner]
  33. trog_provisioner = /home/you/Code/trog-provisioner
  34. The recipes are not in the checkout. They describe an installation rather than
  35. the software, so trog-provisioner keeps them in /etc/trog-provisioner, or
  36. wherever TROG_PROVISIONER_CONFIG says instead. We find them by that same rule,
  37. which is one fewer thing to tell tCMS and one fewer thing to disagree about.
  38. =head1 A NOTE ON SAFETY
  39. Reprovisioning is not a recoverable operation. It destroys the guest and builds
  40. it again from its recipe, and whatever was on it that the recipe does not
  41. describe does not come back.
  42. The discipline is the same as its parent's, and for the same reasons. It is
  43. POST only and admin only; it refuses outright for the guest tCMS is itself
  44. running on, whatever the template chose to draw; and nothing it runs goes near a
  45. shell, so a guest name is an argument and can never be a command.
  46. =cut
  47. our $recipe_dir = 'recipes.d';
  48. our $log_dir = 'logs/reprovision';
  49. # What the provisioner's two passwords are called in a user's vault. One name
  50. # per person rather than one per guest: the passphrase is to their own secrets
  51. # database, and the sudo password is theirs on the hypervisor rather than
  52. # anything to do with a particular guest.
  53. our $secret_name = 'provisioner';
  54. our $sudo_name = 'provisioner_sudo';
  55. # Where an installation's own files live, which is trog-provisioner's rule
  56. # rather than ours -- see its Trog::Config.
  57. our $provisioner_config = '/etc/trog-provisioner';
  58. # What a reprovision can be, in the order it can be it.
  59. our %states = (
  60. running => 'reprovisioning',
  61. ok => 'provisioned',
  62. failed => 'reprovision failed',
  63. interrupted => 'reprovision interrupted',
  64. );
  65. =head1 FUNCTIONS
  66. =head2 posts($series, $query) = @posts
  67. The guests Trog::DataSource::Virt would have listed, each carrying what we know
  68. about how it was built:
  69. recipe the recipe's YAML, as text, for the page to show
  70. recipe_path where that came from
  71. has_recipe whether there was one at all
  72. can_reprovision whether the button should be drawn
  73. reprovision_state running, ok, failed, interrupted, or absent
  74. reprovision_status that, in words a person reads
  75. reprovision_started when the last run began
  76. reprovision_finished when it ended, if it has
  77. reprovision_exit what it exited with, if it has
  78. reprovision_by who asked for it
  79. is_reprovisioning whether one is going on right now
  80. reprovision_log the tail of the last run
  81. reprovision_log_href where to read all of it
  82. A guest with no recipe is still listed. Plenty of guests on a hypervisor were
  83. not built by this, and saying nothing about them is better than hiding them.
  84. =cut
  85. sub posts ( $series, $query ) {
  86. my @guests = Trog::DataSource::Virt::posts( $series, $query );
  87. my $config = _config();
  88. # Asked once for the page rather than once per guest, and asked rather than
  89. # opened: what the form needs to know is which box to draw.
  90. my $user = $query->{user} // '';
  91. $config->{can_remember} = ( $user && Trog::Vault::has_key() ) ? 1 : 0;
  92. $config->{remembered} = ( $config->{can_remember} && Trog::Vault::has( $user, $secret_name ) ) ? 1 : 0;
  93. $config->{sudo_remembered} = ( $config->{can_remember} && Trog::Vault::has( $user, $sudo_name ) ) ? 1 : 0;
  94. return map { _with_recipe( $_, $config ) } @guests;
  95. }
  96. sub _with_recipe ( $post, $config ) {
  97. return $post if $post->{unreachable};
  98. my $domain = $post->{domain} // '';
  99. my $path = _recipe_path( $config, $domain );
  100. if ($path) {
  101. my $recipe = eval { File::Slurper::read_text($path) };
  102. if ( defined $recipe ) {
  103. $post->{recipe} = $recipe;
  104. $post->{recipe_path} = $path;
  105. $post->{has_recipe} = 1;
  106. }
  107. else {
  108. WARN("Could not read the recipe for '$domain' at $path: $@");
  109. }
  110. }
  111. # There has to be something to run it with, and we will not rebuild the
  112. # machine we are answering the request from -- see act() in the parent,
  113. # which refuses to power that one off for the same reason.
  114. $post->{can_reprovision} =
  115. ( $post->{has_recipe} && $config->{trog_provisioner} && !$post->{is_self} ) ? 1 : 0;
  116. # Which of the things the button has to ask for.
  117. $post->{passphrase_remembered} = $config->{remembered};
  118. $post->{sudo_remembered} = $config->{sudo_remembered};
  119. $post->{can_remember} = $config->{can_remember};
  120. my $status = status($domain);
  121. if ($status) {
  122. $post->{reprovision_state} = $status->{state};
  123. $post->{reprovision_status} = $states{ $status->{state} } // $status->{state};
  124. $post->{reprovision_started} = $status->{started};
  125. $post->{reprovision_finished} = $status->{finished};
  126. $post->{reprovision_exit} = $status->{exit};
  127. $post->{reprovision_by} = $status->{user};
  128. $post->{is_reprovisioning} = $status->{state} eq 'running' ? 1 : 0;
  129. }
  130. # One at a time. Two provisions of the same machine at once is not a thing
  131. # anybody wants to have started by double clicking.
  132. $post->{can_reprovision} = 0 if $post->{is_reprovisioning};
  133. $post->{reprovision_log} = _log_tail($domain);
  134. $post->{reprovision_log_href} = $post->{reprovision_log} ? "/guest/reprovision/log/$domain" : undef;
  135. return $post;
  136. }
  137. =head2 status($domain) = HASHREF or undef
  138. What the last reprovision of this guest is doing, or did.
  139. state running, ok, failed or interrupted
  140. pid the process doing it, while one is
  141. started / finished / exit / user
  142. Nothing waits on the process which does the work -- it is deliberately orphaned,
  143. so that it outlives the worker that started it -- which means its exit status is
  144. not reported to anybody. This file is how it says what happened, and the last
  145. thing the run does is write it.
  146. A run whose status still says 'running' but whose process is gone therefore
  147. crashed, was killed, or took the machine down with it, and reads as interrupted.
  148. That is a guess from the one piece of evidence there is, and it is the honest
  149. one: the alternative is a page that says a provision is in progress forever.
  150. =cut
  151. sub status ($domain) {
  152. my $safe = _safe_domain($domain);
  153. return undef unless $safe;
  154. my $path = "$log_dir/$safe.status";
  155. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  156. my $raw = eval { File::Slurper::read_text($path) };
  157. return undef unless defined $raw;
  158. my %status;
  159. foreach my $line ( split( "\n", $raw ) ) {
  160. my ( $key, $value ) = $line =~ m/^(\w+)=(.*)$/;
  161. $status{$key} = $value if defined $key;
  162. }
  163. return undef unless $status{state};
  164. # kill 0 rather than trusting the file: the process is orphaned, so nothing
  165. # else would ever correct a 'running' that stopped being true. Same uid, so
  166. # this is a real answer. A recycled pid could fool it, which would show a
  167. # finished run as still going rather than the other way about.
  168. if ( $status{state} eq 'running' ) {
  169. my $alive = $status{pid} && kill( 0, $status{pid} );
  170. $status{state} = 'interrupted' unless $alive;
  171. }
  172. return \%status;
  173. }
  174. # Written by the run itself, at the two moments worth recording. By rename, so
  175. # that a page drawn while the run is writing sees the old status or the new one
  176. # and never half of either -- the reader would ignore a torn file, but ignoring
  177. # it means the page says nothing was ever run.
  178. sub _write_status ( $domain, %fields ) {
  179. my $path = "$log_dir/$domain.status";
  180. my $out = join( '', map { "$_=" . ( $fields{$_} // '' ) . "\n" } sort keys %fields );
  181. local $@;
  182. eval {
  183. # Beside the file it replaces, or the rename is a copy across
  184. # filesystems and stops being atomic.
  185. local $File::Slurper::Temp::FILE_TEMP_DIR = $log_dir;
  186. local $File::Slurper::Temp::FILE_TEMP_PERMS = oct('644');
  187. File::Slurper::Temp::write_text( $path, $out );
  188. 1;
  189. } or WARN("Could not record the reprovision status for '$domain': $@");
  190. return;
  191. }
  192. =head2 _config() = HASHREF
  193. Where the provisioner is checked out, from the tCMS configuration, and where the
  194. recipes it reads are, from trog-provisioner's own rule for that.
  195. trog_provisioner the checkout, or undef
  196. recipes the directory the guests' recipes are in
  197. Undef for the checkout means the feature is off rather than broken: a site which
  198. has not configured it gets a plain guest listing, which is what it asked for.
  199. =cut
  200. sub _config {
  201. my $conf = Trog::Config::get();
  202. # Nothing to configure here: the provisioner reads this env var or that
  203. # directory, so a recipe we showed from anywhere else would be a recipe it
  204. # is not going to build from.
  205. my %config = ( recipes => ( $ENV{TROG_PROVISIONER_CONFIG} // $provisioner_config ) . "/$recipe_dir" );
  206. my $dir = $conf->param('provisioner.trog_provisioner');
  207. return \%config unless $dir && !ref $dir;
  208. # Resolved, and checked to be there. A path in a config file which does not
  209. # exist is a typo, and finding that out here beats finding it out halfway
  210. # through a reprovision.
  211. my $absolute = Cwd::abs_path($dir);
  212. if ( !$absolute || !-d $absolute ) {
  213. WARN("provisioner.trog_provisioner is set to '$dir', which is not a directory here");
  214. return \%config;
  215. }
  216. $config{trog_provisioner} = $absolute;
  217. return \%config;
  218. }
  219. # A guest name reaches the filesystem here, so it is a hostname or it is nothing.
  220. sub _safe_domain ($domain) {
  221. return undef unless defined $domain && length($domain) && length($domain) < 254;
  222. return undef if $domain =~ m/(?:^|\.)\.\.?(?:\.|$)/;
  223. my ($safe) = $domain =~ m/^([A-Za-z0-9][A-Za-z0-9._-]*)$/;
  224. return $safe;
  225. }
  226. # An installation's recipes are where they are whether tCMS knows about the
  227. # provisioner or not, but reading them is the feature, so it is off with it.
  228. sub _recipe_path ( $config, $domain ) {
  229. return undef unless $config->{trog_provisioner};
  230. my $safe = _safe_domain($domain);
  231. return undef unless $safe;
  232. my $path = "$config->{recipes}/$safe.yaml";
  233. return -f $path ? $path : undef; ## no critic (ProhibitFiletest_f) -- is there a recipe for this guest
  234. }
  235. =head2 _log_tail($domain) = STRING
  236. The last of whatever the previous reprovision said, or nothing.
  237. The run happens in a detached process which nobody is waiting on, so this file
  238. is the only account of it there is.
  239. =cut
  240. our $log_tail_bytes = 4096;
  241. sub _log_tail ($domain) {
  242. my $safe = _safe_domain($domain);
  243. return undef unless $safe;
  244. my $path = "$log_dir/$safe.log";
  245. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  246. my $text = eval { File::Slurper::read_text($path) };
  247. return undef unless defined $text;
  248. return length($text) > $log_tail_bytes ? substr( $text, -$log_tail_bytes ) : $text;
  249. }
  250. =head2 log_for($domain) = STRING or undef
  251. The whole reprovision log for a guest, for the route which serves it.
  252. Undef when there has never been a run, or when the name is not a guest name --
  253. this reaches the filesystem, so it is checked here rather than trusted from the
  254. route that called it.
  255. =cut
  256. our $log_max_bytes = 1024 * 1024;
  257. sub log_for ($domain) {
  258. my $safe = _safe_domain($domain);
  259. return undef unless $safe;
  260. my $path = "$log_dir/$safe.log";
  261. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  262. my $text = eval { File::Slurper::read_text($path) };
  263. return undef unless defined $text;
  264. # A provisioner can be chatty and this goes out in one response.
  265. return length($text) > $log_max_bytes
  266. ? "[ truncated: showing the last " . int( $log_max_bytes / 1024 ) . "KB ]\n" . substr( $text, -$log_max_bytes )
  267. : $text;
  268. }
  269. =head2 reprovision(%args) = ($ok, $message)
  270. Run bin/provision for one guest, which generates its configuration from its
  271. recipe and then builds the machine.
  272. domain which guest. Required, and validated as a hostname.
  273. user who asked. For the log, and whose vault to look in.
  274. passphrase the KeePass passphrase the recipe's secrets need.
  275. sudo their sudo password on the hypervisor, if it wants one.
  276. totp a code, instead of those, when they have been stored.
  277. remember store what they just typed, so that next time is a code.
  278. Returns immediately. Provisioning a machine takes minutes and an HTTP worker
  279. does not have minutes, so the work is handed to a detached process and the
  280. caller is told it started rather than told it finished. What happened is in
  281. logs/reprovision/$domain.log, which is what _log_tail reads back onto the page.
  282. =head3 WHY IT ASKS FOR ANYTHING AT ALL
  283. Two passwords, for two different reasons.
  284. Every recipe inherits secret: values from _base, so the provisioner opens a
  285. KeePass database on its way past and wants the passphrase to it. The
  286. alternative to asking is keeping the master password for every secret an
  287. operator holds in a file the webserver can read, which is worse than asking.
  288. And almost everything it does on the hypervisor needs root. Where the login
  289. there has passwordless sudo -- which is how ours are set up, and what we would
  290. recommend -- there is nothing to ask for. Where it does not, sudo over ssh has
  291. no terminal to ask at, and a run that finds that out dies several minutes in on
  292. a prompt nobody will ever see. So it is asked for here instead, and left empty
  293. by anybody who does not need it.
  294. Asking every time has its own cost, though: a passphrase somebody has to have to
  295. hand is a passphrase that gets written down, and then it is in a text file
  296. instead of a config file, which is not an improvement. So it can be stored --
  297. see Trog::Vault, where it is sealed under a key the database does not contain --
  298. and then what this asks for is a TOTP code, which proves the person is here
  299. without their having to be holding anything.
  300. The code is spent either way, so it authorizes this one reprovision rather than
  301. every reprovision inside its window.
  302. However they arrive, they go down the child's stdin as a credentials block --
  303. see Trog::Credentials in trog-provisioner -- and are written nowhere: not the
  304. log, not the process table, not the configuration.
  305. =cut
  306. sub reprovision (%args) {
  307. my $safe = _safe_domain( $args{domain} );
  308. return ( 0, 'bad guest name' ) unless $safe;
  309. # The template does not draw the button for this guest. This is what
  310. # actually stops it: /guest/reprovision is a POST anybody holding the admin
  311. # acl can craft by hand, and there would be nothing left to report to.
  312. if ( Trog::DataSource::Virt::_is_self($safe) ) {
  313. WARN("Refused to reprovision '$safe': that is this server");
  314. return ( 0, "'$safe' is this server -- refusing to reprovision it" );
  315. }
  316. my $config = _config();
  317. return ( 0, 'provisioner.trog_provisioner is not configured' ) unless $config->{trog_provisioner};
  318. my $recipe = _recipe_path( $config, $safe );
  319. return ( 0, "there is no recipe for '$safe' in $config->{recipes}" ) unless $recipe;
  320. my ( $credentials, $why ) = _credentials(%args);
  321. return ( 0, $why ) unless $credentials;
  322. my $unsendable = _sendable($credentials);
  323. return ( 0, $unsendable ) if $unsendable;
  324. # One at a time. Two provisions of one machine racing each other is not
  325. # something anybody should be able to start by double clicking.
  326. my $running = status($safe);
  327. return ( 0, 'a reprovision of this guest is already running' ) if $running && $running->{state} eq 'running';
  328. # --credentials, because nothing in there reads stdin unless it is told to.
  329. my @command = ( "$config->{trog_provisioner}/bin/provision", '--credentials', $safe );
  330. return ( 0, "$command[0] is not there to run" ) unless -x $command[0]; ## no critic (ProhibitFiletest_rwxRWX) -- refusing early beats finding out mid-provision
  331. INFO( "Reprovision of '$safe' requested by " . ( $args{user} // 'somebody' ) );
  332. my ( $ok, $failed ) = _spawn( $safe, $credentials, $config->{trog_provisioner}, \@command, $args{user} );
  333. return ( 0, $failed ) unless $ok;
  334. return ( 1, "reprovision started; watch $log_dir/$safe.log" );
  335. }
  336. =head2 _credentials(%args) = ($credentials, $why)
  337. What to hand the provisioner, out of whatever the form sent: a hashref of the
  338. names Trog::Credentials knows, or undef and a reason.
  339. A code is only ever exchanged for passwords that are already stored -- it is
  340. proof of presence, not a password, and there is nothing to derive from six
  341. digits. Typed passwords are used as they are, and stored on the way past if
  342. they asked for that, so the next run is a code.
  343. The two are independent. A sudo password typed into the form wins over a stored
  344. one, because somebody typing it has a reason to; and a hypervisor with
  345. passwordless sudo simply never has one, in the form or the vault, which is the
  346. ordinary case and not a missing answer.
  347. The reason, when there is one, is what the person reads -- so it has to tell
  348. 'that code is stale' apart from 'there is nothing stored to unlock'.
  349. =cut
  350. sub _credentials (%args) {
  351. my $user = $args{user} // '';
  352. my %credentials;
  353. # What they typed, as opposed to what came back out of the vault. Only the
  354. # typed ones are worth filing away, and only they can be: a value fetched
  355. # from the vault is already in it.
  356. my %typed;
  357. $typed{sudo} = $args{sudo} if length( $args{sudo} // '' );
  358. if ( length( $args{totp} // '' ) ) {
  359. return ( undef, 'a code identifies somebody, and nobody is logged in' ) unless $user;
  360. # Asked before the code is spent, and the reason is that a code is
  361. # spent whether or not the thing it authorized worked. Somebody whose
  362. # key has gone would otherwise burn a code to be told there is nothing
  363. # to unlock, then wait thirty seconds to be told it again. has() opens
  364. # the row to answer, so this is the same answer get() is about to give.
  365. return (
  366. undef,
  367. "there is no provisioning passphrase this installation can open for $user." . " Store it again under /secrets, or reprovision with the passphrase itself."
  368. ) unless Trog::Vault::has( $user, $secret_name );
  369. my ( $ok, $why ) = Trog::Auth::spend_totp( $user, $args{totp} );
  370. return ( undef, $why ) unless $ok;
  371. my $stored = Trog::Vault::get( $user, $secret_name );
  372. return ( undef, "the stored provisioning passphrase for $user could not be read" ) unless defined $stored && length($stored);
  373. $credentials{keepass} = $stored;
  374. }
  375. else {
  376. return ( undef, 'a passphrase is required, as the provisioner asks for one' ) unless length( $args{passphrase} // '' );
  377. $credentials{keepass} = $args{passphrase};
  378. $typed{keepass} = $args{passphrase};
  379. }
  380. # A typed sudo password beats a stored one -- somebody typing it has a
  381. # reason to -- and no sudo password at all is the ordinary answer, for a
  382. # hypervisor whose login has passwordless sudo.
  383. my $sudo = $typed{sudo} // ( $user ? Trog::Vault::get( $user, $sudo_name ) : undef );
  384. $credentials{sudo} = $sudo if defined $sudo && length($sudo);
  385. _remember( $user, \%typed ) if $args{remember} && $user && %typed;
  386. return ( \%credentials, '' );
  387. }
  388. # One 'name: value' per line is the format, so a value with a newline in it is
  389. # two lines -- and the second one could name a credential nobody asked us to
  390. # send. Refused rather than escaped or trimmed: no password anybody meant to
  391. # type has a newline in the middle of it, and quietly changing what somebody
  392. # typed into their own password field is worse than saying no.
  393. sub _sendable ($credentials) {
  394. foreach my $name ( sort keys %$credentials ) {
  395. next unless $credentials->{$name} =~ m/[\r\n]/;
  396. return "the $name has a line break in it, which is not something this can send";
  397. }
  398. return '';
  399. }
  400. # File away what they typed, so the next run is a code.
  401. #
  402. # Said rather than refused when it does not work: they asked for a reprovision
  403. # and gave us what it needs, and failing to keep a copy is not a reason to not do
  404. # the thing they asked for.
  405. sub _remember ( $user, $credentials ) {
  406. my %vault_name = ( keepass => $secret_name, sudo => $sudo_name );
  407. foreach my $name ( sort keys %$credentials ) {
  408. my ( $ok, $why ) = Trog::Vault::set( $user, $vault_name{$name}, $credentials->{$name} );
  409. WARN("Could not remember the provisioner's $name for $user: $why") unless $ok;
  410. }
  411. return;
  412. }
  413. =head2 _spawn($domain, $credentials, $dir, $command, $user)
  414. Fork the provisioner off where nothing is waiting for it.
  415. Double forked and setsid'd on purpose: a save signals the parent to reload the
  416. routing table, and a provision which died because a worker was recycled halfway
  417. through would leave a half-built machine. This has to outlive the request, the
  418. worker, and a restart.
  419. It runs through open() with a list, so there is no shell between us and the
  420. program, and the guest name is an argument rather than a thing that could be
  421. read as one.
  422. The passwords go down its stdin as a credentials block, which is
  423. Trog::Credentials' format over there: one C<name: value> per line, and a blank
  424. line to say that is all of them. A value with a newline in it would be two
  425. lines, and the second could name a credential we were not asked to send, so one
  426. is refused rather than escaped -- there is no password anybody meant to type
  427. that has a newline in the middle of it.
  428. =cut
  429. sub _spawn ( $domain, $credentials, $dir, $command, $user ) {
  430. my $log = "$log_dir/$domain.log";
  431. local $@;
  432. eval { File::Path::make_path($log_dir); 1 } or return ( 0, "could not make $log_dir: $@" );
  433. my $pid = fork();
  434. return ( 0, "could not fork: $!" ) unless defined $pid;
  435. return ( 1, 'started' ) if $pid;
  436. # First child: detach, fork again, and let the middle process go so that
  437. # nothing is left for the worker to reap or be blocked by.
  438. POSIX::setsid();
  439. my $grandchild = fork();
  440. POSIX::_exit(0) if !defined $grandchild || $grandchild;
  441. # From here on we are nobody's child and nothing reads our exit status, so
  442. # the log is the only way to say anything.
  443. open( my $fh, '>>', $log ) or POSIX::_exit(1);
  444. $fh->autoflush(1);
  445. my $started = time();
  446. print {$fh} "\n=== reprovision of $domain by " . ( $user // 'somebody' ) . ' at ' . localtime($started) . " ===\n";
  447. # $$ is this process, which is the one that will still be here in ten
  448. # minutes -- the two before it have already gone. status() checks it is
  449. # alive, so it has to be the pid of whatever is actually doing the work.
  450. _write_status( $domain, state => 'running', pid => $$, started => $started, user => ( $user // '' ) );
  451. print {$fh} "\n--- $command->[0] $command->[1] (in $dir)\n";
  452. # In the checkout, so that anything the provisioner writes relative to where
  453. # it was run lands there rather than in the middle of the website.
  454. if ( !chdir($dir) ) {
  455. print {$fh} "could not chdir to $dir: $!\n";
  456. POSIX::_exit(1);
  457. }
  458. # The child's own stdout and stderr are the log, so whatever the program
  459. # says lands there without a shell redirect to get wrong.
  460. open( STDOUT, '>&', $fh ) or POSIX::_exit(1);
  461. open( STDERR, '>&', $fh ) or POSIX::_exit(1);
  462. # List form on purpose, and the reason the whole thing is shaped this way: a
  463. # piped open with a list never involves a shell, so the guest name is an
  464. # argument and cannot be read as a command. The single argument form of
  465. # this would be the bug.
  466. my $ok = open( my $stdin, '|-', @$command ); ## no critic (ProhibitPipeOpen) -- list form, so no shell
  467. if ( !$ok ) {
  468. print {$fh} "could not run $command->[0]: $!\n";
  469. POSIX::_exit(1);
  470. }
  471. # What the provisioner would otherwise have nobody to ask for. Closed
  472. # afterwards, so the read on the far side ends rather than waiting on us.
  473. print {$stdin} "$_: $credentials->{$_}\n" foreach sort keys %$credentials;
  474. print {$stdin} "\n";
  475. close($stdin);
  476. if ($?) {
  477. my $status = $? >> 8;
  478. print {$fh} "\n--- $command->[0] exited $status\n";
  479. _write_status(
  480. $domain,
  481. state => 'failed',
  482. started => $started,
  483. finished => time(),
  484. exit => $status,
  485. failed => $command->[0],
  486. user => ( $user // '' ),
  487. );
  488. POSIX::_exit($status);
  489. }
  490. print {$fh} "\n=== finished ===\n";
  491. _write_status( $domain, state => 'ok', started => $started, finished => time(), exit => 0, user => ( $user // '' ) );
  492. POSIX::_exit(0);
  493. }
  494. 1;