ProvisionedVirt.pm 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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::Log qw{WARN INFO};
  15. =head1 Trog::DataSource::ProvisionedVirt
  16. Trog::DataSource::Virt, plus the recipe each guest was built from and a button to
  17. build it again.
  18. Everything about listing guests is inherited unchanged -- this is the same
  19. libvirt connection, the same posts, the same search and the same refusal to be
  20. cached. What it adds is the other half of the story: a guest on a Troglodyne
  21. hypervisor was provisioned from a recipe, and the recipe is on disk next to the
  22. hypervisor rather than anywhere libvirt can tell you about.
  23. One repository owns that lifecycle. trog-provisioner's bin/provision generates
  24. a guest's configuration from its recipe and then builds the machine out of it.
  25. The generator used to be a second repository and a second run; the two had to
  26. become one program once which hypervisor a guest lands on became a choice rather
  27. than whichever machine you happened to be sat at.
  28. Say where that checkout is and this becomes useful; leave it out and it degrades
  29. to plain Virt, which is what it is.
  30. [provisioner]
  31. trog_provisioner = /home/you/Code/trog-provisioner
  32. The recipes are not in the checkout. They describe an installation rather than
  33. the software, so trog-provisioner keeps them in /etc/trog-provisioner, or
  34. wherever TROG_PROVISIONER_CONFIG says instead. We find them by that same rule,
  35. which is one fewer thing to tell tCMS and one fewer thing to disagree about.
  36. =head1 A NOTE ON SAFETY
  37. Reprovisioning is not a recoverable operation. It destroys the guest and builds
  38. it again from its recipe, and whatever was on it that the recipe does not
  39. describe does not come back.
  40. The discipline is the same as its parent's, and for the same reasons. It is
  41. POST only and admin only; it refuses outright for the guest tCMS is itself
  42. running on, whatever the template chose to draw; and nothing it runs goes near a
  43. shell, so a guest name is an argument and can never be a command.
  44. =cut
  45. our $recipe_dir = 'recipes.d';
  46. our $log_dir = 'logs/reprovision';
  47. # Where an installation's own files live, which is trog-provisioner's rule
  48. # rather than ours -- see its Trog::Config.
  49. our $provisioner_config = '/etc/trog-provisioner';
  50. # What a reprovision can be, in the order it can be it.
  51. our %states = (
  52. running => 'reprovisioning',
  53. ok => 'provisioned',
  54. failed => 'reprovision failed',
  55. interrupted => 'reprovision interrupted',
  56. );
  57. =head1 FUNCTIONS
  58. =head2 posts($series, $query) = @posts
  59. The guests Trog::DataSource::Virt would have listed, each carrying what we know
  60. about how it was built:
  61. recipe the recipe's YAML, as text, for the page to show
  62. recipe_path where that came from
  63. has_recipe whether there was one at all
  64. can_reprovision whether the button should be drawn
  65. reprovision_state running, ok, failed, interrupted, or absent
  66. reprovision_status that, in words a person reads
  67. reprovision_started when the last run began
  68. reprovision_finished when it ended, if it has
  69. reprovision_exit what it exited with, if it has
  70. reprovision_by who asked for it
  71. is_reprovisioning whether one is going on right now
  72. reprovision_log the tail of the last run
  73. reprovision_log_href where to read all of it
  74. A guest with no recipe is still listed. Plenty of guests on a hypervisor were
  75. not built by this, and saying nothing about them is better than hiding them.
  76. =cut
  77. sub posts ( $series, $query ) {
  78. my @guests = Trog::DataSource::Virt::posts( $series, $query );
  79. my $config = _config();
  80. return map { _with_recipe( $_, $config ) } @guests;
  81. }
  82. sub _with_recipe ( $post, $config ) {
  83. return $post if $post->{unreachable};
  84. my $domain = $post->{domain} // '';
  85. my $path = _recipe_path( $config, $domain );
  86. if ($path) {
  87. my $recipe = eval { File::Slurper::read_text($path) };
  88. if ( defined $recipe ) {
  89. $post->{recipe} = $recipe;
  90. $post->{recipe_path} = $path;
  91. $post->{has_recipe} = 1;
  92. }
  93. else {
  94. WARN("Could not read the recipe for '$domain' at $path: $@");
  95. }
  96. }
  97. # There has to be something to run it with, and we will not rebuild the
  98. # machine we are answering the request from -- see act() in the parent,
  99. # which refuses to power that one off for the same reason.
  100. $post->{can_reprovision} =
  101. ( $post->{has_recipe} && $config->{trog_provisioner} && !$post->{is_self} ) ? 1 : 0;
  102. my $status = status($domain);
  103. if ($status) {
  104. $post->{reprovision_state} = $status->{state};
  105. $post->{reprovision_status} = $states{ $status->{state} } // $status->{state};
  106. $post->{reprovision_started} = $status->{started};
  107. $post->{reprovision_finished} = $status->{finished};
  108. $post->{reprovision_exit} = $status->{exit};
  109. $post->{reprovision_by} = $status->{user};
  110. $post->{is_reprovisioning} = $status->{state} eq 'running' ? 1 : 0;
  111. }
  112. # One at a time. Two provisions of the same machine at once is not a thing
  113. # anybody wants to have started by double clicking.
  114. $post->{can_reprovision} = 0 if $post->{is_reprovisioning};
  115. $post->{reprovision_log} = _log_tail($domain);
  116. $post->{reprovision_log_href} = $post->{reprovision_log} ? "/guest/reprovision/log/$domain" : undef;
  117. return $post;
  118. }
  119. =head2 status($domain) = HASHREF or undef
  120. What the last reprovision of this guest is doing, or did.
  121. state running, ok, failed or interrupted
  122. pid the process doing it, while one is
  123. started / finished / exit / user
  124. Nothing waits on the process which does the work -- it is deliberately orphaned,
  125. so that it outlives the worker that started it -- which means its exit status is
  126. not reported to anybody. This file is how it says what happened, and the last
  127. thing the run does is write it.
  128. A run whose status still says 'running' but whose process is gone therefore
  129. crashed, was killed, or took the machine down with it, and reads as interrupted.
  130. That is a guess from the one piece of evidence there is, and it is the honest
  131. one: the alternative is a page that says a provision is in progress forever.
  132. =cut
  133. sub status ($domain) {
  134. my $safe = _safe_domain($domain);
  135. return undef unless $safe;
  136. my $path = "$log_dir/$safe.status";
  137. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  138. my $raw = eval { File::Slurper::read_text($path) };
  139. return undef unless defined $raw;
  140. my %status;
  141. foreach my $line ( split( "\n", $raw ) ) {
  142. my ( $key, $value ) = $line =~ m/^(\w+)=(.*)$/;
  143. $status{$key} = $value if defined $key;
  144. }
  145. return undef unless $status{state};
  146. # kill 0 rather than trusting the file: the process is orphaned, so nothing
  147. # else would ever correct a 'running' that stopped being true. Same uid, so
  148. # this is a real answer. A recycled pid could fool it, which would show a
  149. # finished run as still going rather than the other way about.
  150. if ( $status{state} eq 'running' ) {
  151. my $alive = $status{pid} && kill( 0, $status{pid} );
  152. $status{state} = 'interrupted' unless $alive;
  153. }
  154. return \%status;
  155. }
  156. # Written by the run itself, at the two moments worth recording. By rename, so
  157. # that a page drawn while the run is writing sees the old status or the new one
  158. # and never half of either -- the reader would ignore a torn file, but ignoring
  159. # it means the page says nothing was ever run.
  160. sub _write_status ( $domain, %fields ) {
  161. my $path = "$log_dir/$domain.status";
  162. my $out = join( '', map { "$_=" . ( $fields{$_} // '' ) . "\n" } sort keys %fields );
  163. local $@;
  164. eval {
  165. # Beside the file it replaces, or the rename is a copy across
  166. # filesystems and stops being atomic.
  167. local $File::Slurper::Temp::FILE_TEMP_DIR = $log_dir;
  168. local $File::Slurper::Temp::FILE_TEMP_PERMS = oct('644');
  169. File::Slurper::Temp::write_text( $path, $out );
  170. 1;
  171. } or WARN("Could not record the reprovision status for '$domain': $@");
  172. return;
  173. }
  174. =head2 _config() = HASHREF
  175. Where the provisioner is checked out, from the tCMS configuration, and where the
  176. recipes it reads are, from trog-provisioner's own rule for that.
  177. trog_provisioner the checkout, or undef
  178. recipes the directory the guests' recipes are in
  179. Undef for the checkout means the feature is off rather than broken: a site which
  180. has not configured it gets a plain guest listing, which is what it asked for.
  181. =cut
  182. sub _config {
  183. my $conf = Trog::Config::get();
  184. # Nothing to configure here: the provisioner reads this env var or that
  185. # directory, so a recipe we showed from anywhere else would be a recipe it
  186. # is not going to build from.
  187. my %config = ( recipes => ( $ENV{TROG_PROVISIONER_CONFIG} // $provisioner_config ) . "/$recipe_dir" );
  188. my $dir = $conf->param('provisioner.trog_provisioner');
  189. return \%config unless $dir && !ref $dir;
  190. # Resolved, and checked to be there. A path in a config file which does not
  191. # exist is a typo, and finding that out here beats finding it out halfway
  192. # through a reprovision.
  193. my $absolute = Cwd::abs_path($dir);
  194. if ( !$absolute || !-d $absolute ) {
  195. WARN("provisioner.trog_provisioner is set to '$dir', which is not a directory here");
  196. return \%config;
  197. }
  198. $config{trog_provisioner} = $absolute;
  199. return \%config;
  200. }
  201. # A guest name reaches the filesystem here, so it is a hostname or it is nothing.
  202. sub _safe_domain ($domain) {
  203. return undef unless defined $domain && length($domain) && length($domain) < 254;
  204. return undef if $domain =~ m/(?:^|\.)\.\.?(?:\.|$)/;
  205. my ($safe) = $domain =~ m/^([A-Za-z0-9][A-Za-z0-9._-]*)$/;
  206. return $safe;
  207. }
  208. # An installation's recipes are where they are whether tCMS knows about the
  209. # provisioner or not, but reading them is the feature, so it is off with it.
  210. sub _recipe_path ( $config, $domain ) {
  211. return undef unless $config->{trog_provisioner};
  212. my $safe = _safe_domain($domain);
  213. return undef unless $safe;
  214. my $path = "$config->{recipes}/$safe.yaml";
  215. return -f $path ? $path : undef; ## no critic (ProhibitFiletest_f) -- is there a recipe for this guest
  216. }
  217. =head2 _log_tail($domain) = STRING
  218. The last of whatever the previous reprovision said, or nothing.
  219. The run happens in a detached process which nobody is waiting on, so this file
  220. is the only account of it there is.
  221. =cut
  222. our $log_tail_bytes = 4096;
  223. sub _log_tail ($domain) {
  224. my $safe = _safe_domain($domain);
  225. return undef unless $safe;
  226. my $path = "$log_dir/$safe.log";
  227. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  228. my $text = eval { File::Slurper::read_text($path) };
  229. return undef unless defined $text;
  230. return length($text) > $log_tail_bytes ? substr( $text, -$log_tail_bytes ) : $text;
  231. }
  232. =head2 log_for($domain) = STRING or undef
  233. The whole reprovision log for a guest, for the route which serves it.
  234. Undef when there has never been a run, or when the name is not a guest name --
  235. this reaches the filesystem, so it is checked here rather than trusted from the
  236. route that called it.
  237. =cut
  238. our $log_max_bytes = 1024 * 1024;
  239. sub log_for ($domain) {
  240. my $safe = _safe_domain($domain);
  241. return undef unless $safe;
  242. my $path = "$log_dir/$safe.log";
  243. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  244. my $text = eval { File::Slurper::read_text($path) };
  245. return undef unless defined $text;
  246. # A provisioner can be chatty and this goes out in one response.
  247. return length($text) > $log_max_bytes
  248. ? "[ truncated: showing the last " . int( $log_max_bytes / 1024 ) . "KB ]\n" . substr( $text, -$log_max_bytes )
  249. : $text;
  250. }
  251. =head2 reprovision(%args) = ($ok, $message)
  252. Run bin/provision for one guest, which generates its configuration from its
  253. recipe and then builds the machine.
  254. domain which guest. Required, and validated as a hostname.
  255. passphrase the KeePass passphrase the recipe's secrets need, on stdin.
  256. user who asked, for the log.
  257. Returns immediately. Provisioning a machine takes minutes and an HTTP worker
  258. does not have minutes, so the work is handed to a detached process and the
  259. caller is told it started rather than told it finished. What happened is in
  260. logs/reprovision/$domain.log, which is what _log_tail reads back onto the page.
  261. The passphrase is passed down the child's stdin and is never written anywhere:
  262. not to the log, not to the process table, not to the configuration. It is asked
  263. for because every recipe inherits secret: values from _base, and the alternative
  264. to asking each time is keeping the master password for every secret the operator
  265. holds in a file the webserver can read.
  266. =cut
  267. sub reprovision (%args) {
  268. my $safe = _safe_domain( $args{domain} );
  269. return ( 0, 'bad guest name' ) unless $safe;
  270. # The template does not draw the button for this guest. This is what
  271. # actually stops it: /guest/reprovision is a POST anybody holding the admin
  272. # acl can craft by hand, and there would be nothing left to report to.
  273. if ( Trog::DataSource::Virt::_is_self($safe) ) {
  274. WARN("Refused to reprovision '$safe': that is this server");
  275. return ( 0, "'$safe' is this server -- refusing to reprovision it" );
  276. }
  277. my $config = _config();
  278. return ( 0, 'provisioner.trog_provisioner is not configured' ) unless $config->{trog_provisioner};
  279. my $recipe = _recipe_path( $config, $safe );
  280. return ( 0, "there is no recipe for '$safe' in $config->{recipes}" ) unless $recipe;
  281. return ( 0, 'a passphrase is required, as the provisioner asks for one' ) unless length( $args{passphrase} // '' );
  282. # One at a time. Two provisions of one machine racing each other is not
  283. # something anybody should be able to start by double clicking.
  284. my $running = status($safe);
  285. return ( 0, 'a reprovision of this guest is already running' ) if $running && $running->{state} eq 'running';
  286. my @command = ( "$config->{trog_provisioner}/bin/provision", $safe );
  287. return ( 0, "$command[0] is not there to run" ) unless -x $command[0]; ## no critic (ProhibitFiletest_rwxRWX) -- refusing early beats finding out mid-provision
  288. INFO( "Reprovision of '$safe' requested by " . ( $args{user} // 'somebody' ) );
  289. my ( $ok, $why ) = _spawn( $safe, $args{passphrase}, $config->{trog_provisioner}, \@command, $args{user} );
  290. return ( 0, $why ) unless $ok;
  291. return ( 1, "reprovision started; watch $log_dir/$safe.log" );
  292. }
  293. =head2 _spawn($domain, $passphrase, $dir, $command, $user)
  294. Fork the provisioner off where nothing is waiting for it.
  295. Double forked and setsid'd on purpose: a save signals the parent to reload the
  296. routing table, and a provision which died because a worker was recycled halfway
  297. through would leave a half-built machine. This has to outlive the request, the
  298. worker, and a restart.
  299. It runs through open() with a list, so there is no shell between us and the
  300. program, and the guest name is an argument rather than a thing that could be
  301. read as one.
  302. =cut
  303. sub _spawn ( $domain, $passphrase, $dir, $command, $user ) {
  304. my $log = "$log_dir/$domain.log";
  305. local $@;
  306. eval { File::Path::make_path($log_dir); 1 } or return ( 0, "could not make $log_dir: $@" );
  307. my $pid = fork();
  308. return ( 0, "could not fork: $!" ) unless defined $pid;
  309. return ( 1, 'started' ) if $pid;
  310. # First child: detach, fork again, and let the middle process go so that
  311. # nothing is left for the worker to reap or be blocked by.
  312. POSIX::setsid();
  313. my $grandchild = fork();
  314. POSIX::_exit(0) if !defined $grandchild || $grandchild;
  315. # From here on we are nobody's child and nothing reads our exit status, so
  316. # the log is the only way to say anything.
  317. open( my $fh, '>>', $log ) or POSIX::_exit(1);
  318. $fh->autoflush(1);
  319. my $started = time();
  320. print {$fh} "\n=== reprovision of $domain by " . ( $user // 'somebody' ) . ' at ' . localtime($started) . " ===\n";
  321. # $$ is this process, which is the one that will still be here in ten
  322. # minutes -- the two before it have already gone. status() checks it is
  323. # alive, so it has to be the pid of whatever is actually doing the work.
  324. _write_status( $domain, state => 'running', pid => $$, started => $started, user => ( $user // '' ) );
  325. print {$fh} "\n--- $command->[0] $command->[1] (in $dir)\n";
  326. # In the checkout, so that anything the provisioner writes relative to where
  327. # it was run lands there rather than in the middle of the website.
  328. if ( !chdir($dir) ) {
  329. print {$fh} "could not chdir to $dir: $!\n";
  330. POSIX::_exit(1);
  331. }
  332. # The child's own stdout and stderr are the log, so whatever the program
  333. # says lands there without a shell redirect to get wrong.
  334. open( STDOUT, '>&', $fh ) or POSIX::_exit(1);
  335. open( STDERR, '>&', $fh ) or POSIX::_exit(1);
  336. # List form on purpose, and the reason the whole thing is shaped this way: a
  337. # piped open with a list never involves a shell, so the guest name is an
  338. # argument and cannot be read as a command. The single argument form of
  339. # this would be the bug.
  340. my $ok = open( my $stdin, '|-', @$command ); ## no critic (ProhibitPipeOpen) -- list form, so no shell
  341. if ( !$ok ) {
  342. print {$fh} "could not run $command->[0]: $!\n";
  343. POSIX::_exit(1);
  344. }
  345. # What the provisioner prompts for on its way to the secrets database.
  346. # Closing this instead would make anything that asks hang forever.
  347. print {$stdin} "$passphrase\n";
  348. close($stdin);
  349. if ($?) {
  350. my $status = $? >> 8;
  351. print {$fh} "\n--- $command->[0] exited $status\n";
  352. _write_status(
  353. $domain,
  354. state => 'failed',
  355. started => $started,
  356. finished => time(),
  357. exit => $status,
  358. failed => $command->[0],
  359. user => ( $user // '' ),
  360. );
  361. POSIX::_exit($status);
  362. }
  363. print {$fh} "\n=== finished ===\n";
  364. _write_status( $domain, state => 'ok', started => $started, finished => time(), exit => 0, user => ( $user // '' ) );
  365. POSIX::_exit(0);
  366. }
  367. 1;