Virt.pm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. package Trog::DataSource::Virt;
  2. use v5.36;
  3. use re '/aa';
  4. use File::Path();
  5. use Sys::Hostname::FQDN();
  6. use Sys::Virt();
  7. use Trog::Config();
  8. use Trog::DataSource();
  9. use Trog::Log qw{WARN INFO};
  10. =head1 Trog::DataSource::Virt
  11. Builds posts out of libvirt guests rather than out of the datastore.
  12. A post type says it wants this by naming it in its sidecar:
  13. "x-tcms-datasource": "Trog::DataSource::Virt"
  14. A series of that type then lists the guests of whichever hypervisor posts its
  15. relations pulled in, instead of listing posts somebody wrote. Nothing here is
  16. ever written to the datastore -- the guests are the source of truth, and the
  17. posts are rebuilt from them on every view.
  18. =head2 EDITABLE
  19. False. A guest is built from libvirt every time the page is drawn and has
  20. nothing behind it to save, so a post type backed by this wants no editor: a
  21. form posting to /post/save would write a real post into the datastore which
  22. would then sit alongside, and collide with, the synthesized ones.
  23. =cut
  24. use constant EDITABLE => 0;
  25. =head2 A NOTE ON SAFETY
  26. libvirt forbids virDomainScreenshot on a read-only connection, so the read path
  27. cannot protect itself by connecting read-only -- it holds a connection which is
  28. perfectly capable of destroying a guest.
  29. The discipline is therefore in the code: posts() and screenshot() call nothing
  30. but accessors, and every operation that changes a guest lives in act(), which
  31. is reached only from an explicit admin-gated POST. Keep it that way.
  32. =cut
  33. # How long a cached screenshot is considered fresh. These are console
  34. # captures, so they change slowly and are cheap to refetch.
  35. our $screenshot_ttl = 30;
  36. # Under www/assets like every other asset, in its own subtree because these are
  37. # not uploads somebody made -- they are cached datasource output, and anything
  38. # in here can be deleted at any time and will simply be refetched.
  39. #
  40. # Under private/ specifically because a console capture can show a login
  41. # prompt, a hostname, whatever the last command printed. That is the same
  42. # reasoning _handle_upload uses to put a private post's assets there, and the
  43. # screenshot route serves these to admins itself rather than relying on
  44. # anything about how www/assets is exposed.
  45. our $screenshot_dir = 'www/assets/private/datasource/virt';
  46. # Reconnecting per guest would be absurd -- one ssh handshake per hypervisor
  47. # per process is enough. Not a state var: a connection that has gone away
  48. # should be retried rather than remembered.
  49. sub _connect ( $uri, $cache = {} ) {
  50. return $cache->{$uri} if $cache->{$uri};
  51. local $@;
  52. my $conn = eval { Sys::Virt->new( uri => $uri ) };
  53. if ( !$conn ) {
  54. my $why = "$@";
  55. $why =~ s/\n.*//s;
  56. WARN("Could not connect to hypervisor '$uri': $why");
  57. return ( undef, $why );
  58. }
  59. $cache->{$uri} = $conn;
  60. return $conn;
  61. }
  62. # libvirt's numeric domain states, in the order the constants define them.
  63. my @states = (
  64. 'no state', 'running', 'blocked', 'paused',
  65. 'shutting down', 'shut off', 'crashed', 'suspended',
  66. );
  67. sub _state_name ($state) {
  68. return $states[$state] // 'unknown';
  69. }
  70. # What this machine calls itself. Not a state var so that a test can pretend
  71. # to be a different host without having to lie to Sys::Hostname.
  72. our $hostname;
  73. sub _hostname {
  74. return $hostname if defined $hostname;
  75. local $@;
  76. # Sys::Hostname croaks rather than returning undef when it cannot tell, and
  77. # the configured hostname is the next best thing we know about ourselves.
  78. $hostname =
  79. eval { Sys::Hostname::FQDN::fqdn() }
  80. || eval { Trog::Config->get()->param('general.hostname') }
  81. || '';
  82. return $hostname;
  83. }
  84. =head2 _is_self($name)
  85. Whether a guest by this name is the machine we are running on.
  86. Such a guest is acting as dom0: it is serving the page the guest list appears
  87. on, so powering it off or destroying it takes the site down along with whatever
  88. asked for that.
  89. Returns true if the guest name is the same as the fqdn of this machine.
  90. Returns false otherwise.
  91. =cut
  92. sub _is_self ($name) {
  93. my $me = lc( _hostname() );
  94. $name = lc( $name // '' );
  95. print("Name comp: $me $name\n");
  96. return 1 if $name eq $me;
  97. return 0;
  98. }
  99. =head2 posts($series, $query) = @posts
  100. One post per guest, across every hypervisor the series' relations pulled in.
  101. A hypervisor we cannot reach becomes a single post saying so, rather than
  102. vanishing -- a page that silently omits half your infrastructure is worse than
  103. one that tells you the connection is broken.
  104. =cut
  105. sub posts ( $series, $query ) {
  106. my $hypervisors = $series->{ $series->{'x-tcms-datasource-relation'} // 'hypervisors' };
  107. return () unless ref $hypervisors eq 'ARRAY';
  108. my $form = $series->{child_form} // '';
  109. my %cache;
  110. my @out;
  111. foreach my $hypervisor (@$hypervisors) {
  112. my $uri = $hypervisor->{conn_uri};
  113. next unless $uri;
  114. my ( $conn, $why ) = _connect( $uri, \%cache );
  115. if ( !$conn ) {
  116. push( @out, _unreachable_post( $hypervisor, $series, $form, $why ) );
  117. next;
  118. }
  119. local $@;
  120. my @domains = eval { $conn->list_all_domains() };
  121. if ($@) {
  122. my $err = "$@";
  123. $err =~ s/\n.*//s;
  124. push( @out, _unreachable_post( $hypervisor, $series, $form, $err ) );
  125. next;
  126. }
  127. push( @out, map { _post_for( $_, $hypervisor, $series, $form ) } @domains );
  128. }
  129. return @out;
  130. }
  131. =head2 filter($query, @posts) = @posts
  132. Apply the reader's search to the guest list.
  133. A guest post's body is empty -- everything about it is in named fields -- so the
  134. default, which searches a post's title and body, would only ever match the guest
  135. name. Search what the page actually shows instead: the guest name, its state,
  136. and the hypervisor it is on. Searching 'shut' for the stopped guests, or a
  137. hypervisor's title for everything on it, is the thing somebody typing in that
  138. box on this page is trying to do.
  139. Everything else about the query means what it does elsewhere, so it is left to
  140. Trog::DataSource::filter.
  141. =cut
  142. sub filter ( $query, @posts ) {
  143. $query //= {};
  144. if ( length( $query->{like} // '' ) ) {
  145. my $like = $query->{like};
  146. @posts = grep {
  147. Trog::DataSource::searchable_match(
  148. $like,
  149. $_->{title}, $_->{domain}, $_->{state}, $_->{hypervisor_title}, $_->{hypervisor},
  150. )
  151. } @posts;
  152. }
  153. # Without like, since that one is answered above.
  154. return Trog::DataSource::filter( { %$query, like => undef }, @posts );
  155. }
  156. =head2 lang() = STRING
  157. What the search box searches on a page of guests.
  158. =head2 help() = STRING
  159. Where to read about it.
  160. =cut
  161. sub lang { 'Case insensitive substring of a guest name, state or hypervisor' }
  162. sub help { 'https://en.wikipedia.org/wiki/Substring' }
  163. sub _post_for ( $domain, $hypervisor, $series, $form ) {
  164. my $name = $domain->get_name();
  165. my $info = $domain->get_info();
  166. return {
  167. # The guest's own UUID: stable across renders, and what the control
  168. # routes look it back up by.
  169. id => $domain->get_uuid_string(),
  170. title => $name,
  171. form => $form,
  172. data => '',
  173. domain => $name,
  174. state => _state_name( $info->{state} ),
  175. is_active => $domain->is_active() ? 1 : 0,
  176. is_self => _is_self($name),
  177. memory => $info->{memory},
  178. vcpus => $info->{nrVirtCpu},
  179. hypervisor => $hypervisor->{id},
  180. hypervisor_title => $hypervisor->{title},
  181. # Fetched by the browser rather than inline, so ten guests don't mean
  182. # ten screenshots taken serially before the page can render.
  183. preview => "/guest/screenshot/$hypervisor->{id}/$name",
  184. # Enough of a post to survive being rendered like one.
  185. local_href => "/guest/$hypervisor->{id}/$name",
  186. href => '',
  187. tags => $series->{tags} // [],
  188. visibility => $series->{visibility} // 'private',
  189. created => time(),
  190. version => 0,
  191. user => $series->{user},
  192. method => 'GET',
  193. };
  194. }
  195. sub _unreachable_post ( $hypervisor, $series, $form, $why ) {
  196. return {
  197. id => "unreachable-$hypervisor->{id}",
  198. title => $hypervisor->{title} // 'hypervisor',
  199. form => $form,
  200. data => '',
  201. state => "unreachable: $why",
  202. is_active => 0,
  203. unreachable => 1,
  204. hypervisor => $hypervisor->{id},
  205. hypervisor_title => $hypervisor->{title},
  206. preview => '',
  207. local_href => '',
  208. href => '',
  209. tags => $series->{tags} // [],
  210. visibility => $series->{visibility} // 'private',
  211. created => time(),
  212. version => 0,
  213. user => $series->{user},
  214. method => 'GET',
  215. };
  216. }
  217. =head2 screenshot($hypervisor, $guest_name) = ($path, $error)
  218. Path to a reasonably fresh PNG of the guest's console.
  219. Cached on disk, because a page of guests means one of these per guest and they
  220. are only interesting to about the nearest half minute. libvirt hands back the
  221. mimetype; qemu gives us PNG already, so there is nothing to convert.
  222. Keyed by hypervisor as well as by guest -- guest names are only unique within
  223. one hypervisor, and two of them called 'staging' would otherwise show each
  224. other's console.
  225. =cut
  226. sub screenshot ( $hypervisor, $guest_name ) {
  227. my ($safe) = ( $guest_name // '' ) =~ m/^([A-Za-z0-9._-]+)$/;
  228. return ( undef, 'bad guest name' ) unless $safe;
  229. my ($host) = ( $hypervisor->{id} // '' ) =~ m/^([A-Za-z0-9._-]+)$/;
  230. return ( undef, 'bad hypervisor id' ) unless $host;
  231. my $conn_uri = $hypervisor->{conn_uri};
  232. return ( undef, 'hypervisor has no connection uri' ) unless $conn_uri;
  233. my $dir = "$screenshot_dir/$host";
  234. my $path = "$dir/$safe.png";
  235. # One stat rather than -f and then a second stat for the mtime. A missing
  236. # file gives the empty list, so $mtime is undef and we fall through to a
  237. # fresh capture.
  238. my $mtime = ( stat($path) )[9];
  239. return ( $path, undef ) if $mtime && ( time() - $mtime ) < $screenshot_ttl;
  240. my ( $conn, $why ) = _connect($conn_uri);
  241. return ( undef, $why ) unless $conn;
  242. local $@;
  243. my $data = eval {
  244. my ($domain) = grep { $_->get_name() eq $safe } $conn->list_all_domains();
  245. die "no such guest\n" unless $domain;
  246. my $stream = $conn->new_stream();
  247. $domain->screenshot( $stream, 0, 0 );
  248. my $buffer = '';
  249. $stream->recv_all( sub { my ( undef, $chunk ) = @_; $buffer .= $chunk; return length($chunk) } );
  250. $stream->finish();
  251. $buffer;
  252. };
  253. if ( !$data ) {
  254. my $err = "$@";
  255. $err =~ s/\n.*//s;
  256. return ( undef, $err );
  257. }
  258. File::Path::make_path($dir);
  259. open( my $fh, '>', $path ) or return ( undef, "could not cache the screenshot: $!" );
  260. binmode $fh;
  261. print {$fh} $data;
  262. close $fh;
  263. return ( $path, undef );
  264. }
  265. =head2 act($action, $conn_uri, $domain_name, $user) = ($ok, $message)
  266. The operations which change a guest.
  267. Deliberately the only sub here that does, and deliberately not reachable from
  268. the render path -- see the safety note at the top. Everything it does is
  269. logged with the user who asked for it.
  270. =cut
  271. sub act ( $action, $conn_uri, $domain_name, $user ) {
  272. my ($safe) = $domain_name =~ m/^([A-Za-z0-9._-]+)$/;
  273. return ( 0, 'bad guest name' ) unless $safe;
  274. # The template draws neither of these buttons for this guest; this is what
  275. # actually stops it happening. /guest/act is a POST anybody holding the
  276. # admin acl can craft by hand, and if it went through there would be
  277. # nothing left running to report the mistake.
  278. if ( _is_self($safe) && ( $action // '' ) =~ m/^(?:poweroff|destroy)$/ ) {
  279. WARN("Refused guest action '$action' on '$safe': that is this server");
  280. return ( 0, "'$safe' is this server -- refusing to $action it" );
  281. }
  282. my ( $conn, $why ) = _connect($conn_uri);
  283. return ( 0, "could not reach the hypervisor: $why" ) unless $conn;
  284. local $@;
  285. my ($domain) = eval {
  286. grep { $_->get_name() eq $safe } $conn->list_all_domains();
  287. };
  288. return ( 0, "no guest called '$safe' on that hypervisor" ) unless $domain;
  289. INFO("Guest action '$action' on '$safe' requested by $user");
  290. my %actions = (
  291. poweron => sub { $_[0]->create() },
  292. poweroff => sub { $_[0]->shutdown() },
  293. snapshot => sub { $_[0]->create_snapshot() },
  294. destroy => sub { $_[0]->destroy() },
  295. );
  296. my $doit = $actions{ $action // '' };
  297. return ( 0, "'$action' is not something we do to a guest" ) unless $doit;
  298. eval { $doit->($domain); 1 } or do {
  299. my $err = "$@";
  300. $err =~ s/\n.*//s;
  301. WARN("Guest action '$action' on '$safe' failed: $err");
  302. return ( 0, $err );
  303. };
  304. return ( 1, "$action: ok" );
  305. }
  306. 1;