Virt.pm 13 KB

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