ProvisionedVirt.pm 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. package Trog::DataSource::ProvisionedVirt;
  2. use v5.36;
  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 a stored provisioning passphrase is called in a user's vault. One name
  50. # per person rather than one per guest: it is the passphrase to their secrets
  51. # database, and there is one of those.
  52. our $secret_name = 'provisioner';
  53. # Where an installation's own files live, which is trog-provisioner's rule
  54. # rather than ours -- see its Trog::Config.
  55. our $provisioner_config = '/etc/trog-provisioner';
  56. # What a reprovision can be, in the order it can be it.
  57. our %states = (
  58. running => 'reprovisioning',
  59. ok => 'provisioned',
  60. failed => 'reprovision failed',
  61. interrupted => 'reprovision interrupted',
  62. );
  63. =head1 FUNCTIONS
  64. =head2 posts($series, $query) = @posts
  65. The guests Trog::DataSource::Virt would have listed, each carrying what we know
  66. about how it was built:
  67. recipe the recipe's YAML, as text, for the page to show
  68. recipe_path where that came from
  69. has_recipe whether there was one at all
  70. can_reprovision whether the button should be drawn
  71. reprovision_state running, ok, failed, interrupted, or absent
  72. reprovision_status that, in words a person reads
  73. reprovision_started when the last run began
  74. reprovision_finished when it ended, if it has
  75. reprovision_exit what it exited with, if it has
  76. reprovision_by who asked for it
  77. is_reprovisioning whether one is going on right now
  78. reprovision_log the tail of the last run
  79. reprovision_log_href where to read all of it
  80. A guest with no recipe is still listed. Plenty of guests on a hypervisor were
  81. not built by this, and saying nothing about them is better than hiding them.
  82. =cut
  83. sub posts ( $series, $query ) {
  84. my @guests = Trog::DataSource::Virt::posts( $series, $query );
  85. my $config = _config();
  86. # Asked once for the page rather than once per guest, and asked rather than
  87. # opened: what the form needs to know is which box to draw.
  88. my $user = $query->{user} // '';
  89. $config->{can_remember} = ( $user && Trog::Vault::has_key() ) ? 1 : 0;
  90. $config->{remembered} = ( $config->{can_remember} && Trog::Vault::has( $user, $secret_name ) ) ? 1 : 0;
  91. return map { _with_recipe( $_, $config ) } @guests;
  92. }
  93. sub _with_recipe ( $post, $config ) {
  94. return $post if $post->{unreachable};
  95. my $domain = $post->{domain} // '';
  96. my $path = _recipe_path( $config, $domain );
  97. if ($path) {
  98. my $recipe = eval { File::Slurper::read_text($path) };
  99. if ( defined $recipe ) {
  100. $post->{recipe} = $recipe;
  101. $post->{recipe_path} = $path;
  102. $post->{has_recipe} = 1;
  103. }
  104. else {
  105. WARN("Could not read the recipe for '$domain' at $path: $@");
  106. }
  107. }
  108. # There has to be something to run it with, and we will not rebuild the
  109. # machine we are answering the request from -- see act() in the parent,
  110. # which refuses to power that one off for the same reason.
  111. $post->{can_reprovision} =
  112. ( $post->{has_recipe} && $config->{trog_provisioner} && !$post->{is_self} ) ? 1 : 0;
  113. # Which of the two things the button has to ask for.
  114. $post->{passphrase_remembered} = $config->{remembered};
  115. $post->{can_remember} = $config->{can_remember};
  116. my $status = status($domain);
  117. if ($status) {
  118. $post->{reprovision_state} = $status->{state};
  119. $post->{reprovision_status} = $states{ $status->{state} } // $status->{state};
  120. $post->{reprovision_started} = $status->{started};
  121. $post->{reprovision_finished} = $status->{finished};
  122. $post->{reprovision_exit} = $status->{exit};
  123. $post->{reprovision_by} = $status->{user};
  124. $post->{is_reprovisioning} = $status->{state} eq 'running' ? 1 : 0;
  125. }
  126. # One at a time. Two provisions of the same machine at once is not a thing
  127. # anybody wants to have started by double clicking.
  128. $post->{can_reprovision} = 0 if $post->{is_reprovisioning};
  129. $post->{reprovision_log} = _log_tail($domain);
  130. $post->{reprovision_log_href} = $post->{reprovision_log} ? "/guest/reprovision/log/$domain" : undef;
  131. return $post;
  132. }
  133. =head2 status($domain) = HASHREF or undef
  134. What the last reprovision of this guest is doing, or did.
  135. state running, ok, failed or interrupted
  136. pid the process doing it, while one is
  137. started / finished / exit / user
  138. Nothing waits on the process which does the work -- it is deliberately orphaned,
  139. so that it outlives the worker that started it -- which means its exit status is
  140. not reported to anybody. This file is how it says what happened, and the last
  141. thing the run does is write it.
  142. A run whose status still says 'running' but whose process is gone therefore
  143. crashed, was killed, or took the machine down with it, and reads as interrupted.
  144. That is a guess from the one piece of evidence there is, and it is the honest
  145. one: the alternative is a page that says a provision is in progress forever.
  146. =cut
  147. sub status ($domain) {
  148. my $safe = _safe_domain($domain);
  149. return undef unless $safe;
  150. my $path = "$log_dir/$safe.status";
  151. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  152. my $raw = eval { File::Slurper::read_text($path) };
  153. return undef unless defined $raw;
  154. my %status;
  155. foreach my $line ( split( "\n", $raw ) ) {
  156. my ( $key, $value ) = $line =~ m/^(\w+)=(.*)$/;
  157. $status{$key} = $value if defined $key;
  158. }
  159. return undef unless $status{state};
  160. # kill 0 rather than trusting the file: the process is orphaned, so nothing
  161. # else would ever correct a 'running' that stopped being true. Same uid, so
  162. # this is a real answer. A recycled pid could fool it, which would show a
  163. # finished run as still going rather than the other way about.
  164. if ( $status{state} eq 'running' ) {
  165. my $alive = $status{pid} && kill( 0, $status{pid} );
  166. $status{state} = 'interrupted' unless $alive;
  167. }
  168. return \%status;
  169. }
  170. # Written by the run itself, at the two moments worth recording. By rename, so
  171. # that a page drawn while the run is writing sees the old status or the new one
  172. # and never half of either -- the reader would ignore a torn file, but ignoring
  173. # it means the page says nothing was ever run.
  174. sub _write_status ( $domain, %fields ) {
  175. my $path = "$log_dir/$domain.status";
  176. my $out = join( '', map { "$_=" . ( $fields{$_} // '' ) . "\n" } sort keys %fields );
  177. local $@;
  178. eval {
  179. # Beside the file it replaces, or the rename is a copy across
  180. # filesystems and stops being atomic.
  181. local $File::Slurper::Temp::FILE_TEMP_DIR = $log_dir;
  182. local $File::Slurper::Temp::FILE_TEMP_PERMS = oct('644');
  183. File::Slurper::Temp::write_text( $path, $out );
  184. 1;
  185. } or WARN("Could not record the reprovision status for '$domain': $@");
  186. return;
  187. }
  188. =head2 _config() = HASHREF
  189. Where the provisioner is checked out, from the tCMS configuration, and where the
  190. recipes it reads are, from trog-provisioner's own rule for that.
  191. trog_provisioner the checkout, or undef
  192. recipes the directory the guests' recipes are in
  193. Undef for the checkout means the feature is off rather than broken: a site which
  194. has not configured it gets a plain guest listing, which is what it asked for.
  195. =cut
  196. sub _config {
  197. my $conf = Trog::Config::get();
  198. # Nothing to configure here: the provisioner reads this env var or that
  199. # directory, so a recipe we showed from anywhere else would be a recipe it
  200. # is not going to build from.
  201. my %config = ( recipes => ( $ENV{TROG_PROVISIONER_CONFIG} // $provisioner_config ) . "/$recipe_dir" );
  202. my $dir = $conf->param('provisioner.trog_provisioner');
  203. return \%config unless $dir && !ref $dir;
  204. # Resolved, and checked to be there. A path in a config file which does not
  205. # exist is a typo, and finding that out here beats finding it out halfway
  206. # through a reprovision.
  207. my $absolute = Cwd::abs_path($dir);
  208. if ( !$absolute || !-d $absolute ) {
  209. WARN("provisioner.trog_provisioner is set to '$dir', which is not a directory here");
  210. return \%config;
  211. }
  212. $config{trog_provisioner} = $absolute;
  213. return \%config;
  214. }
  215. # A guest name reaches the filesystem here, so it is a hostname or it is nothing.
  216. sub _safe_domain ($domain) {
  217. return undef unless defined $domain && length($domain) && length($domain) < 254;
  218. return undef if $domain =~ m/(?:^|\.)\.\.?(?:\.|$)/;
  219. my ($safe) = $domain =~ m/^([A-Za-z0-9][A-Za-z0-9._-]*)$/;
  220. return $safe;
  221. }
  222. # An installation's recipes are where they are whether tCMS knows about the
  223. # provisioner or not, but reading them is the feature, so it is off with it.
  224. sub _recipe_path ( $config, $domain ) {
  225. return undef unless $config->{trog_provisioner};
  226. my $safe = _safe_domain($domain);
  227. return undef unless $safe;
  228. my $path = "$config->{recipes}/$safe.yaml";
  229. return -f $path ? $path : undef; ## no critic (ProhibitFiletest_f) -- is there a recipe for this guest
  230. }
  231. =head2 _log_tail($domain) = STRING
  232. The last of whatever the previous reprovision said, or nothing.
  233. The run happens in a detached process which nobody is waiting on, so this file
  234. is the only account of it there is.
  235. =cut
  236. our $log_tail_bytes = 4096;
  237. sub _log_tail ($domain) {
  238. my $safe = _safe_domain($domain);
  239. return undef unless $safe;
  240. my $path = "$log_dir/$safe.log";
  241. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  242. my $text = eval { File::Slurper::read_text($path) };
  243. return undef unless defined $text;
  244. return length($text) > $log_tail_bytes ? substr( $text, -$log_tail_bytes ) : $text;
  245. }
  246. =head2 log_for($domain) = STRING or undef
  247. The whole reprovision log for a guest, for the route which serves it.
  248. Undef when there has never been a run, or when the name is not a guest name --
  249. this reaches the filesystem, so it is checked here rather than trusted from the
  250. route that called it.
  251. =cut
  252. our $log_max_bytes = 1024 * 1024;
  253. sub log_for ($domain) {
  254. my $safe = _safe_domain($domain);
  255. return undef unless $safe;
  256. my $path = "$log_dir/$safe.log";
  257. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  258. my $text = eval { File::Slurper::read_text($path) };
  259. return undef unless defined $text;
  260. # A provisioner can be chatty and this goes out in one response.
  261. return length($text) > $log_max_bytes
  262. ? "[ truncated: showing the last " . int( $log_max_bytes / 1024 ) . "KB ]\n" . substr( $text, -$log_max_bytes )
  263. : $text;
  264. }
  265. =head2 reprovision(%args) = ($ok, $message)
  266. Run bin/provision for one guest, which generates its configuration from its
  267. recipe and then builds the machine.
  268. domain which guest. Required, and validated as a hostname.
  269. user who asked. For the log, and whose vault to look in.
  270. passphrase the KeePass passphrase the recipe's secrets need, on stdin.
  271. totp a code, instead of the passphrase, when they have stored one.
  272. remember store the passphrase they just typed, so that next time is a code.
  273. Returns immediately. Provisioning a machine takes minutes and an HTTP worker
  274. does not have minutes, so the work is handed to a detached process and the
  275. caller is told it started rather than told it finished. What happened is in
  276. logs/reprovision/$domain.log, which is what _log_tail reads back onto the page.
  277. =head3 WHY IT ASKS FOR ANYTHING AT ALL
  278. Every recipe inherits secret: values from _base, so the provisioner opens a
  279. KeePass database on its way past and wants the passphrase to it on stdin. The
  280. alternative to asking is keeping the master password for every secret an
  281. operator holds in a file the webserver can read, which is worse than asking.
  282. Asking every time has its own cost, though: a passphrase somebody has to have to
  283. hand is a passphrase that gets written down, and then it is in a text file
  284. instead of a config file, which is not an improvement. So it can be stored --
  285. see Trog::Vault, where it is sealed under a key the database does not contain --
  286. and then what this asks for is a TOTP code, which proves the person is here
  287. without their having to be holding anything.
  288. The code is spent either way, so it authorizes this one reprovision rather than
  289. every reprovision inside its window.
  290. Whichever it arrives as, the passphrase goes down the child's stdin and is
  291. written nowhere: not the log, not the process table, not the configuration.
  292. =cut
  293. sub reprovision (%args) {
  294. my $safe = _safe_domain( $args{domain} );
  295. return ( 0, 'bad guest name' ) unless $safe;
  296. # The template does not draw the button for this guest. This is what
  297. # actually stops it: /guest/reprovision is a POST anybody holding the admin
  298. # acl can craft by hand, and there would be nothing left to report to.
  299. if ( Trog::DataSource::Virt::_is_self($safe) ) {
  300. WARN("Refused to reprovision '$safe': that is this server");
  301. return ( 0, "'$safe' is this server -- refusing to reprovision it" );
  302. }
  303. my $config = _config();
  304. return ( 0, 'provisioner.trog_provisioner is not configured' ) unless $config->{trog_provisioner};
  305. my $recipe = _recipe_path( $config, $safe );
  306. return ( 0, "there is no recipe for '$safe' in $config->{recipes}" ) unless $recipe;
  307. my ( $passphrase, $why ) = _passphrase(%args);
  308. return ( 0, $why ) unless defined $passphrase;
  309. # One at a time. Two provisions of one machine racing each other is not
  310. # something anybody should be able to start by double clicking.
  311. my $running = status($safe);
  312. return ( 0, 'a reprovision of this guest is already running' ) if $running && $running->{state} eq 'running';
  313. my @command = ( "$config->{trog_provisioner}/bin/provision", $safe );
  314. return ( 0, "$command[0] is not there to run" ) unless -x $command[0]; ## no critic (ProhibitFiletest_rwxRWX) -- refusing early beats finding out mid-provision
  315. INFO( "Reprovision of '$safe' requested by " . ( $args{user} // 'somebody' ) );
  316. my ( $ok, $failed ) = _spawn( $safe, $passphrase, $config->{trog_provisioner}, \@command, $args{user} );
  317. return ( 0, $failed ) unless $ok;
  318. return ( 1, "reprovision started; watch $log_dir/$safe.log" );
  319. }
  320. =head2 _passphrase(%args) = ($passphrase, $why)
  321. The passphrase to hand the provisioner, out of whichever of the two things the
  322. form sent.
  323. A code is only ever exchanged for a passphrase that is already stored -- it is
  324. proof of presence, not a password, and there is nothing to derive from it. A
  325. typed passphrase is used as it is, and stored on the way past if they asked for
  326. it to be, so that the next run is a code.
  327. Undef with a reason for anything else, and the reason is what the person sees:
  328. this is the message that has to distinguish 'that code is stale' from 'there is
  329. nothing stored to unlock'.
  330. =cut
  331. sub _passphrase (%args) {
  332. my $user = $args{user} // '';
  333. if ( length( $args{totp} // '' ) ) {
  334. return ( undef, 'a code identifies somebody, and nobody is logged in' ) unless $user;
  335. my ( $ok, $why ) = Trog::Auth::spend_totp( $user, $args{totp} );
  336. return ( undef, $why ) unless $ok;
  337. my $stored = Trog::Vault::get( $user, $secret_name );
  338. return ( undef, "there is no provisioning passphrase stored for $user" ) unless defined $stored && length($stored);
  339. return ( $stored, '' );
  340. }
  341. return ( undef, 'a passphrase is required, as the provisioner asks for one' ) unless length( $args{passphrase} // '' );
  342. if ( $args{remember} && $user ) {
  343. my ( $ok, $why ) = Trog::Vault::set( $user, $secret_name, $args{passphrase} );
  344. # Said rather than refused: they asked for a reprovision and gave us
  345. # what it needs, and failing to file the passphrase away is not a
  346. # reason not to do the thing they asked for.
  347. WARN("Could not remember the provisioning passphrase for $user: $why") unless $ok;
  348. }
  349. return ( $args{passphrase}, '' );
  350. }
  351. =head2 _spawn($domain, $passphrase, $dir, $command, $user)
  352. Fork the provisioner off where nothing is waiting for it.
  353. Double forked and setsid'd on purpose: a save signals the parent to reload the
  354. routing table, and a provision which died because a worker was recycled halfway
  355. through would leave a half-built machine. This has to outlive the request, the
  356. worker, and a restart.
  357. It runs through open() with a list, so there is no shell between us and the
  358. program, and the guest name is an argument rather than a thing that could be
  359. read as one.
  360. =cut
  361. sub _spawn ( $domain, $passphrase, $dir, $command, $user ) {
  362. my $log = "$log_dir/$domain.log";
  363. local $@;
  364. eval { File::Path::make_path($log_dir); 1 } or return ( 0, "could not make $log_dir: $@" );
  365. my $pid = fork();
  366. return ( 0, "could not fork: $!" ) unless defined $pid;
  367. return ( 1, 'started' ) if $pid;
  368. # First child: detach, fork again, and let the middle process go so that
  369. # nothing is left for the worker to reap or be blocked by.
  370. POSIX::setsid();
  371. my $grandchild = fork();
  372. POSIX::_exit(0) if !defined $grandchild || $grandchild;
  373. # From here on we are nobody's child and nothing reads our exit status, so
  374. # the log is the only way to say anything.
  375. open( my $fh, '>>', $log ) or POSIX::_exit(1);
  376. $fh->autoflush(1);
  377. my $started = time();
  378. print {$fh} "\n=== reprovision of $domain by " . ( $user // 'somebody' ) . ' at ' . localtime($started) . " ===\n";
  379. # $$ is this process, which is the one that will still be here in ten
  380. # minutes -- the two before it have already gone. status() checks it is
  381. # alive, so it has to be the pid of whatever is actually doing the work.
  382. _write_status( $domain, state => 'running', pid => $$, started => $started, user => ( $user // '' ) );
  383. print {$fh} "\n--- $command->[0] $command->[1] (in $dir)\n";
  384. # In the checkout, so that anything the provisioner writes relative to where
  385. # it was run lands there rather than in the middle of the website.
  386. if ( !chdir($dir) ) {
  387. print {$fh} "could not chdir to $dir: $!\n";
  388. POSIX::_exit(1);
  389. }
  390. # The child's own stdout and stderr are the log, so whatever the program
  391. # says lands there without a shell redirect to get wrong.
  392. open( STDOUT, '>&', $fh ) or POSIX::_exit(1);
  393. open( STDERR, '>&', $fh ) or POSIX::_exit(1);
  394. # List form on purpose, and the reason the whole thing is shaped this way: a
  395. # piped open with a list never involves a shell, so the guest name is an
  396. # argument and cannot be read as a command. The single argument form of
  397. # this would be the bug.
  398. my $ok = open( my $stdin, '|-', @$command ); ## no critic (ProhibitPipeOpen) -- list form, so no shell
  399. if ( !$ok ) {
  400. print {$fh} "could not run $command->[0]: $!\n";
  401. POSIX::_exit(1);
  402. }
  403. # What the provisioner prompts for on its way to the secrets database.
  404. # Closing this instead would make anything that asks hang forever.
  405. print {$stdin} "$passphrase\n";
  406. close($stdin);
  407. if ($?) {
  408. my $status = $? >> 8;
  409. print {$fh} "\n--- $command->[0] exited $status\n";
  410. _write_status(
  411. $domain,
  412. state => 'failed',
  413. started => $started,
  414. finished => time(),
  415. exit => $status,
  416. failed => $command->[0],
  417. user => ( $user // '' ),
  418. );
  419. POSIX::_exit($status);
  420. }
  421. print {$fh} "\n=== finished ===\n";
  422. _write_status( $domain, state => 'ok', started => $started, finished => time(), exit => 0, user => ( $user // '' ) );
  423. POSIX::_exit(0);
  424. }
  425. 1;