GIF89a=( õ' 7IAXKgNgYvYx\%wh…hŽth%ˆs%—x¨}9®Œ©€&©‰%¶†(¹–.¹5·œD¹&Çš)ÇŸ5ǘ;Í£*È¡&Õ²)ׯ7×µ<Ñ»4ï°3ø‘HÖ§KͯT÷¨Yÿšqÿ»qÿÔFØ !ù ' !ÿ NETSCAPE2.0 , =( þÀ“pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§gª«ªE¯°¨¬ª±²Œ¹º¹E¾­”´ÂB¶¯ §Åȸ»ÑD¾¿Á•ÄÅ®° ÝH¾ÒLÀÆDÙ«D¶BÝïðÀ¾DÑÑÔTÌÍíH òGö¨A RÎڐ |¥ ٭&ºìE8œ¹kGÔAÞpx­a¶­ã R2XB®åE8I€Õ6Xî:vT)äžþÀq¦è³¥ì仕F~%xñ  4#ZÔ‰O|-4Bs‘X:= QÉ œš lºÒyXJŠGȦ|s hÏíK–3l7·B|¥$'7Jީܪ‰‡àá”Dæn=Pƒ ¤Òëí‰`䌨ljóá¯Éüv>á–Á¼5 ½.69ûϸd«­ºÀûnlv©‹ªîf{¬ÜãPbŸ  l5‘ޝpß ´ ˜3aÅùäI«O’ý·‘áÞ‡˜¾Æ‚ÙÏiÇÿ‹Àƒ #öó)pâš Þ½ ‘Ý{ó)vmÞü%D~ 6f s}ŃƒDØW Eþ`‡þ À…L8xá†ç˜{)x`X/> Ì}mø‚–RØ‘*|`D=‚Ø_ ^ð5 !_…'aä“OÚ—7âcð`D”Cx`ÝÂ¥ä‹éY¹—F¼¤¥Š?¡Õ™ n@`} lď’ÄÉ@4>ñd œ à‘vÒxNÃ×™@žd=ˆgsžG±æ ´²æud &p8Qñ)ˆ«lXD©øÜéAžHìySun jª×k*D¤LH] †¦§C™Jä–´Xb~ʪwStŽ6K,°£qÁœ:9ت:¨þªl¨@¡`‚ûÚ ».Û¬¯t‹ÆSÉ[:°=Š‹„‘Nåû”Ìî{¿ÂA ‡Rà›ÀÙ6úë°Ÿð0Ä_ ½;ÃϱîÉì^ÇÛÇ#Ëë¼ôº!±Ä˜íUîÅÇ;0L1óÁµö«p% AÀºU̬ݵ¼á%霼€‡¯Á~`ÏG¯»À× ­²± =4ªnpð3¾¤³¯­ü¾¦îuÙuµÙ®|%2ÊIÿür¦#0·ÔJ``8È@S@5ê¢ ö×Þ^`8EÜ]ý.뜃Âç 7 ú ȉÞj œ½Dç zý¸iþœÑÙûÄë!ˆÞÀl§Ïw‹*DçI€nEX¯¬¼ &A¬Go¼QföõFç°¯;é¦÷îŽêJ°îúôF5¡ÌQ|îúöXªæ»TÁÏyñêï]ê² o óÎC=öõ›ÒÓPB@ D×½œä(>èCÂxŽ`±«Ÿ–JЀ»Û á¤±p+eE0`ëŽ`A Ú/NE€Ø†À9‚@¤à H½7”à‡%B‰`Àl*ƒó‘–‡8 2ñ%¸ —€:Ù1Á‰E¸àux%nP1ð!‘ðC)¾P81lÑɸF#ˆ€{´âé°ÈB„0>±û °b¡Š´±O‚3È–Ù()yRpbµ¨E.Z‘D8ÊH@% òŒx+%Ù˜Æcü »¸˜fõ¬b·d`Fê™8èXH"ÉÈ-±|1Ô6iI, 2““¬$+](A*jÐ QTÂo‰.ÛU슬Œã„Ž`¯SN¡–¶Äåyše¯ª’­¬‚´b¦Éož œ)åyâ@Ì®3 ÎtT̉°&Ø+žLÀf"Ø-|žçÔ>‡Ðv¦Ðžì\‚ Q1)Ž@Žh#aP72”ˆ™¨$‚ !ù " , =( …7IAXG]KgNgYvYxR"k\%w]'}hŽth%ˆg+ˆs%—r.—m3šx3˜x¨}9®€&©€+¨‡7§‰%¶†(¹–.¹œD¹&ǘ;Í•&ײ)×»4ïÌ6ò§KÍ þ@‘pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g «¬ E ±± ¨­¶°ººE Á´”·®C¬²§Ç¶Œ»ÓDÃÕƷ¯Ê±H½ºM×ÁGÚ¬D¶BËÁ½î½DÓôTÏÛßîG»ôõC×CÌ l&âž:'òtU³6ɹ#·Ø)€'Ü.6±&ëÍÈ» K(8p0N?!æ2"ÛˆNIJX>R¼ÐO‚M '¡¨2¸*Ÿþ>#n↠å@‚<[:¡Iïf’ ¤TÚ˘CdbÜÙ“[«ŽEú5MBo¤×@€`@„€Êt W-3 ¶Ÿ¡BíêäjIÝ…Eò9[T…$íêﯧ„…•s»Óȳ¹€ÅÚdc®UUρ#±Ùïldj?´í¼²`\ŽÁðÞu|3'ÖŒ]ë6 ¶S#²‡˜FKLÈ *N E´‘áäŠ$˜›eÄYD„ºq«.è촁ƒs \-ÔjA 9²õ÷å- üúM[Âx(ís÷ì®x€|í¡Ù’p¦‚ ŽkÛTÇDpE@WÜ ²Ç]kŠ1¨ þ€·Yb ÓÁ‰l°*n0 ç™—žzBdОu¾7ĉBl€â‰-ºx~|UåU‰  h*Hœ|e"#"?vpÄiŠe6^ˆ„+qâŠm8 #VÇá ‘å–ÄV„œ|Аè•m"сœn|@›U¶ÆÎž—Špb¥G¨ED”€±Úê2FÌIç? >Éxå Œ± ¡¤„%‘žjŸ‘ꄯ<Ìaà9ijÐ2˜D¦È&›†Z`‚å]wþ¼Â:ç6àB¤7eFJ|õÒ§Õ,¨äàFÇ®cS·Ê¶+B°,‘Þ˜ºNûãØ>PADÌHD¹æž«ÄÀnÌ¥}­#Ë’ë QÀÉSÌÂÇ2ÌXÀ{æk²lQÁ2«ÊðÀ¯w|2Í h‹ÄÂG€,m¾¶ë3ÐÙ6-´ÅE¬L°ÆIij*K½ÀÇqï`DwVÍQXœÚÔpeœ±¬Ñ q˜§Tœ½µƒ°Œìu Â<¶aØ*At¯lmEØ ü ôÛN[P1ÔÛ¦­±$ÜÆ@`ùåDpy¶yXvCAyåB`ŽD¶ 0QwG#¯ æš[^Äþ $ÀÓÝǦ{„L™[±úKÄgÌ;ï£S~¹ìGX.ôgoT.»åˆ°ùŸûù¡?1zö¦Ÿž:ÅgÁ|ìL¹ „®£œŠ‚à0œ]PÁ^p F<"•ç?!,ñ‡N4—…PÄ Á„ö¨Û:Tè@hÀ‹%táÿ:ø-žI<`þ‹p I….)^ 40D#p@ƒj4–؀:²‰1Øâr˜¼F2oW¼#Z†;$Q q” ‘ ÂK¦ñNl#29 !’F@¥Bh·ᏀL!—XFóLH‘Kh¤.«hE&JòG¨¥<™WN!€ÑÙÚˆY„@†>Œž19J" 2,/ &.GXB%ÌRÈ9B6¹W]’î×ÔW¥’IÎ$ ñ‹ÓŒE8YÆ ¼³™ñA5“à®Q.aŸB€&Ø©³ JÁ—! ¦t)K%tœ-¦JF bòNMxLôþ)ÐR¸Ð™‘ èÝ6‘O!THÌ„HÛ ‰ !ù ) , =( …AXKgNgYvYxR"k\%wh…hŽh%ˆg+ˆs%—r.—x3˜x¨}9®€&©€+¨Œ,©‡7§‰%¶†(¹–.¹5·&Çš)ǘ;Í•&×£*Ȳ)ׯ7×»4ï°3øÌ6ò‘HÖ§KÍ»Hó¯T÷¨Yÿ»qÿÇhÿ þÀ”pH,È¤rÉl:ŸÐ¨tJ­Z¯Ø¬vËíz¿à°xL.›Ïè´zÍn»ßð¸|N¯Ûïø¼~Ïïûÿ€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§g ª« E$±²¨ª­ · °²½$E$ÂÕ««D· Í ¿¦Ç¶¸ÌŒ¾³CÃÅÆ E ééH½MÛÂGâªD­ çBêêϾD²ÒaÀà€Š1r­ðÓ¤ ÔožzU!L˜C'¾yW½UGtäÇïÙllê0×àÂuGþ)AÀs[þ·xì ÁxO%ƒûX2ó—  P£n›R/¡ÑšHše+êDm?# —‘Ç£6¡8íJ¡ŸâDiäªM¥Ö„ôj“¬¹£5oQ7°- <‡ *´lãÓŒ2r/a!l)dÈ A™ÈE¢ôÔ͆…ð ;Ö˜c ¡%ß‚’Ùˆâ¸b½—pe~C"BíëÚHïeF2§æŠ8qb t_`urŠeü wÅu3êæPv§h•"ß`íÍxçLĹÜÖ3á  ~Öº“®›¸ÏMDfJÙ °„ÛµáWõ%§œ‚à©–‚X ÓØ)@®Ñ›Eþ´wëuÅSxb8y\mÖzœ¥§ZbºE—ÂLªÌw!y(>¡™wú=Ç|ÅÝs¢d €CÁW)HÜcC$€L Ä7„r.á\{)@ð` @ äXÈ$PD” `šaG:§æˆOˆ72EÐamn]ù"ŒcÊxÑŒ° &dR8`g«iÙŸLR!¦P …d’ä¡“¦ðÎTƒ¦ià|À _ ¥ Qi#¦Šg›Æ ›noMµ ›V ã£)p ç£ÎW…š=Âeªk§†j„ ´®1ß²sÉxéW«jšl|0¯B0Û, \jÛ´›6±¬¶C ÛíWþï|ëÙ‹¸ñzĸV {ì;Ýñn¼òVˆm³I¼³.Ðã¤PN¥ ²µ¼„µCã+¹ÍByî£Ñ¾HŸ›ëê 7ìYÆFTk¨SaoaY$Dµœìï¿Ã29RÈkt Çïfñ ÇÒ:ÀÐSp¹3ÇI¨â¥DZÄ ü9Ïýögñ½­uÔ*3)O‘˜Ö[_hv ,àî×Et Ÿé¶BH€ Õ[ü±64M@ÔSÌM7dÐl5-ÄÙU܍´©zߌ3Ô€3ž„ „ ¶ÛPô½5×g› êÚ˜kN„Ý…0Îj4€Ìë°“#{þÕ3S2çKÜ'ợlø¼Ú2K{° {Û¶?žm𸧠ËI¼nEò='êüóºè^üæÃ_Û=°óž‚ì#Oý¿Í'¡½áo..ÏYìnüñCœO±Áa¿¢Kô½o,üÄËbö²çºíï{ËC Ú— "”Ï{ËK ÍÒw„õ±Oz dÕ¨à:$ ƒô—«v»] A#ð «€¿šéz)Rx׿ˆ¥‚d``èw-îyÏf×K!ð€þ­Ð|ìPľ„=Ì`ý(f” 'Pa ¥ÐBJa%Ðâf§„%Š¡}FàáÝ×6>ÉäŠG"éŽè=ø!oа^FP¼Ø©Q„ÀCÙÁ`(Ž\ÄÝ® ©Â$<n@dÄ E#ììUÒI! ‚#lù‹`k¦ÐÇ'Rró’ZýNBÈMF Í[¤+‹ðɈ-áwj¨¥þ8¾rá ,VÂh„"|½œ=×G_¦Ñ™EØ 0i*%̲˜Æda0mV‚k¾)›;„&6 p>ÓjK “¦Ç# âDÂ:ûc?:R Ó¬fÞéI-Ì“•Ã<ä=™Ï7˜3œ¨˜c2ŒW ,ˆ”8(T™P‰F¡Jhç"‚ ; 403WebShell
403Webshell
Server IP : 192.254.185.125  /  Your IP : 216.73.216.196
Web Server : Apache
System : Linux gator3151.hostgator.com 5.14.0-687.42.1.el9_8.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Aug 27 11:55:12 EDT 2026 x86_64
User : diablo ( 32101)
PHP Version : 7.4.33
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : ON
Directory :  /scripts/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /scripts/backups_create_metadata
#!/usr/local/cpanel/3rdparty/bin/perl

# cpanel - scripts/backups_create_metadata         Copyright 2022 cPanel, L.L.C.
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

################################################################################

package scripts::backups_create_metadata;

use strict;
use warnings;

use Cpanel::Backup::Config         ();
use Cpanel::Backup::Metadata       ();
use Cpanel::Backup::StreamFileList ();
use Cpanel::Config::LoadCpConf     ();
use Cpanel::ConfigFiles            ();
use Cpanel::FileUtils::Path        ();
use Cpanel::IONice                 ();
use Cpanel::Logger                 ();
use Cpanel::OSSys                  ();
use Cpanel::OSSys::Capabilities    ();
use Cpanel::SafeRun::Simple        ();

use Getopt::Long ();
use File::Glob   ();
use File::Spec   ();

use Try::Tiny;

################################################################################

our $all;
our $backup;
our $user;
our $vacuum;
our $schedule_rebuild;
our $fix_corrupt;

our $logger;

sub _help {
    my ($msg) = @_;

    print qq{$msg

Usage:

--all - Create metadata for all backups in the configured directory.

e.g. $0 --all
This creates metadata for all backups and users.
If metadata exists, it will delete it and create new metadata.
You cannot combine --all with other options.

--vacuum - Defragment the database and release unused space, runs in the background

e.g. $0 --vacuum
This defragments the database and release unused space.
You cannot combine --vacuum with other options.

--backup=monthly/YYYY-MM-DD - Create metadata for all users in the backup directory that you specify.

e.g. $0 --backup=monthly/2017-03-01
This creates metadata for all users in this backup directory.
You can combine this option with the --user option.
e.g. $0 --backup=monthly/2017-03-01 --user=alvin
This creates metadata for this user in this backup directory.

--user=user - Create metadata only for this user.

e.g. $0 --user=alvin
This creates metadata only for this user.
You can combine this option with the --backup=monthly/YYYY-MM-DD option.
e.g. $0 --backup=monthly/2017-03-01 --user=alvin
This creates metadata for this user in this backup directory.

--schedule_rebuild - Rebuild all metadata in the background.

e.g. $0 --schedule_rebuild
This rebuilds all metadata. The script returns to the command line immediately and
continues to rebuild the metadata in a background task.
You can combine this option with the --fix_corrupt option.
e.g. $0 --schedule_rebuild --fix_corrupt
This scans all user metadata and rebuilds corrupt metadata. The script returns to
the command line immediately and continues to rebuild the metadata in a background
task.

--fix_corrupt - Scans all user metadata to identify and rebuild corrupt metadata.
e.g. $0 --fix_corrupt
This scans all user metadata and rebuilds corrupt metadata.
You can combine this option with the --schedule_rebuild option.
e.g. $0 --schedule_rebuild --fix_corrupt
This scans all user metadata and rebuilds corrupt metadata. The script returns to
the command line immediately and continues to rebuild the metadata in a background
task.
};

    exit 0;
}

sub _invalid_parms {
    _help("invalid parameters");
    die "Invalid Command Line Parameters\n";
}

sub _output {
    my ($line) = @_;

    print $line . "\n";

    return;
}

sub clean_old_metadata_files {
    my ($dir) = @_;

    opendir( my $accounts_dir, "$dir/accounts/" );
    foreach my $file ( readdir($accounts_dir) ) {
        if ( ( $file =~ m/\-\=\-meta/ || $file eq '.sql_dump.gz' ) && -f "$dir/accounts/$file" ) {
            print "Removing old metadata file $dir/accounts/$file\n";
            unlink("$dir/accounts/$file");
        }
    }
    closedir($accounts_dir);

    # Clean old version of single sqlitedb
    unlink '/var/cpanel/backups/metadata.sqlite';

    return;
}

sub create_master_meta {
    my ($dir) = @_;

    my $meta_master = $dir . "/accounts/.master.meta";
    if ( !-e $meta_master ) {
        my $ref = Cpanel::Backup::Metadata::introspect_old_backup($dir);
        if ( defined( $ref->{'backup'}->{'backup_type'} ) && $ref->{'backup'}->{'backup_type'} ne 'ERROR' ) {
            Cpanel::Backup::Metadata::create_meta_master_with_users_from_introspect( $dir, $ref );
        }
        else {
            return 0;    # ignore if the directory cannot be determined
        }
    }

    return 1;
}

# Set our "nice" level

sub apply_nice_level_to_process {
    my ($logger) = @_;
    my $cpconf_ref;
    ( %{$cpconf_ref} ) = Cpanel::Config::LoadCpConf::loadcpconf();

    Cpanel::OSSys::nice(18);    # needs to be one higher for cpuwatch
    my $CAPABILITIES = Cpanel::OSSys::Capabilities->load;
    if ( $CAPABILITIES->capable_of('ionice') ) {
        if ( Cpanel::IONice::ionice( 'best-effort', exists $cpconf_ref->{'ionice_cpbackup'} ? $cpconf_ref->{'ionice_cpbackup'} : 6 ) ) {
            $logger->info( "Setting I/O priority to reduce system load: " . Cpanel::IONice::get_ionice() );
        }
    }
    return;
}

sub _run_vacuum {
    require Cpanel::Daemonizer::Tiny;

    Cpanel::Daemonizer::Tiny::run_as_daemon(
        sub {
            require Cpanel::Logger;
            my $logger = Cpanel::Logger->new();
            sleep 15;
            Cpanel::Backup::Metadata::vacuum_metadata($logger);
        },
        ""
    );

    return;
}

sub _get_raw_backup_dirs {
    my ($backup_master_dir) = @_;

    # get all backup dirs under the main backup
    my %backup_dirs_hash;

    foreach my $dir (
        File::Glob::bsd_glob( $backup_master_dir . "/2*/accounts" ),
        File::Glob::bsd_glob( $backup_master_dir . "/monthly/2*/accounts" ),
        File::Glob::bsd_glob( $backup_master_dir . "/weekly/2*/accounts" ),
        File::Glob::bsd_glob( $backup_master_dir . "/incremental/accounts" )
    ) {
        next if ( !-d $dir );
        my ( $xdir, $accounts ) = Cpanel::FileUtils::Path::dir_and_file_from_path($dir);
        $backup_dirs_hash{$xdir} = 1;
    }

    return %backup_dirs_hash;
}

sub _get_all_backup_dirs {
    my ( $backup_master_dir, %backup_dirs_hash ) = @_;

    # sort this in a smart manner so it plays out like it would have had
    # bin/backup done it.

    my @order;
    foreach my $dir ( sort keys %backup_dirs_hash ) {
        my $introspect_ref;
        try {
            $introspect_ref = Cpanel::Backup::Metadata::introspect_old_backup($dir);
        };
        next if !$introspect_ref;                                        # if it dies this is not a valid backup dir, so just move on
        next if !exists $introspect_ref->{'backup'}->{'backup_id'};
        next if $introspect_ref->{'backup'}->{'backup_id'} eq 'ERROR';

        my @users = keys %{ $introspect_ref->{'users'} };
        next if !@users;
        my $user = $users[0];

        my $category_ref = Cpanel::Backup::StreamFileList::categorize_backup( $backup_master_dir, $dir, $user );

        my $sort_path = $category_ref->{'backupID'};
        if ( $sort_path =~ m{^(monthly|weekly)/(.*)$} ) {
            $sort_path = $2 . '/' . $1;
        }
        else {
            $sort_path .= '/a';    # for sorting consistency a is before (m)onthly
        }

        $category_ref->{'sort_path'} = $sort_path;
        push( @order, $category_ref );
    }

    my @dirs = map { $_->{'path'} } sort { $a->{'sort_path'} cmp $b->{'sort_path'} } @order;

    return @dirs;
}

sub fix_corrupt_metadata {
    my ( $backup_master_dir, @users ) = @_;

    # delete the users db's
    foreach my $user (@users) {
        my $user_db_path = Cpanel::Backup::Metadata::get_metadata_filename( $user, 0 );
        unlink $user_db_path if -f $user_db_path;
    }

    my @dirs = _get_all_backup_dirs( $backup_master_dir, _get_raw_backup_dirs($backup_master_dir) );
    foreach my $user (@users) {
        print "Fixing corrupt backup metadata for $user\n";
        foreach my $dir (@dirs) {
            Cpanel::Backup::Metadata::create_metadata_for_backup_user( $dir, $user, $logger );
        }
    }

    return;
}

sub script {    ##no critic qw(ProhibitExcessComplexity)
    my (@args) = @_;

    $ENV{'LANG'} = 'en_US.UTF-8';

    local $| = 1;
    $logger //= Cpanel::Logger->new( { 'alternate_logfile' => '/dev/stdout' } );

    apply_nice_level_to_process($logger);

    my $opts = Getopt::Long::GetOptionsFromArray(
        \@args,
        'all'              => \$all,
        'backup=s'         => \$backup,
        'user=s'           => \$user,
        'vacuum'           => \$vacuum,
        'schedule_rebuild' => \$schedule_rebuild,
        'fix_corrupt'      => \$fix_corrupt,
    ) or _invalid_parms();

    _help("You must provide at least one option to execute the script.") if ( !$all && !$backup && !$vacuum && !$schedule_rebuild && !$user && !$fix_corrupt );

    _help("You cannot combine --all with other options.") if ( $all && ( $backup || $user || $vacuum || $schedule_rebuild || $fix_corrupt ) );

    _help("You cannot combine --vacuum with other options.") if ( $vacuum && ( $all || $backup || $user || $schedule_rebuild || $fix_corrupt ) );

    _help("You can only combine this option with the --user option.")   if ( $backup && ( $all || $schedule_rebuild || $fix_corrupt || $vacuum ) );
    _help("You can only combine this option with the --backup option.") if ( $user   && ( $all || $schedule_rebuild || $fix_corrupt || $vacuum ) );

    _help("You can only combine this option with the --fix_corrupt option.")      if ( $schedule_rebuild && ( $all || $backup || $user || $vacuum ) );
    _help("You can only combine this option with the --schedule_rebuild option.") if ( $fix_corrupt      && ( $all || $backup || $user || $vacuum ) );

    my $conf              = Cpanel::Backup::Config::load();
    my $backup_master_dir = $conf->{'BACKUPDIR'};

    # if --user is on the command line by itself, leverage the --all code to
    # process all the backups but for this user only.

    if ( $user && !$backup ) {
        $all = $backup_master_dir;
    }

    # if disabled do not do anything, unless it is all then allow the
    # cleanup operation to happen, but then fail

    Cpanel::Backup::Metadata::metadata_disabled_check(1) if ( !$all );

    #We use this two places, may as well just get it now
    my @users;

    if ($user) {
        push( @users, $user );
    }
    else {
        @users = Cpanel::Backup::Metadata::get_all_users();
    }

    if ($all) {
        $all = $backup_master_dir;

        foreach my $this_user (@users) {
            my $db = Cpanel::Backup::Metadata::get_metadata_filename($this_user);
            unlink $db if -f $db;
        }

        my %backup_dirs_hash = _get_raw_backup_dirs($backup_master_dir);

        # clean old metadata
        foreach my $dir ( sort keys %backup_dirs_hash ) {
            try {
                clean_old_metadata_files($dir);

                # delete existing master meta, as it may be of an older type
                my $meta_master = $dir . "/accounts/.master.meta";
                unlink $meta_master if -e $meta_master;
            }
            catch {
                $logger->warn("Failed to clean old metadata for $dir :$_:");
            };
        }

        # allow the clean up to take place regardless of disabled or not
        # but then fail if metadata is disabled
        Cpanel::Backup::Metadata::metadata_disabled_check(1);

        my @dirs = _get_all_backup_dirs( $backup_master_dir, %backup_dirs_hash );
        foreach my $dir (@dirs) {
            print "Processing directory “$dir”\n";
            my $ret;

            try {
                $ret = create_master_meta($dir);
            }
            catch {
                $logger->warn("Failed to create metadata for $dir :$_:");
            };

            next if !$ret;    # ignore if the directory cannot be determined

            try {
                if ($user) {
                    Cpanel::Backup::Metadata::create_metadata_for_backup_user( $dir, $user, $logger );
                }
                else {
                    Cpanel::Backup::Metadata::create_metadata_for_backup( $dir, $logger );
                }
            }
            catch {
                $logger->warn("Failed to create metadata for $dir : $! ($_)");
            };
        }

        _run_vacuum();
    }
    elsif ($backup) {
        $backup = $backup_master_dir . "/$backup";

        my $backup_ref = Cpanel::Backup::StreamFileList::categorize_backup( $backup_master_dir, $backup, "dontcare" );
        if ( $backup_ref->{'backupID'} eq "ERROR" ) {
            _help("backup parameter is not a valid backup");
        }

        if ($user) {
            $backup_ref = Cpanel::Backup::StreamFileList::categorize_backup( $backup_master_dir, $backup, $user );
            if ( $backup_ref->{'type'} eq 'unknown' ) {
                _help("user parameter is not a valid backup");
            }

            try {
                if ( !create_master_meta($backup) ) {
                    die "Cannot create backup";    # is caught and warned
                }
                my $master_meta = Cpanel::Backup::Metadata::load_master_meta($backup);
                foreach my $user_ref ( values %{ $master_meta->{'users'} } ) {

                    next if ( $user_ref->{'user'} ne $user );
                    $logger->info("Processing Backup $backup for User $user");
                    Cpanel::Backup::Metadata::create_metadata_for_backup_user( $backup, $user_ref->{'user'}, $logger );
                    last;
                }
            }
            catch {
                $logger->warn("Failed to create metadata for $backup");
            }
        }
        else {
            try {
                if ( !create_master_meta($backup) ) {
                    die "Cannot create backup";    # is caught and warned
                }

                $logger->info("Processing Backup $backup");
                Cpanel::Backup::Metadata::create_metadata_for_backup( $backup, $logger );
            }
            catch {
                $logger->warn("Failed to create metadata for $backup");
            }
        }

        _run_vacuum();
        $logger->info("Processing is complete.");
    }
    elsif ($vacuum) {
        _run_vacuum();
    }
    elsif ($schedule_rebuild) {
        if ($fix_corrupt) {
            print "Fixing corrupted backup metadata in the background\n";
        }
        else {
            print "Creating all backup metadata in the background\n";
        }

        # remove old metadata, and regen with new schema
        require Cpanel::Daemonizer::Tiny;

        Cpanel::Daemonizer::Tiny::run_as_daemon(
            sub {
                # Don't lose output from the script when it detaches from here and goes off on it's own
                open( STDERR, '>>', $Cpanel::ConfigFiles::CPANEL_ROOT . '/logs/error_log' ) or warn "Could not open cPanel Error Log: $!";
                open( STDOUT, '>>', $Cpanel::ConfigFiles::CPANEL_ROOT . '/logs/error_log' ) or warn "Could not open cPanel Error Log: $!";

                if ($fix_corrupt) {
                    Cpanel::SafeRun::Simple::saferun( '/usr/local/cpanel/scripts/backups_create_metadata', '--fix_corrupt' );
                }
                else {
                    Cpanel::SafeRun::Simple::saferun( '/usr/local/cpanel/scripts/backups_create_metadata', '--all' );
                }
            },
            ""
        );
    }
    elsif ($fix_corrupt) {
        my ( $dbs_valid, $broken_users_ar ) = Cpanel::Backup::Metadata::is_database_valid( \@users );
        if ($dbs_valid) {
            print "No user metadata is corrupt\n";
        }
        else {
            try {
                fix_corrupt_metadata( $backup_master_dir, keys %{$broken_users_ar} );
            }
            catch {
                print "Error fixing corrupt backup metadata: $_\n";
            };
        }
    }

    return 1;
}

exit( script(@ARGV) ? 0 : 1 ) unless caller();

Youez - 2016 - github.com/yon3zu
LinuXploit