Virt.pm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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::Hostname::FQDN();
  8. use Sys::Virt();
  9. use Trog::Config();
  10. use Trog::Log qw{WARN INFO};
  11. =head1 Trog::DataSource::Virt
  12. Builds posts out of libvirt guests rather than out of the datastore.
  13. A post type says it wants this by naming it in its sidecar:
  14. "x-tcms-datasource": "Trog::DataSource::Virt"
  15. A series of that type then lists the guests of whichever hypervisor posts its
  16. relations pulled in, instead of listing posts somebody wrote. Nothing here is
  17. ever written to the datastore -- the guests are the source of truth, and the
  18. posts are rebuilt from them on every view.
  19. =head2 EDITABLE
  20. False. A guest is built from libvirt every time the page is drawn and has
  21. nothing behind it to save, so a post type backed by this wants no editor: a
  22. form posting to /post/save would write a real post into the datastore which
  23. would then sit alongside, and collide with, the synthesized ones.
  24. =cut
  25. use constant EDITABLE => 0;
  26. =head2 A NOTE ON SAFETY
  27. libvirt forbids virDomainScreenshot on a read-only connection, so the read path
  28. cannot protect itself by connecting read-only -- it holds a connection which is
  29. perfectly capable of destroying a guest.
  30. The discipline is therefore in the code: posts() and screenshot() call nothing
  31. but accessors, and every operation that changes a guest lives in act(), which
  32. is reached only from an explicit admin-gated POST. Keep it that way.
  33. =cut
  34. # How long a cached screenshot is considered fresh. These are console
  35. # captures, so they change slowly and are cheap to refetch.
  36. our $screenshot_ttl = 30;
  37. # Under www/assets like every other asset, in its own subtree because these are
  38. # not uploads somebody made -- they are cached datasource output, and anything
  39. # in here can be deleted at any time and will simply be refetched.
  40. #
  41. # Under private/ specifically because a console capture can show a login
  42. # prompt, a hostname, whatever the last command printed. That is the same
  43. # reasoning _handle_upload uses to put a private post's assets there, and the
  44. # screenshot route serves these to admins itself rather than relying on
  45. # anything about how www/assets is exposed.
  46. our $screenshot_dir = 'www/assets/private/datasource/virt';
  47. # Reconnecting per guest would be absurd -- one ssh handshake per hypervisor
  48. # per process is enough. Not a state var: a connection that has gone away
  49. # should be retried rather than remembered.
  50. sub _connect ( $uri, $cache = {} ) {
  51. return $cache->{$uri} if $cache->{$uri};
  52. local $@;
  53. my $conn = eval { Sys::Virt->new( uri => $uri ) };
  54. if ( !$conn ) {
  55. my $why = "$@";
  56. $why =~ s/\n.*//s;
  57. WARN("Could not connect to hypervisor '$uri': $why");
  58. return ( undef, $why );
  59. }
  60. $cache->{$uri} = $conn;
  61. return $conn;
  62. }
  63. # libvirt's numeric domain states, in the order the constants define them.
  64. my @states = (
  65. 'no state', 'running', 'blocked', 'paused',
  66. 'shutting down', 'shut off', 'crashed', 'suspended',
  67. );
  68. sub _state_name ($state) {
  69. return $states[$state] // 'unknown';
  70. }
  71. # What this machine calls itself. Not a state var so that a test can pretend
  72. # to be a different host without having to lie to Sys::Hostname.
  73. our $hostname;
  74. sub _hostname {
  75. return $hostname if defined $hostname;
  76. local $@;
  77. # Sys::Hostname croaks rather than returning undef when it cannot tell, and
  78. # the configured hostname is the next best thing we know about ourselves.
  79. $hostname = 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. sub _post_for ( $domain, $hypervisor, $series, $form ) {
  132. my $name = $domain->get_name();
  133. my $info = $domain->get_info();
  134. return {
  135. # The guest's own UUID: stable across renders, and what the control
  136. # routes look it back up by.
  137. id => $domain->get_uuid_string(),
  138. title => $name,
  139. form => $form,
  140. data => '',
  141. domain => $name,
  142. state => _state_name( $info->{state} ),
  143. is_active => $domain->is_active() ? 1 : 0,
  144. is_self => _is_self($name),
  145. memory => $info->{memory},
  146. vcpus => $info->{nrVirtCpu},
  147. hypervisor => $hypervisor->{id},
  148. hypervisor_title => $hypervisor->{title},
  149. # Fetched by the browser rather than inline, so ten guests don't mean
  150. # ten screenshots taken serially before the page can render.
  151. preview => "/guest/screenshot/$hypervisor->{id}/$name",
  152. # Enough of a post to survive being rendered like one.
  153. local_href => "/guest/$hypervisor->{id}/$name",
  154. href => '',
  155. tags => $series->{tags} // [],
  156. visibility => $series->{visibility} // 'private',
  157. created => time(),
  158. version => 0,
  159. user => $series->{user},
  160. method => 'GET',
  161. };
  162. }
  163. sub _unreachable_post ( $hypervisor, $series, $form, $why ) {
  164. return {
  165. id => "unreachable-$hypervisor->{id}",
  166. title => $hypervisor->{title} // 'hypervisor',
  167. form => $form,
  168. data => '',
  169. state => "unreachable: $why",
  170. is_active => 0,
  171. unreachable => 1,
  172. hypervisor => $hypervisor->{id},
  173. hypervisor_title => $hypervisor->{title},
  174. preview => '',
  175. local_href => '',
  176. href => '',
  177. tags => $series->{tags} // [],
  178. visibility => $series->{visibility} // 'private',
  179. created => time(),
  180. version => 0,
  181. user => $series->{user},
  182. method => 'GET',
  183. };
  184. }
  185. =head2 screenshot($hypervisor, $guest_name) = ($path, $error)
  186. Path to a reasonably fresh PNG of the guest's console.
  187. Cached on disk, because a page of guests means one of these per guest and they
  188. are only interesting to about the nearest half minute. libvirt hands back the
  189. mimetype; qemu gives us PNG already, so there is nothing to convert.
  190. Keyed by hypervisor as well as by guest -- guest names are only unique within
  191. one hypervisor, and two of them called 'staging' would otherwise show each
  192. other's console.
  193. =cut
  194. sub screenshot ( $hypervisor, $guest_name ) {
  195. my ($safe) = ( $guest_name // '' ) =~ m/^([A-Za-z0-9._-]+)$/;
  196. return ( undef, 'bad guest name' ) unless $safe;
  197. my ($host) = ( $hypervisor->{id} // '' ) =~ m/^([A-Za-z0-9._-]+)$/;
  198. return ( undef, 'bad hypervisor id' ) unless $host;
  199. my $conn_uri = $hypervisor->{conn_uri};
  200. return ( undef, 'hypervisor has no connection uri' ) unless $conn_uri;
  201. my $dir = "$screenshot_dir/$host";
  202. my $path = "$dir/$safe.png";
  203. return ( $path, undef ) if -f $path && ( time() - ( stat($path) )[9] ) < $screenshot_ttl;
  204. my ( $conn, $why ) = _connect($conn_uri);
  205. return ( undef, $why ) unless $conn;
  206. local $@;
  207. my $data = eval {
  208. my ($domain) = grep { $_->get_name() eq $safe } $conn->list_all_domains();
  209. die "no such guest\n" unless $domain;
  210. my $stream = $conn->new_stream();
  211. $domain->screenshot( $stream, 0, 0 );
  212. my $buffer = '';
  213. $stream->recv_all( sub { my ( undef, $chunk ) = @_; $buffer .= $chunk; return length($chunk) } );
  214. $stream->finish();
  215. $buffer;
  216. };
  217. if ( !$data ) {
  218. my $err = "$@";
  219. $err =~ s/\n.*//s;
  220. return ( undef, $err );
  221. }
  222. File::Path::make_path($dir);
  223. open( my $fh, '>', $path ) or return ( undef, "could not cache the screenshot: $!" );
  224. binmode $fh;
  225. print {$fh} $data;
  226. close $fh;
  227. return ( $path, undef );
  228. }
  229. =head2 act($action, $conn_uri, $domain_name, $user) = ($ok, $message)
  230. The operations which change a guest.
  231. Deliberately the only sub here that does, and deliberately not reachable from
  232. the render path -- see the safety note at the top. Everything it does is
  233. logged with the user who asked for it.
  234. =cut
  235. sub act ( $action, $conn_uri, $domain_name, $user ) {
  236. my ($safe) = $domain_name =~ m/^([A-Za-z0-9._-]+)$/;
  237. return ( 0, 'bad guest name' ) unless $safe;
  238. # The template draws neither of these buttons for this guest; this is what
  239. # actually stops it happening. /guest/act is a POST anybody holding the
  240. # admin acl can craft by hand, and if it went through there would be
  241. # nothing left running to report the mistake.
  242. if ( _is_self($safe) && ( $action // '' ) =~ m/^(?:poweroff|destroy)$/ ) {
  243. WARN("Refused guest action '$action' on '$safe': that is this server");
  244. return ( 0, "'$safe' is this server -- refusing to $action it" );
  245. }
  246. my ( $conn, $why ) = _connect($conn_uri);
  247. return ( 0, "could not reach the hypervisor: $why" ) unless $conn;
  248. local $@;
  249. my ($domain) = eval {
  250. grep { $_->get_name() eq $safe } $conn->list_all_domains();
  251. };
  252. return ( 0, "no guest called '$safe' on that hypervisor" ) unless $domain;
  253. INFO("Guest action '$action' on '$safe' requested by $user");
  254. my %actions = (
  255. poweron => sub { $_[0]->create() },
  256. poweroff => sub { $_[0]->shutdown() },
  257. snapshot => sub { $_[0]->create_snapshot() },
  258. destroy => sub { $_[0]->destroy() },
  259. );
  260. my $doit = $actions{ $action // '' };
  261. return ( 0, "'$action' is not something we do to a guest" ) unless $doit;
  262. eval { $doit->($domain); 1 } or do {
  263. my $err = "$@";
  264. $err =~ s/\n.*//s;
  265. WARN("Guest action '$action' on '$safe' failed: $err");
  266. return ( 0, $err );
  267. };
  268. return ( 1, "$action: ok" );
  269. }
  270. 1;