#!/usr/bin/env perl # Main qemu-web-desktop service script. # # You must edit the /etc/qemu-web-desktop/config.pl file or config.d/*.pl to configure the service. # Think about editing the /usr/share/qemu-web-desktop/html/desktop/index.html # to comment/un-comment sections (GPU, oneshot). # # When relevant, the equivalent OpenStack naming is indicated (as documented # in https://docs.openstack.org/nova/latest/configuration/config.html) # # This script is triggered by a FORM or runs as a script. # to test this script, launch from the project root level something like: # # cd remote-desktop # perl cgi-bin/qemu-web-desktop.pl --dir_service=html/desktop \ # --dir_html=html --dir_snapshots=/tmp \ # --dir_machines=html/desktop/machines/ --oneshot=1 # # Then follow printed instructions in the terminal: # open a browser at something like: # - http://localhost:38443/vnc.html?host=localhost&port=38443 # # The script is effectively used in two steps (when executed as a CGI): # - The HTML FORM launches the script as a CGI which starts the session. # QEMU and VNC are initiated, the message is displayed, but does not wait for # the end of the session. # # A running session with an attached JSON file can be stopped with: # # perl qemu-web-desktop.pl --session_stop=/path/to/json # # To stop and clear all running sessions use: # # perl qemu-web-desktop.pl --dir_snapshots=/tmp --service_purge=1 # # To monitor all running sessions, use: # # perl cgi-bin/qemu-web-desktop.pl --service_monitor=1 # # # Requirements # ============ # sudo apt install apache2 libapache2-mod-perl2 # sudo apt install qemu-system bridge-utils qemu iptables dnsmasq libguestfs-tools # sudo apt install novnc websockify # # sudo apt install libsys-cpu-perl libsys-cpuload-perl libsys-meminfo-perl \ # libcgi-pm-perl liblist-moreutils-perl libnet-dns-perl libjson-perl \ # libproc-background-perl libproc-processtable-perl libemail-valid-perl \ # libnet-smtps-perl libmail-imapclient-perl libnet-ldap-perl libemail-valid-perl \ # libwww-perl liburi-perl libnet-ssh2-perl libtext-qrcode-perl # # (c) 2020- Emmanuel Farhi - GRADES - Synchrotron Soleil. AGPL3. # https://gitlab.com/soleil-data-treatment/soleil-software-projects/qemu-web-desktop # See 'support subroutines' below for in-line functions. # ensure all fatals go to browser during debugging and set-up # comment this BEGIN block out on production code for security # BEGIN { # $|=1; # use CGI::Carp('fatalsToBrowser'); # } # dependencies ----------------------------------------------------------------- use strict; use warnings qw( all ); use CGI; # use CGI.pm use Cwd 'abs_path'; # for abs_path use Date::Parse; # to convert date/time use File::Temp qw/ tempdir tempfile /; use File::Path qw/ rmtree /; use File::Basename qw/ fileparse dirname /; use File::Copy qw/ copy/; use File::Spec; use List::MoreUtils qw(uniq); # liblist-moreutils-perl use List::Util; use IO::Socket::INET; use IO::Socket::IP; use JSON; # libjson-perl for JSON use Proc::Background; # libproc-background-perl for Background->new use Proc::ProcessTable; # libproc-processtable-perl use Proc::Killfam; # libproc-processtable-perl for killfam (kill pid and children) use Sys::MemInfo; use Email::Valid; # libemail-valid-perl use Mail::IMAPClient; # libmail-imapclient-perl for imap user check use LWP::UserAgent; # libwww-perl for new and get(URL) use Net::Ping; # perl to test server up-down use Net::LDAP; # libnet-ldap-perl for ldap user check use Net::SSH2; # libnet-ssh2-perl for local user check use URI; # liburi-perl to split URL into parts # Sys::CpuLoad libsys-cpuload-perl for CpuLoad::load # Sys::CPU libsys-cpu-perl for CPU::cpu_count # System::CPU for System::CPU::get_ncpu() # Net::SMTPS; libnet-smtps-perl for smtp user check and emailing # NOTE: we trap import errors (when not present) BEGIN { eval { require Net::SMTPS; }; Net::SMTPS->import; } BEGIN { eval { require Sys::CpuLoad; }; Sys::CpuLoad->import; } BEGIN { eval { require Sys::CPU; }; Sys::CPU->import; } BEGIN { eval { require System::CPU; }; System::CPU->import; } # see http://honglus.blogspot.com/2010/08/resolving-perl-cgi-buffering-issue.html $| = 1; CGI->nph(1); # use https://perl.apache.org/docs/2.0/api/Apache2/RequestIO.html # for flush with CGI my $r = shift; if (not $r or not $r->can("rflush")) { push @ARGV, $r; # put back into ARGV when not a RequestIO object } use constant IS_MOD_PERL => exists $ENV{'MOD_PERL'}; use constant IS_CGI => IS_MOD_PERL || exists $ENV{'GATEWAY_INTERFACE'} || exists $ENV{'REQUEST_METHOD'}; # ------------------------------------------------------------------------------ # service configuration: tune for your needs # ------------------------------------------------------------------------------ # NOTE: This is where you can tune the default service configuration. # Adapt the path, and default VM specifications. # we use a Hash to store the configuration. This is simpler to pass to functions. our %config; $config{version} = "26.07.23"; # year.month.day my $dirname = abs_path(dirname(__FILE__)); # Locations for configuration files my @config_locations = ( "$dirname/../etc/config.pl", "$dirname/../etc/config.d/*.pl", '/etc/qemu-web-desktop/config.pl', '/etc/qemu-web-desktop/config.d/*.pl', '/opt/homebrew/etc/qemu-web-desktop/config.pl', '/opt/homebrew/etc/qemu-web-desktop/config.d/*.pl', ); my $config_found = 0; # Search configuration file foreach my $location (@config_locations) { # Unique file if (-e $location) { require $location; $config_found = 1; } else { # Files in config.d my @files = glob ($location); foreach my $file (@files) { if (-e $file) { require $file; $config_found = 1; } } } } unless ($config_found) { die "$0: Can not find config.pl or any .pl file in config.d (e.g. /etc/qemu-web-desktop/config.pl or $dirname/../config.pl)"; } # search detached GPU (via vfio-pci). Only use video part, no audio. # WARNING: Not supported on MacOS if ($^O ne 'darwin') { # can be a VGA adaptor or a 'controller' my ($device_pci1, $device_model1, $device_name1) = pci_devices("lspci -nnk","vga","vfio"); my ($device_pci2, $device_model2, $device_name2) = pci_devices("lspci -nnk","3d controller","vfio"); my @gpu_pci = (@$device_pci1, @$device_pci2); my @gpu_model= (@$device_model1, @$device_model2); my @gpu_name = (@$device_name1, @$device_name2); $config{gpu_model} = \@gpu_model; $config{gpu_name} = \@gpu_name; $config{gpu_pci} = \@gpu_pci; } # ------------------------------------------------------------------------------ # update config with input arguments from the command line (when run as script) # ------------------------------------------------------------------------------ # the 'service_monitor' can be set to true to generate a list of running sessions. # each of these can display its configuration, and be stopped/cleaned. $config{service_monitor} = 0; $config{session_stop} = ""; # contains a json ref, stop service $config{service_purge} = 0; # when true stop/clean all $config{oneshot} = 0; for(my $i = 0; $i < @ARGV; $i++) { $_ = $ARGV[$i]; if(! $_) { next; } if(/--help|-h$/) { print STDERR "$0: launch a QEMU/KVM machine in a browser window. Version $config{version}\n\n"; print STDERR "Usage: $0 --option1=value1 ...\n\n"; print STDERR "Valid options are:\n"; foreach my $key (sort keys %config) { print STDERR " --$key=VALUE [$config{$key}]\n"; } print STDERR "\nTo manually start virtual machine in DIR_VM/VM :\n"; print STDERR "$0 --dir_machines=DIR_VM --machine=VM --dir_snapshots=/tmp --dir_cfg=/tmp --oneshot=1 --service_max_mem_fraction_nb_per_user=0.8 --service_max_cpu_fraction_nb_per_user=0.8 --snapshot_alloc_disk=30\n"; print STDERR "or use: 'qwdctl start VM'.\n"; exit; } elsif (/--version|-v$/) { print STDERR "$0 $config{version}\n\n"; print STDERR "Copyright (C) 2020- Synchrotron Soleil, AGPL3.\n"; print STDERR "This is free software; see the source for copying conditions. There is NO\n"; print STDERR "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"; print STDERR "Written by Emmanuel Farhi \n"; exit; } elsif (/^--(\w+)=(\w+)$/) { # e.g. '--opt=value' if (exists($config{$1})) { $config{$1} = $2; } } elsif (/^--(\w+)=([a-zA-Z0-9_\ \"\.\-\:\~\\\/]+)$/) { # e.g. '--opt=file' if (exists($config{$1})) { $config{$1} = $2; } } } $config{session_nb} = 0; if ($config{session_stop}) { # from ARGS (command line) # wait for session to end, and clean files/PIDs. my $session_ref = session_load(\%config, $config{session_stop}); if ($session_ref) { session_stop($session_ref); } exit; } # for I/O, to generate HTML display and email content. my $error = ""; my $output = ""; my $output_email= ""; # message sent via email when MFA and check via email # Check running snapshots and clean any left over. { (my $err, my $nb) = service_housekeeping(\%config); # see below for private subroutines. $error .= $err; $config{session_nb} = $nb; }; if ($config{certificate_crt} and -e $config{certificate_crt} and $config{certificate_key} and -e $config{certificate_key}) { $config{http} = "https"; # secured connection with certificates } else { $config{http} = "http"; } # ------------------------------------------------------------------------------ # Session variables: into a hash as well. # ------------------------------------------------------------------------------ my %session; # transfer defaults $session{machine} = $config{machine}; # OpenStack DEFAULT.instance_name_template ? $session{dir_snapshot}= tempdir(TEMPLATE => "$config{service}" . "_XXXXXXXX", DIR => $config{dir_snapshots}) || die "$0: Can not create snapshot directory in $config{dir_snapshots}."; $session{name} = File::Basename::fileparse($session{dir_snapshot}); $session{snapshot} = safe_path($session{dir_snapshot}, $config{service} . ".qcow2"); $session{json} = safe_path($config{dir_cfg}, $session{name} . ".json"); $session{output} = safe_path($session{dir_snapshot}, "index.html"); $session{qrcode} = ""; $session{user} = ""; $session{password} = ""; $session{persistent} = ""; # not persistent implies lower server load $session{cpu} = int($config{snapshot_alloc_cpu}); # default: cores $session{memory} = int($config{snapshot_alloc_mem}); # default: in GB $session{disk} = int($config{snapshot_alloc_disk}); # default: only for ISO $session{gpu} = ""; # indicates PCI GPU passthrough request when not empty $session{snapshot_lifetime} = int($config{snapshot_lifetime}); # default [sec] $session{oneshot} = $config{oneshot}; $session{user_email} = ""; $session{date} = localtime(); # see https://www.oreilly.com/library/view/perl-cookbook/1565922433/ch11s03.html#:~:text=To%20append%20a%20new%20value,values%20for%20the%20same%20key. # on how to handle arrays in a hash. # push new PID: push @{ $session{pid} }, 1234; # get PIDs: my @pid = @{ $session{pid} }; $session{pid} = (); # we search all children in session_stop # push @{ $session{pid} }, $$; # do NOT add our own PID = common Perl for all cgi's $session{pid_wait} = $$; # PID to wait for (daemon). $session{port} = $config{service_port}; # e.g. 6080 for websockify $session{qemuvnc_ip} = "127.0.0.1"; # OpenStack vnc.server_listen vnc.proxyclient_address # cast a random token key for VNC: 8 random chars in [a-z A-Z digits] sub rndStr{ join'', @_[ map{ rand @_ } 1 .. shift ] }; $session{token_vnc} = rndStr (20, 'a'..'z', 'A'..'Z', 0..9); $session{password_vnc}= rndStr (20, 'a'..'z', 'A'..'Z', 0..9); $session{token_file} = ""; $session{runs_as_cgi} = IS_CGI; $session{url} = ""; # auto: default QEMU executable if ($config{qemu_exec} =~ /^(auto|host)$/) { my $arch=`uname -m`; if ($arch =~ 'x86_64') { $config{qemu_exec} = 'qemu-system-x86_64'; } elsif ($arch =~ /(aarch64|arm64)/) { $config{qemu_exec} = 'qemu-system-aarch64'; } else { die "$0: Can not determine qemu-system for architecture $arch. Set config{qemu_exec} in config.pl\n"; } } # auto: best QEMU options from host capabilities if (not $error and $config{qemu_exec_options} =~ 'auto') { $config{qemu_exec_options} =~ s/auto//; my $accel=`$config{qemu_exec} -accel help`; my $mach=`$config{qemu_exec} -M help`; # test type of accelerator # usual case on Intel/AMD and Apple/Silicon if ($accel =~ "kvm") { $config{qemu_exec_options} .= " -enable-kvm -cpu host"; if ($mach =~ "Standard PC") { $config{qemu_exec_options} .= ",kvm=off"; } } elsif ($accel =~ "hvf") { $config{qemu_exec_options} .= " -accel hvf -cpu host"; } # test type of target machine if ($mach =~ "Standard PC") { # usual case on Intel/AMD "PC" $config{qemu_exec_options} .= " -M pc"; # test type of VGA (not on ARM) my $mach_vga= `$config{qemu_exec} -M pc -vga help`; if ($mach_vga =~ "virtio") { $config{qemu_exec_options} .= " -vga virtio"; } elsif ($mach_vga =~ "qxl") { $config{qemu_exec_options} .= " -vga qxl"; } else { $config{qemu_exec_options} .= " -device ramfb"; } } elsif ($mach =~ "virt") { # Other, e.g. ARM $config{qemu_exec_options} .= " -M virt,iommu=smmuv3"; $config{qemu_exec_options} .= " -device ramfb"; } # the device virtio-gpu is nice, but brings mouse pointer offset # if (`$config{qemu_exec} -device help` =~ "virtio-gpu") { # $config{qemu_exec_options} .= " -device virtio-gpu"; # } # special case for ARM: require EFI boot if (`uname -m` =~ /(aarch64|arm64)/) { # search for EFI/ARM my @EFIs=('/usr/share/qemu-efi-aarch64/QEMU_EFI.fd', '/usr/share/qemu-efi/QEMU_EFI.fd', '/usr/share/ovmf/AARCH64/QEMU_EFI.fd', '/usr/share/edk2/arm/QEMU_EFI.fd', '/opt/homebrew/share/qemu/edk2-aarch64-code.fd'); foreach my $EFI (@EFIs) { if (-f $EFI) { # Debian arm # https://documentation.ubuntu.com/server/how-to/virtualisation/qemu/index.html # https://wiki.debian.org/Arm64Qemu recommends to use the '-bios $EFI' # Special case for Apple/Silicon # https://ww2.coastal.edu/mmurphy2/oer/qemu/aarch64/ $config{qemu_exec_options} .= " -bios $EFI"; last; } } } } # end auto qemu options # ------------------------------------------------------------------------------ # Update session info from CGI # ------------------------------------------------------------------------------ $CGI::POST_MAX = 65535; # max size of POST message my $q = new CGI; # create new CGI object "query" if (my $res = $q->cgi_error()){ if ($res =~ /^413\b/o) { $error .= "Maximum data limit exceeded. \n"; } else { $error .= "An unknown error has occured. \n"; } } $session{remote_host} = safe_path("",$q->remote_host()); # the 'client' if ($session{remote_host} =~ "::1") { $session{remote_host} = "localhost"; } $session{server_name} = safe_path("",$q->server_name()); # the 'server' OpenStack DEFAULT.host if ($session{server_name} =~ "::1") { $session{server_name} = "localhost"; } $config{server_name} = $session{server_name}; # check input arguments values (not 'password') for ('machine','user','cpu','memory','gpu','snapshot_lifetime', 'session_stop','service_purge','session_extend','oneshot','fallback_servers') { my $val = $q->param($_); if (defined($val)) { if ( $val =~ /^([a-zA-Z0-9_.\-@\: ]+)$/ ) { # all is fine $session{$_} = $val; } else { $error .= "$_ is not defined or contains invalid characters. \n"; } } } # these are the "input" to collect from the HTML FORM. Store in $session for ('password') { my $val = $q->param($_); if (defined($val)) { $session{$_} = $val; } } # we get the list of fallback servers to be used when current machine is over-subscribed. # The POST message will be updated with a reduced fallback_servers list # and sent via LWP::UserAgent -> post if (not defined $session{fallback_servers} and defined $config{fallback_servers}) { $session{fallback_servers} = $config{fallback_servers}; } my $need_fallback_server = 0; # check if the 'Manage button' was hit, instead of Create if (defined $q->param('manage')) { $session{machine} = 'monitor'; } if (not $session{runs_as_cgi}) { # not a CGI: running as detached script print STDERR $0.": WARNING: Running as detached script. No token. NO AUTHENTICATION.\n"; $config{check_user_with_email} = 0; $config{check_user_with_ldap} = 0; $config{check_user_with_imap} = 0; $config{check_user_with_smtp} = 0; $session{password_vnc} = ""; } # assemble welcome message ----------------------------------------------------- # # NOTE on HTML generation: from here on, $output only accumulates BODY content # (status list, tables, messages). The full HTML document (doctype, , # shared
$body_html
END_HTML return $html; } # html_page_wrap # session_save(\%session): save session hash into a JSON. sub session_save { my $session_ref = shift; if (not $session_ref) { return; } my %session = %{ $session_ref }; # Remove sensitive data before saving my %safe_session = %session; delete $safe_session{password}; delete $safe_session{token_vnc}; # Set restrictive permissions umask(0077); open my $fh, ">", $session{json} or die "$0: Cannot write $session{json}: $!"; print $fh JSON::encode_json(\%safe_session); close $fh; chmod(0600, $session{json}); # Owner read/write only } # session_save # $session = session_load(\%config, $file): load session hash from JSON. # return $session reference sub session_load { my $config_ref = shift; my $file = shift; if (not $config_ref or not $file) { return undef; } my %config = %{ $config_ref }; # we test if the given ref is partial (just session name) if (not -e $file) { if (-e "$config{dir_cfg}/$file" or -e "$config{dir_cfg}/$file.json") { $file = "$config{dir_cfg}/$file"; } if (-e "$file.json") { $file = "$file.json"; } } if (not -e $file) { return undef; } open my $fh, "<", $file or return undef; # "$0: Cannot read $file: $!"; my $json = <$fh>; close $fh; my $session = decode_json($json); return $session; } # session_load # session_stop(\%session): stop given session, and remove files. sub session_stop { my $session_ref = shift; if (not $session_ref) { return; } my %session = %{ $session_ref }; # remove directory and JSON config if ($session{dir_snapshot} and -e $session{dir_snapshot}) { rmtree($session{dir_snapshot}); } if ($session{json} and -e $session{json}) { unlink($session{json}); } if ($session{output} and -e $session{output}) { unlink($session{output}); } if ($session{token_file} and -e $session{token_file}) { unlink($session{token_file}); } if ($session{qrcode} and -e $session{qrcode}) { unlink($session{qrcode}); } my $now = localtime(); if ($session{remote_host}) { print STDERR $0." [$now] STOP $session{name} $session{machine} started on [$session{date}] for $session{user}\@$session{remote_host} $session{user_email}\n"; } # make sure QEMU/noVNC and asssigned SHELLs are killed # sometimes, PID's can change (more forks e.g. by websocket) if ($session{pid}) { my @pids = reverse uniq sort @{ $session{pid} }; print STDERR $0." [$now] Kill @pids\n"; map { my @all = flatten(proc_getchildren($_)); # get all children from that PID killfam('KILL', reverse uniq sort @all); # by reverse creation date/PID } reverse uniq sort @pids; } if ($config{service_logfile}) { if (open my $fh, ">>", $config{service_logfile}) { print $fh "[$now] STOP CPU=$session{cpu} MEM=$session{memory} GPU=$session{gpu} USER=$session{user} VM=$session{machine} NAME=$session{name}\n"; close $fh; } } } # session_stop # $session = session_extend(\%session, $extension): sextend session life-time sub session_extend { my $session_ref = shift; my $time_extension = shift; if (not $session_ref) { return; } my %session = %{ $session_ref }; # extend snapshot_lifetime when it does not exceed $config{snapshot_lifetime} if ($session{snapshot_lifetime} and ($session{snapshot_lifetime} < $config{snapshot_lifetime}) ) { print STDERR $0." [$session{date}] Extend session $session{name} by $time_extension s.\n"; $session{snapshot_lifetime} = $session{snapshot_lifetime} + $time_extension; # save new config session_save(\%session); } } # session_extend # (TF, $content) = session_test_script(\%session, content) # Test the script '$content' after replacing symbols # The test expression must be found with syntax 'if(exp):'. It is extracted, # removed from the $content (which is returned after removal). Then it is # evaluated, and its result is placed in TF (returned). False is returned # when the test can not be evaluated (fails). # return (TF, $content) sub session_test_script { my $session_ref = shift; my $content = shift; my $TF = 0; if (not $session_ref) { return (0,$content); } if (not $content) { return (0,$content); } my %session = %{ $session_ref }; # replace @symbols@ (globally) $content=~s/\@USER\@/$session{user}/g; $content=~s/\@SESSION_NAME\@/$session{name}/g; $content=~s/\@VM\@/$session{machine}/g; $content=~s/\@PW\@/$session{password}/g; # trim $content =~ s/^\s+|\s+$//g ; # now search for the expression "if(EXPR):". Get 1st match. if ($content =~ m/if\((.*)\):/) { my $test = $1; $content =~ s/if\((.*)\)://; # remove match $content =~ s/^\s+|\s+$//g ; # trim again # evaluate the EXPR in test. $TF = eval $test; if ($@) { $TF = 0; } # error -> fails return ($TF,$content); } else { # no match: use content as is. return (1, $content); } } # session_test_script # session_run_script(\%config, \%session, $script): install a script for boot in VM # The script can be specifyed as: # "http://some/url" # "/some/local/path/to/script" # "exec: some commands" separated by EOL (\n) or ';' # "virt-customize: commands" separated by EOL (\n) # "qemu: QEMU options" separated by spaces # # In addition, the script text (expression, file or URL) may contain the syntax: # if(EXPR): # so that the script content is evaluated when EXPR is true. # The script content and EXPR may use the @USER@ @PW@ @SESSION_NAME@ and @VM@ symbols, # which are replaced by the user name, the session name and the VM name. # # The returned value is ($virt_customize_cmd, $qemu_cmd) sub session_run_script { my $config_ref = shift; my $session_ref = shift; my $script = shift; my $virt_customize_cmd = ""; my $qemu_cmd = ""; if (not $session_ref) { return ("",""); } if (not $config_ref) { return ("",""); } my %config = %{ $config_ref }; my %session = %{ $session_ref }; if (length($script) > $config{service_max_script_length} || not $script) { return ("",""); } my $TF=0; ($TF,$script) = session_test_script(\%session, $script); # handle any 'if(EXPR)' statement if (not $TF) { return ("",""); } my $content = undef; my $virt_customize_commands = 0; # add 'file://' for local file if (rindex($script, "bash:", 0) == 0 or rindex($script, "exec:", 0) == 0) { $content = substr($script, 5); } elsif (rindex($script, "virt-customize:", 0) == 0) { $content = substr($script, 15); $virt_customize_commands = 1; } elsif (-e "$script") { $script = "file://".$script; } elsif (rindex($script, "qemu:", 0) == 0) { return ("", $script); } # get script from $script URL # we try a few times to get the content. A single attempt is often not enough. if (not defined ($content) or not $content) { for (1..5) { my $ua = LWP::UserAgent->new(timeout => 2); # use a specific proxy, or system configuration (e.g. HTTP_PROXY env var) if ($config{service_proxy}) { $ua->proxy(['http', 'ftp', 'https'], $config{service_proxy}); } else { $ua->env_proxy; } my $response = $ua->get($script); if (not $response->is_error) { $content = $response->content; last; } } } if (defined ($content) and length($content)) { # remove invalid characters $content=~s/[^\x00-\x7f]//g; if (length($content) < $config{service_max_script_length}) { # replace symbols. Script is known to be active from previous call to session_test_script ($TF, $content) = session_test_script(\%session, $content); # store script in our 'snapshot' directory for local exec. my ($script_handle, $script_name) = tempfile(TEMPLATE => "$session{dir_snapshot}/configuration_script_XXXXXXXX"); if (not $script_name) { return ("",""); } print $script_handle "$content\n"; close $script_handle; # output script into apache2/log print STDERR $0.": $session{name}: $session{date}: $session{user} uses config_script=$script -> $script_name\n"; # print STDERR "$content\n"; # call virt-customize: start VM, execute script, stop it. Only runs on stopped VMs. # virt-customize -a vm.qcow2 --run snapshot/script # my $cmd = "virt-customize -a $session{snapshot} "; my $cmd= ""; if ($virt_customize_commands == 0) { $cmd = " --firstboot $script_name"; } else { $cmd = " --commands-from-file $script_name"; } return ($cmd, ""); } } } # session_run_script # service_housekeeping(\%config): scan 'snapshot' and 'cfg' directories. # - kill over-time sessions # - check that 'snapshots' have a 'cfg'. # - remove orphan 'snapshots' (may be left from a hard reboot). # return ($error,$nb) string (or empty when all is OK) and number of sessions. sub service_housekeeping { my $config_ref = shift; if (not $config_ref) { return; } my %config = %{ $config_ref }; my $dir = $config{dir_snapshots}; my $cfg = $config{dir_cfg}; my $service = $config{service}; # clean: # - remove orphan snapshots (no corresponding JSON file) # - remove orphan JSON (no corresponding snapshots) # - remove snapshots that have gone above their lifetime my $now = localtime(); foreach my $snapshot (glob("$dir/$service"."_*")) { if (-d $snapshot && time - (stat($snapshot))[9] > 10*$config{boot_delay}) { # is a snapshot directory my $snaphot_name = fileparse($snapshot); # just the session name if (not -e "$cfg/$snaphot_name.json") { # remove orphan $snapshot (no JSON) print STDERR $0." [$now] housekeeping: $snapshot (left-over, no JSON - internal command)\n"; rmtree( $snapshot ) || print STDERR $0." [$now] Failed removing $snapshot\n"; } else { my $session_ref = session_load(\%config, "$cfg/$snaphot_name.json"); if ($session_ref) { my %session = %{ $session_ref }; if ($session{snapshot_lifetime} and (time > (stat $snapshot)[9] + $session{snapshot_lifetime}) or (time > (stat $snapshot)[9] + $config{snapshot_lifetime}) ) { # json exists, lifetime exceeded print STDERR $0." [$now] housekeeping: $cfg/$snaphot_name.json (exceeded life-time)\n"; session_stop($session_ref); } } else { rmtree( $snapshot ) || print STDERR $0." [$now] Failed removing $snapshot\n"; } } } } # for snapshot # scan JSON files foreach my $json (glob("$cfg/*.json")) { # session exists, load JSON my $session_ref = session_load(\%config, $json); if ($session_ref && time - (stat($json))[9] > 10*$config{boot_delay}) { my %session = %{ $session_ref }; if (not -d $session{dir_snapshot}) { print STDERR $0." [$now] housekeeping: $json (left-over, no snapshot)\n"; unlink($json); } # snapshot does not exist } } # now count how many active sessions we have. my @jsons = glob("$cfg/$service"."_*.json"); my $nb = scalar(@jsons); my $err = ""; $config{session_nb} = $nb; $err = ""; return ($err,$nb); } # service_housekeeping # service_monitor(\%config, $out, $isadmin, $user): present a list of running sessions # as well as the server usage and history. # $out is expected to arrive with an OPEN '\n"; # display a table with current info $out .= "
"; $out .= "

Current $config{service} status ($now)

"; $out .= ""; $out .= "\n"; $out .= "\n"; $out .= "\n"; $out .= "\n"; $out .= "\n"; $out .= "\n"; $out .= "\n"; $out .= "\n"; $out .= "
Server $config{server_name} running '$config{service}' version $config{version}
#CPU total $cpu_count
#CPU used $cpu_load
Load [0-1] $load
Total memory (GB)$total_memory_GB
Available memory (GB) $avail_memory_GB
Active sessions $config{session_nb} (total)
\n"; $out .= "
\n"; # display a list of active sessions for the given user my $dir = $config{dir_snapshots}; my $cfg = $config{dir_cfg}; my $service = $config{service}; # iter=1: normal user; 2: admin user for my $iter (1..2) { # {name} {machine} {user} {date} {cpu} {mem} {lifetime} {url} {PIDs} if ($iter == 1) { $out .= "

Active sessions for $user

\n"; $out .= ""; $out .= ""; $out .= "\n"; } elsif ($iter == 2 and $isadmin) { $out .= "

Active sessions [$config{session_nb}] (administration)

Start DateNameMachineUserlife-time (h)URLProcessCPUMemory (MB)GPU
\n"; $out .= ""; $out .= ""; $out .= "\n"; } foreach my $snapshot (glob("$dir/$service"."_*")) { if (-d $snapshot) { # is a snapshot directory my $snaphot_name = fileparse($snapshot); # just the session name if (-e "$cfg/$snaphot_name.json") { my $session_ref = session_load(\%config, "$cfg/$snaphot_name.json"); if ($session_ref) { my %session = %{ $session_ref }; my $flag=0; if ($iter == 1 and $user eq $session{user}) { $flag = 1; } elsif ($iter == 2 and $isadmin) { $flag = 1; } if ($session{pid} and $flag) { my @pids = @{ $session{pid} }; $out .= ""; $out .= ""; if ($iter == 2) { # admin only. Appear as a collapsible text $out .= ""; } $out .= ""; if ($session{user_email}) { $out .= ""; } else { $out .= ""; } my $lt = $session{snapshot_lifetime}/3600; my $end_date = localtime(str2time($session{date}) + $session{snapshot_lifetime}); $out .= "\n"; if ($session{oneshot}) { $out .= ""; # create a STOP button for each $out .= "\n"; $out .= ""; $out .= ""; if ($session{gpu}) { $out .= ""; } else { $out .= ""; } } } } } } # foreach snapshot $out .= "
Start DateNameMachineUserlife-time (h)URLProcessCPUMemory (MB)GPU
$session{date}
$session{name}

"; my %hash = %session; $hash{password}="XXXX"; # hide user pw $out .= "$_=$hash{$_}; " for (keys %hash); $out .= "

"; } else { $out .= "
$session{name}$session{machine}$session{user}$session{user}$lt [$end_date] "; my $extend_by = 24; # hours if ($session{snapshot_lifetime} + 3600*$extend_by < $config{snapshot_lifetime}) { $out .= "
"; } $out .= "
one-shot"; } else { $out .= "▶ Connect"; if ($session{password_vnc} && ($config{service_port_multiple} or ($config{check_user_mfa} and $iter == 2))) { $out .= " $session{password_vnc}"; } } $out .= "
$session{cpu}$session{memory}$session{gpu}
"; # display full list of sessions (when user is marked as 'admin') if (not $isadmin) { return $out; } } # for 1..2 return $out; } # service_monitor # service_purge(\%config): kill all running sessions sub service_purge { my $config_ref = shift; if (not $config_ref) { return; } my %config = %{ $config_ref }; my $dir = $config{dir_snapshots}; my $cfg = $config{dir_cfg}; my $service = $config{service}; foreach my $snapshot (glob("$dir/$service"."_*")) { if (-d $snapshot) { # is a snapshot directory my $snaphot_name = fileparse($snapshot); # just the session name if (-e "$cfg/$snaphot_name.json") { my $session_ref = session_load(\%config, "$cfg/$snaphot_name.json"); session_stop($session_ref); } } } # for } # service_purge # session_email(\%config, \%session, $output): send an email with URL # $output is expected to already be a complete HTML document (see # html_page_wrap) since it is used verbatim as the email body. # return: "" or error message sub session_email { my $config_ref = shift; my $session_ref = shift; my $out = shift; if (not $config_ref or not $session_ref or not $out) { return "Invalid session/config"; } my %config = %{ $config_ref }; my %session = %{ $session_ref }; if (not $session{user} or not $config{smtp_server}) { return "Invalid user or SMTP server"; } # auto use the provided smtp/email settings to decide what to do # SSL use the server, port SSL, and email_from with email_passwd # simple just use the server, and port 25 # port just use the server with given port my $smtp; my $method = $config{email_method}; if ($method =~ 'auto') { if ( not $config{smtp_port} and not $config{smtp_use_ssl}) { $method = 'simple'; } elsif ($config{smtp_port} and $config{smtp_use_ssl} and $config{email_passwd}) { $method = 'SSL'; } else { $method = 'port'; } } if ($method =~ 'SSL' and $config{smtp_port} and $config{smtp_use_ssl} and $config{email_passwd}) { eval { $smtp = Net::SMTPS->new($config{smtp_server}, Port => $config{smtp_port}, doSSL => $config{smtp_use_ssl}, SSL_version=>'TLSv1'); }; $method .= " $@" if $@; # add error from SMTP if any } elsif ($method =~ 'port' and $config{smtp_port}) { $smtp = Net::SMTP->new($config{smtp_server}, Port=>$config{smtp_port}, Timeout => 10); } else { $smtp = Net::SMTP->new($config{smtp_server}, Timeout => 10); # e.g. port 25 } if ($smtp) { if ($config{email_passwd}) { $smtp->auth($config{email_from},$config{email_passwd}) || return "Failed SMTP authentication for $config{email_from}"; } $smtp->mail($config{email_from}); $smtp->recipient($session{user_email}); $smtp->data(); $smtp->datasend("From: $config{email_from}\n"); $smtp->datasend("To: $session{user_email}\n"); # could add BCC to internal monitoring address $smtp->datasend("BCC: address\@example.com\n"); $smtp->datasend("Subject: [$config{service}] Remote $session{name} connection information $session{password_vnc}\n"); $smtp->datasend("Content-Type: text/html; charset=\"UTF-8\" \n"); $smtp->datasend("\n"); # end of header $smtp->datasend($out); $smtp->dataend; $smtp->quit; return ""; # sent } else { return "Invalid SMTP connection: $method"; } } # session_email # session_message(\%config, \%session, # $output_icon, $output_share, $output_token, $output_persistent); # assemble a "Hello user" card to display/send. # Returns BODY content only (no /