ProvisionedVirt.pm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 POSIX ();
  10. use Trog::Config ();
  11. use Trog::DataSource ();
  12. use Trog::DataSource::Virt();
  13. use Trog::Log qw{WARN INFO};
  14. =head1 Trog::DataSource::ProvisionedVirt
  15. Trog::DataSource::Virt, plus the recipe each guest was built from and a button to
  16. build it again.
  17. Everything about listing guests is inherited unchanged -- this is the same
  18. libvirt connection, the same posts, the same search and the same refusal to be
  19. cached. What it adds is the other half of the story: a guest on a Troglodyne
  20. hypervisor was provisioned from a recipe, and the recipe is on disk next to the
  21. hypervisor rather than anywhere libvirt can tell you about.
  22. Two repositories between them own that lifecycle:
  23. provisioners recipes.d/$domain.yaml, and bin/new_config which turns
  24. a recipe into a configuration package
  25. trog-provisioner bin/provision, which turns that package into a machine
  26. Say where they are in the tCMS configuration and this becomes useful; leave them
  27. out and it degrades to plain Virt, which is what it is.
  28. [provisioner]
  29. provisioners = /home/you/Code/provisioners
  30. trog_provisioner = /home/you/Code/trog-provisioner
  31. =head1 A NOTE ON SAFETY
  32. Reprovisioning is not a recoverable operation. It destroys the guest and builds
  33. it again from its recipe, and whatever was on it that the recipe does not
  34. describe does not come back.
  35. The discipline is the same as its parent's, and for the same reasons. It is
  36. POST only and admin only; it refuses outright for the guest tCMS is itself
  37. running on, whatever the template chose to draw; and nothing it runs goes near a
  38. shell, so a guest name is an argument and can never be a command.
  39. =cut
  40. our $recipe_dir = 'recipes.d';
  41. our $log_dir = 'logs/reprovision';
  42. =head1 FUNCTIONS
  43. =head2 posts($series, $query) = @posts
  44. The guests Trog::DataSource::Virt would have listed, each carrying what we know
  45. about how it was built:
  46. recipe the recipe's YAML, as text, for the page to show
  47. recipe_path where that came from
  48. has_recipe whether there was one at all
  49. can_reprovision whether the button should be drawn
  50. reprovision_log the tail of the last run, when there has been one
  51. A guest with no recipe is still listed. Plenty of guests on a hypervisor were
  52. not built by this, and saying nothing about them is better than hiding them.
  53. =cut
  54. sub posts ( $series, $query ) {
  55. my @guests = Trog::DataSource::Virt::posts( $series, $query );
  56. my $config = _config();
  57. return map { _with_recipe( $_, $config ) } @guests;
  58. }
  59. sub _with_recipe ( $post, $config ) {
  60. return $post if $post->{unreachable};
  61. my $domain = $post->{domain} // '';
  62. my $path = _recipe_path( $config, $domain );
  63. if ($path) {
  64. my $recipe = eval { File::Slurper::read_text($path) };
  65. if ( defined $recipe ) {
  66. $post->{recipe} = $recipe;
  67. $post->{recipe_path} = $path;
  68. $post->{has_recipe} = 1;
  69. }
  70. else {
  71. WARN("Could not read the recipe for '$domain' at $path: $@");
  72. }
  73. }
  74. # Both halves have to be there to run the lifecycle, and we will not rebuild
  75. # the machine we are answering the request from -- see act() in the parent,
  76. # which refuses to power that one off for the same reason.
  77. $post->{can_reprovision} =
  78. ( $post->{has_recipe} && $config->{provisioners} && $config->{trog_provisioner} && !$post->{is_self} ) ? 1 : 0;
  79. $post->{reprovision_log} = _log_tail($domain);
  80. return $post;
  81. }
  82. =head2 _config() = HASHREF
  83. Where the two repositories are, from the tCMS configuration.
  84. Undef for either means the feature is off rather than broken: a site which has
  85. not configured them gets a plain guest listing, which is what it asked for.
  86. =cut
  87. sub _config {
  88. my $conf = Trog::Config::get();
  89. my %config;
  90. foreach my $key (qw{provisioners trog_provisioner}) {
  91. my $dir = $conf->param("provisioner.$key");
  92. next unless $dir && !ref $dir;
  93. # Resolved, and checked to be there. A path in a config file which does
  94. # not exist is a typo, and finding that out here beats finding it out
  95. # halfway through a reprovision.
  96. my $absolute = Cwd::abs_path($dir);
  97. if ( !$absolute || !-d $absolute ) {
  98. WARN("provisioner.$key is set to '$dir', which is not a directory here");
  99. next;
  100. }
  101. $config{$key} = $absolute;
  102. }
  103. return \%config;
  104. }
  105. # A guest name reaches the filesystem here, so it is a hostname or it is nothing.
  106. sub _safe_domain ($domain) {
  107. return undef unless defined $domain && length($domain) && length($domain) < 254;
  108. return undef if $domain =~ m/(?:^|\.)\.\.?(?:\.|$)/;
  109. my ($safe) = $domain =~ m/^([A-Za-z0-9][A-Za-z0-9._-]*)$/;
  110. return $safe;
  111. }
  112. sub _recipe_path ( $config, $domain ) {
  113. return undef unless $config->{provisioners};
  114. my $safe = _safe_domain($domain);
  115. return undef unless $safe;
  116. my $path = "$config->{provisioners}/$recipe_dir/$safe.yaml";
  117. return -f $path ? $path : undef; ## no critic (ProhibitFiletest_f) -- is there a recipe for this guest
  118. }
  119. =head2 _log_tail($domain) = STRING
  120. The last of whatever the previous reprovision said, or nothing.
  121. The run happens in a detached process which nobody is waiting on, so this file
  122. is the only account of it there is.
  123. =cut
  124. our $log_tail_bytes = 4096;
  125. sub _log_tail ($domain) {
  126. my $safe = _safe_domain($domain);
  127. return undef unless $safe;
  128. my $path = "$log_dir/$safe.log";
  129. return undef unless -f $path; ## no critic (ProhibitFiletest_f) -- has this ever run
  130. my $text = eval { File::Slurper::read_text($path) };
  131. return undef unless defined $text;
  132. return length($text) > $log_tail_bytes ? substr( $text, -$log_tail_bytes ) : $text;
  133. }
  134. =head2 reprovision(%args) = ($ok, $message)
  135. Run the full lifecycle for one guest: bin/new_config in provisioners, and then
  136. bin/provision in trog-provisioner.
  137. domain which guest. Required, and validated as a hostname.
  138. passphrase the KeePass passphrase new_config asks for on stdin.
  139. user who asked, for the log.
  140. Returns immediately. Provisioning a machine takes minutes and an HTTP worker
  141. does not have minutes, so the work is handed to a detached process and the
  142. caller is told it started rather than told it finished. What happened is in
  143. logs/reprovision/$domain.log, which is what _log_tail reads back onto the page.
  144. The passphrase is passed down the child's stdin and is never written anywhere:
  145. not to the log, not to the process table, not to the configuration. new_config
  146. prompts for it because every recipe inherits secret: values from _base, and the
  147. alternative to asking each time is keeping the master password for every secret
  148. the operator holds in a file the webserver can read.
  149. =cut
  150. sub reprovision (%args) {
  151. my $safe = _safe_domain( $args{domain} );
  152. return ( 0, 'bad guest name' ) unless $safe;
  153. # The template does not draw the button for this guest. This is what
  154. # actually stops it: /guest/reprovision is a POST anybody holding the admin
  155. # acl can craft by hand, and there would be nothing left to report to.
  156. if ( Trog::DataSource::Virt::_is_self($safe) ) {
  157. WARN("Refused to reprovision '$safe': that is this server");
  158. return ( 0, "'$safe' is this server -- refusing to reprovision it" );
  159. }
  160. my $config = _config();
  161. return ( 0, 'provisioner.provisioners is not configured' ) unless $config->{provisioners};
  162. return ( 0, 'provisioner.trog_provisioner is not configured' ) unless $config->{trog_provisioner};
  163. my $recipe = _recipe_path( $config, $safe );
  164. return ( 0, "there is no recipe for '$safe' in $recipe_dir" ) unless $recipe;
  165. return ( 0, 'a passphrase is required, as new_config asks for one' ) unless length( $args{passphrase} // '' );
  166. my @lifecycle = (
  167. [ $config->{provisioners}, "$config->{provisioners}/bin/new_config", $safe ],
  168. [ $config->{trog_provisioner}, "$config->{trog_provisioner}/bin/provision", $safe ],
  169. );
  170. foreach my $step (@lifecycle) {
  171. my ( undef, $program ) = @$step;
  172. return ( 0, "$program is not there to run" ) unless -x $program; ## no critic (ProhibitFiletest_rwxRWX) -- refusing early beats finding out mid-lifecycle
  173. }
  174. INFO( "Reprovision of '$safe' requested by " . ( $args{user} // 'somebody' ) );
  175. my ( $ok, $why ) = _spawn( $safe, $args{passphrase}, \@lifecycle, $args{user} );
  176. return ( 0, $why ) unless $ok;
  177. return ( 1, "reprovision started; watch $log_dir/$safe.log" );
  178. }
  179. =head2 _spawn($domain, $passphrase, $lifecycle, $user)
  180. Fork the lifecycle off where nothing is waiting for it.
  181. Double forked and setsid'd on purpose: a save signals the parent to reload the
  182. routing table, and a provision which died because a worker was recycled halfway
  183. through would leave a half-built machine. This has to outlive the request, the
  184. worker, and a restart.
  185. Each step runs through open() with a list, so there is no shell between us and
  186. the program, and the guest name is an argument rather than a thing that could be
  187. read as one.
  188. =cut
  189. sub _spawn ( $domain, $passphrase, $lifecycle, $user ) {
  190. my $log = "$log_dir/$domain.log";
  191. local $@;
  192. eval { File::Path::make_path($log_dir); 1 } or return ( 0, "could not make $log_dir: $@" );
  193. my $pid = fork();
  194. return ( 0, "could not fork: $!" ) unless defined $pid;
  195. return ( 1, 'started' ) if $pid;
  196. # First child: detach, fork again, and let the middle process go so that
  197. # nothing is left for the worker to reap or be blocked by.
  198. POSIX::setsid();
  199. my $grandchild = fork();
  200. POSIX::_exit(0) if !defined $grandchild || $grandchild;
  201. # From here on we are nobody's child and nothing reads our exit status, so
  202. # the log is the only way to say anything.
  203. open( my $fh, '>>', $log ) or POSIX::_exit(1);
  204. $fh->autoflush(1);
  205. print {$fh} "\n=== reprovision of $domain by " . ( $user // 'somebody' ) . ' at ' . localtime() . " ===\n";
  206. foreach my $step (@$lifecycle) {
  207. my ( $dir, @command ) = @$step;
  208. print {$fh} "\n--- $command[0] $command[1] (in $dir)\n";
  209. if ( !chdir($dir) ) {
  210. print {$fh} "could not chdir to $dir: $!\n";
  211. POSIX::_exit(1);
  212. }
  213. # The child's own stdout and stderr are the log, so whatever the program
  214. # says lands there without a shell redirect to get wrong.
  215. open( STDOUT, '>&', $fh ) or POSIX::_exit(1);
  216. open( STDERR, '>&', $fh ) or POSIX::_exit(1);
  217. # List form on purpose, and the reason the whole thing is shaped this
  218. # way: a piped open with a list never involves a shell, so the guest
  219. # name is an argument and cannot be read as a command. The single
  220. # argument form of this would be the bug.
  221. my $ok = open( my $stdin, '|-', @command ); ## no critic (ProhibitPipeOpen) -- list form, so no shell
  222. if ( !$ok ) {
  223. print {$fh} "could not run $command[0]: $!\n";
  224. POSIX::_exit(1);
  225. }
  226. # What new_config prompts for. The second step ignores it, and giving
  227. # it a closed stdin instead would make anything that asks hang forever.
  228. print {$stdin} "$passphrase\n";
  229. close($stdin);
  230. if ($?) {
  231. my $status = $? >> 8;
  232. print {$fh} "\n--- $command[0] exited $status; stopping here\n";
  233. POSIX::_exit($status);
  234. }
  235. }
  236. print {$fh} "\n=== finished ===\n";
  237. POSIX::_exit(0);
  238. }
  239. 1;