Virt.pm 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. package Trog::DataSource::Virt;
  2. use strict;
  3. use warnings;
  4. no warnings 'experimental';
  5. use feature qw{signatures state};
  6. use File::Path();
  7. use Sys::Virt();
  8. use Trog::Log qw{WARN INFO};
  9. =head1 Trog::DataSource::Virt
  10. Builds posts out of libvirt guests rather than out of the datastore.
  11. A post type says it wants this by naming it in its sidecar:
  12. "x-tcms-datasource": "Trog::DataSource::Virt"
  13. A series of that type then lists the guests of whichever hypervisor posts its
  14. relations pulled in, instead of listing posts somebody wrote. Nothing here is
  15. ever written to the datastore -- the guests are the source of truth, and the
  16. posts are rebuilt from them on every view.
  17. =head2 A NOTE ON SAFETY
  18. libvirt forbids virDomainScreenshot on a read-only connection, so the read path
  19. cannot protect itself by connecting read-only -- it holds a connection which is
  20. perfectly capable of destroying a guest.
  21. The discipline is therefore in the code: posts() and screenshot() call nothing
  22. but accessors, and every operation that changes a guest lives in act(), which
  23. is reached only from an explicit admin-gated POST. Keep it that way.
  24. =cut
  25. # How long a cached screenshot is considered fresh. These are console
  26. # captures, so they change slowly and are cheap to refetch.
  27. our $screenshot_ttl = 30;
  28. # Under www/assets like every other asset, in its own subtree because these are
  29. # not uploads somebody made -- they are cached datasource output, and anything
  30. # in here can be deleted at any time and will simply be refetched.
  31. #
  32. # Under private/ specifically because a console capture can show a login
  33. # prompt, a hostname, whatever the last command printed. That is the same
  34. # reasoning _handle_upload uses to put a private post's assets there, and the
  35. # screenshot route serves these to admins itself rather than relying on
  36. # anything about how www/assets is exposed.
  37. our $screenshot_dir = 'www/assets/private/datasource/virt';
  38. # Reconnecting per guest would be absurd -- one ssh handshake per hypervisor
  39. # per process is enough. Not a state var: a connection that has gone away
  40. # should be retried rather than remembered.
  41. sub _connect ( $uri, $cache = {} ) {
  42. return $cache->{$uri} if $cache->{$uri};
  43. local $@;
  44. my $conn = eval { Sys::Virt->new( uri => $uri ) };
  45. if ( !$conn ) {
  46. my $why = "$@";
  47. $why =~ s/\n.*//s;
  48. WARN("Could not connect to hypervisor '$uri': $why");
  49. return ( undef, $why );
  50. }
  51. $cache->{$uri} = $conn;
  52. return $conn;
  53. }
  54. # libvirt's numeric domain states, in the order the constants define them.
  55. my @states = (
  56. 'no state', 'running', 'blocked', 'paused',
  57. 'shutting down', 'shut off', 'crashed', 'suspended',
  58. );
  59. sub _state_name ($state) {
  60. return $states[$state] // 'unknown';
  61. }
  62. =head2 posts($series, $query) = @posts
  63. One post per guest, across every hypervisor the series' relations pulled in.
  64. A hypervisor we cannot reach becomes a single post saying so, rather than
  65. vanishing -- a page that silently omits half your infrastructure is worse than
  66. one that tells you the connection is broken.
  67. =cut
  68. sub posts ( $series, $query ) {
  69. my $hypervisors = $series->{ $series->{'x-tcms-datasource-relation'} // 'hypervisors' };
  70. return () unless ref $hypervisors eq 'ARRAY';
  71. my $form = $series->{child_form} // '';
  72. my %cache;
  73. my @out;
  74. foreach my $hypervisor (@$hypervisors) {
  75. my $uri = $hypervisor->{conn_uri};
  76. next unless $uri;
  77. my ( $conn, $why ) = _connect( $uri, \%cache );
  78. if ( !$conn ) {
  79. push( @out, _unreachable_post( $hypervisor, $series, $form, $why ) );
  80. next;
  81. }
  82. local $@;
  83. my @domains = eval { $conn->list_all_domains() };
  84. if ($@) {
  85. my $err = "$@";
  86. $err =~ s/\n.*//s;
  87. push( @out, _unreachable_post( $hypervisor, $series, $form, $err ) );
  88. next;
  89. }
  90. push( @out, map { _post_for( $_, $hypervisor, $series, $form ) } @domains );
  91. }
  92. return @out;
  93. }
  94. sub _post_for ( $domain, $hypervisor, $series, $form ) {
  95. my $name = $domain->get_name();
  96. my $info = $domain->get_info();
  97. return {
  98. # The guest's own UUID: stable across renders, and what the control
  99. # routes look it back up by.
  100. id => $domain->get_uuid_string(),
  101. title => $name,
  102. form => $form,
  103. data => '',
  104. domain => $name,
  105. state => _state_name( $info->{state} ),
  106. is_active => $domain->is_active() ? 1 : 0,
  107. memory => $info->{memory},
  108. vcpus => $info->{nrVirtCpu},
  109. hypervisor => $hypervisor->{id},
  110. hypervisor_title => $hypervisor->{title},
  111. # Fetched by the browser rather than inline, so ten guests don't mean
  112. # ten screenshots taken serially before the page can render.
  113. preview => "/guest/screenshot/$hypervisor->{id}/$name",
  114. # Enough of a post to survive being rendered like one.
  115. local_href => "/guest/$hypervisor->{id}/$name",
  116. href => '',
  117. tags => $series->{tags} // [],
  118. visibility => $series->{visibility} // 'private',
  119. created => time(),
  120. version => 0,
  121. user => $series->{user},
  122. method => 'GET',
  123. };
  124. }
  125. sub _unreachable_post ( $hypervisor, $series, $form, $why ) {
  126. return {
  127. id => "unreachable-$hypervisor->{id}",
  128. title => $hypervisor->{title} // 'hypervisor',
  129. form => $form,
  130. data => '',
  131. state => "unreachable: $why",
  132. is_active => 0,
  133. unreachable => 1,
  134. hypervisor => $hypervisor->{id},
  135. hypervisor_title => $hypervisor->{title},
  136. preview => '',
  137. local_href => '',
  138. href => '',
  139. tags => $series->{tags} // [],
  140. visibility => $series->{visibility} // 'private',
  141. created => time(),
  142. version => 0,
  143. user => $series->{user},
  144. method => 'GET',
  145. };
  146. }
  147. =head2 screenshot($hypervisor, $guest_name) = ($path, $error)
  148. Path to a reasonably fresh PNG of the guest's console.
  149. Cached on disk, because a page of guests means one of these per guest and they
  150. are only interesting to about the nearest half minute. libvirt hands back the
  151. mimetype; qemu gives us PNG already, so there is nothing to convert.
  152. Keyed by hypervisor as well as by guest -- guest names are only unique within
  153. one hypervisor, and two of them called 'staging' would otherwise show each
  154. other's console.
  155. =cut
  156. sub screenshot ( $hypervisor, $guest_name ) {
  157. my ($safe) = ( $guest_name // '' ) =~ m/^([A-Za-z0-9._-]+)$/;
  158. return ( undef, 'bad guest name' ) unless $safe;
  159. my ($host) = ( $hypervisor->{id} // '' ) =~ m/^([A-Za-z0-9._-]+)$/;
  160. return ( undef, 'bad hypervisor id' ) unless $host;
  161. my $conn_uri = $hypervisor->{conn_uri};
  162. return ( undef, 'hypervisor has no connection uri' ) unless $conn_uri;
  163. my $dir = "$screenshot_dir/$host";
  164. my $path = "$dir/$safe.png";
  165. return ( $path, undef ) if -f $path && ( time() - ( stat($path) )[9] ) < $screenshot_ttl;
  166. my ( $conn, $why ) = _connect($conn_uri);
  167. return ( undef, $why ) unless $conn;
  168. local $@;
  169. my $data = eval {
  170. my ($domain) = grep { $_->get_name() eq $safe } $conn->list_all_domains();
  171. die "no such guest\n" unless $domain;
  172. my $stream = $conn->new_stream();
  173. $domain->screenshot( $stream, 0, 0 );
  174. my $buffer = '';
  175. $stream->recv_all( sub { my ( undef, $chunk ) = @_; $buffer .= $chunk; return length($chunk) } );
  176. $stream->finish();
  177. $buffer;
  178. };
  179. if ( !$data ) {
  180. my $err = "$@";
  181. $err =~ s/\n.*//s;
  182. return ( undef, $err );
  183. }
  184. File::Path::make_path($dir);
  185. open( my $fh, '>', $path ) or return ( undef, "could not cache the screenshot: $!" );
  186. binmode $fh;
  187. print {$fh} $data;
  188. close $fh;
  189. return ( $path, undef );
  190. }
  191. =head2 act($action, $conn_uri, $domain_name, $user) = ($ok, $message)
  192. The operations which change a guest.
  193. Deliberately the only sub here that does, and deliberately not reachable from
  194. the render path -- see the safety note at the top. Everything it does is
  195. logged with the user who asked for it.
  196. =cut
  197. sub act ( $action, $conn_uri, $domain_name, $user ) {
  198. my ($safe) = $domain_name =~ m/^([A-Za-z0-9._-]+)$/;
  199. return ( 0, 'bad guest name' ) unless $safe;
  200. my ( $conn, $why ) = _connect($conn_uri);
  201. return ( 0, "could not reach the hypervisor: $why" ) unless $conn;
  202. local $@;
  203. my ($domain) = eval {
  204. grep { $_->get_name() eq $safe } $conn->list_all_domains();
  205. };
  206. return ( 0, "no guest called '$safe' on that hypervisor" ) unless $domain;
  207. INFO("Guest action '$action' on '$safe' requested by $user");
  208. my %actions = (
  209. poweron => sub { $_[0]->create() },
  210. poweroff => sub { $_[0]->shutdown() },
  211. snapshot => sub { $_[0]->create_snapshot() },
  212. destroy => sub { $_[0]->destroy() },
  213. );
  214. my $doit = $actions{ $action // '' };
  215. return ( 0, "'$action' is not something we do to a guest" ) unless $doit;
  216. eval { $doit->($domain); 1 } or do {
  217. my $err = "$@";
  218. $err =~ s/\n.*//s;
  219. WARN("Guest action '$action' on '$safe' failed: $err");
  220. return ( 0, $err );
  221. };
  222. return ( 1, "$action: ok" );
  223. }
  224. 1;