ProvisionedVirt.pm 26 KB

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