Your IP : 216.73.216.209


Current Path : /scripts/
Upload File :
Current File : //scripts/backup_jobs_helper

#!/usr/local/cpanel/3rdparty/bin/perl

#                                      Copyright 2025 WebPros International, LLC
#                                                            All rights reserved.
# copyright@cpanel.net                                          http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited.

package scripts::backup_jobs_helper;

use cPstrict;

use Getopt::Long qw(GetOptions);
use Pod::Usage   qw(pod2usage);
use Time::Piece  ();
use Cpanel::Logger;
use Cpanel::Debug ();

use Cpanel::Plugins::FileLock         ();
use Whostmgr::CometBackup::BackupJobs ();
use Whostmgr::CometBackup::Scheduling ();
use Whostmgr::CometBackup::Constants  ();
use Data::UUID                        ();
use POSIX                             ();

my $LOCK_FILE = '/var/run/comet_backup_jobs_helper.lock';

my $logger = Cpanel::Logger->new();

=encoding utf-8

=head1 NAME

backup_jobs_helper - Process scheduled backup jobs for Comet Backup integration

=head1 SYNOPSIS

backup_jobs_helper [options]

=head1 DESCRIPTION

This script processes scheduled backup jobs by checking which jobs are due to run
and executing them. It is designed to be called periodically by cron.

The script performs the following operations:

=over

=item * Retrieves all active backup jobs from the database

=item * Checks which jobs are scheduled to run at the current time

=item * Executes any due backup jobs

=item * Updates job status and last run timestamps

=back

=head1 OPTIONS

=over

=item --help

Show this help message and exit.

=item --verbose

Enable verbose logging output.

=item --debug

Enable debug logging output (shows detailed scheduling calculations).

=item --dry-run

Show what would be done without actually executing backup jobs.

=back

=head1 EXAMPLES

    # Process backup jobs normally
    /usr/local/cpanel/scripts/backup_jobs_helper

    # Show what would be done without executing
    /usr/local/cpanel/scripts/backup_jobs_helper --dry-run

    # Enable verbose output
    /usr/local/cpanel/scripts/backup_jobs_helper --verbose

    # Enable debug output
    /usr/local/cpanel/scripts/backup_jobs_helper --debug

=cut

sub main {

    # Plugin policy: nothing in this process should be world-readable.
    umask 0027;

    my ( $help, $verbose, $dry_run, $debug );

    GetOptions(
        'help|h'    => \$help,
        'verbose|v' => \$verbose,
        'dry-run'   => \$dry_run,
        'debug|d'   => \$debug,
    ) or pod2usage(2);

    pod2usage(1) if $help;

    # Enable debug logging if --debug flag is set
    if ($debug) {
        $Cpanel::Debug::level = 1;
    }

    my $lock_obj = Cpanel::Plugins::FileLock->new($LOCK_FILE);

    if ( -e $LOCK_FILE ) {
        if ( $lock_obj->exists() ) {

            # SafeFile confirms the lock is held by a live process — exit cleanly.
            $logger->info('Another backup_jobs_helper is already running; exiting.');
            exit 0;    ## no critic (Cpanel::NoExitsFromSubroutines)
        }

        # Lock file exists but SafeFile does not consider it held (previous
        # process died without cleaning up) — remove the stale file so
        # create() can succeed.
        $logger->warn("Removing stale lock (previous process is no longer running)");
        unlink $LOCK_FILE or $logger->warn("Could not unlink stale lock $LOCK_FILE: $!");
    }

    my $lock = $lock_obj->create();
    unless ($lock) {
        $logger->error("Failed to acquire lock $LOCK_FILE; cannot proceed.");
        exit 1;
    }

    # Disable DESTROY-based release immediately — we manage cleanup manually.
    $lock_obj->disable_auto_cleanup();

    my $current_time = time();
    my $current_dt   = Time::Piece->new($current_time);

    if ($verbose) {
        $logger->info( "Starting backup jobs helper at " . $current_dt->strftime('%Y-%m-%d %H:%M:%S') );
    }

    eval {
        my $jobs_manager = Whostmgr::CometBackup::BackupJobs->new();
        my $scheduler    = Whostmgr::CometBackup::Scheduling->new();

        # Get all active scheduled backup jobs
        my @active_jobs = $jobs_manager->get_backup_jobs();

        if ($verbose) {
            $logger->info( "Found " . scalar(@active_jobs) . " active backup jobs" );
        }

        # comet_backup_runner enforces a system-wide single-runner guard via
        # its PID file: a second runner invocation will exit immediately. If a
        # runner is already active we must not mark any due job 'running' or
        # fork a second runner — the runner would die on its PID-file guard
        # and the DB row would be left stuck. Bail out of this sweep; the
        # cron tick will retry once the current runner finishes.
        if ( !$dry_run ) {
            if ( my $active_pid = Whostmgr::CometBackup::Constants::existing_runner_pid() ) {
                $logger->info("comet_backup_runner already active (PID $active_pid); skipping this sweep.");
                return;
            }
        }

        my $jobs_processed   = 0;
        my $runner_dispatched = 0;

        for my $job (@active_jobs) {

            $logger->debug( "LOOKING AT JOB: " . $job->{job_id} . " ( " . $job->{description} . " | $job->{schedule_type} )" );

            # Skip manual jobs - they are not scheduled
            next if $job->{schedule_type} eq 'manual';

            # Skip if job is currently running
            next if $job->{status} && $job->{status} eq 'running';

            # Check if this job should run now
            my $should_run = _should_job_run_now( $job, $scheduler );

            if ($should_run) {
                if ($verbose) {
                    $logger->info( "Processing backup job: " . $job->{name} . " (job_id: " . $job->{job_id} . ")" );
                }

                if ($dry_run) {
                    print "Would execute backup job: " . $job->{name} . " (job_id: " . $job->{job_id} . ")\n";
                    $jobs_processed++;
                    next;
                }

                # Only one runner can be active system-wide. Dispatch the
                # first due job, then stop — additional due jobs will be
                # picked up by the next cron tick once this runner exits.
                _execute_backup_job( $jobs_manager, $job );
                $jobs_processed++;
                $runner_dispatched = 1;
                last;
            }
        }

        if ($verbose) {
            $logger->info("Processed $jobs_processed backup jobs");
            if ($runner_dispatched) {
                $logger->info("Deferred remaining due jobs to subsequent cron ticks (single-runner policy).");
            }
        }

        if ( ( $verbose || $debug ) && $dry_run && $jobs_processed == 0 ) {
            $logger->info("No backup jobs are currently due to run");
        }
    };

    $lock_obj->remove($lock);

    if ($@) {
        $logger->error("Error in backup jobs helper: $@");
        exit 1;
    }

    if ($verbose) {
        $logger->info("Backup jobs helper completed successfully");
    }
}

sub _should_job_run_now {
    my ( $job, $scheduler ) = @_;

    # Parse job configuration
    my $schedule_info = $job->{schedule_info} || {};
    my $last_run      = $job->{last_run};

    # Calculate next run time based on schedule
    my $next_run_time;

    eval { $next_run_time = $scheduler->calculate_next_run( $schedule_info, $last_run ); };

    if ($@) {
        $logger->warn( "Could not calculate next run time for job " . $job->{job_id} . ": $@" );
        return 0;
    }

    $logger->debug( "Next run time for job " . $job->{job_id} . " ( $job->{description} ) : " . scalar localtime($next_run_time) );

    # Re-sample the clock immediately before comparing so that any gap between
    # script start and the scheduler's own Time::Piece->new() call (which
    # returns $now for never-run jobs) cannot make the comparison permanently
    # false by a few seconds.
    return defined $next_run_time && time() >= $next_run_time;
}

sub _execute_backup_job {
    my ( $jobs_manager, $job ) = @_;

    my $job_id = $job->{job_id};

    eval {
        # Generate a unique run_uuid for this backup run instance
        require Data::UUID;
        my $ug       = Data::UUID->new();
        my $run_uuid = lc( $ug->create_str() );

        $logger->info( "Starting backup job: " . $job->{name} . " (job_id: $job_id, run_uuid: $run_uuid)" );

        # Store the current_run_uuid in the backup_jobs table for tracking
        $jobs_manager->set_current_run_uuid( $job_id, $run_uuid );

        # Update job status to running and set last run timestamp
        $jobs_manager->update_backup_job(
            $job_id,
            status             => 'running',
            last_run_timestamp => time(),
        );

        # Fork the backup runner script in the background
        my $backup_runner_path = $Whostmgr::CometBackup::Constants::BACKUP_RUNNER_PATH;

        unless ( -x $backup_runner_path ) {
            die "Backup runner script not found or not executable: $backup_runner_path";
        }

        my $pid = fork();

        if ( !defined $pid ) {

            # Fork failed
            die "Failed to fork backup runner process: $!";
        }

        if ( $pid == 0 ) {

            # Child process - exec the backup runner.
            # All failure paths use POSIX::_exit so the child never unwinds
            # back into main()'s eval, which would corrupt the lock state.
            # umask 0027 was set at the top of main() and the child inherits it.
            open STDOUT, '>>', '/var/log/comet_backup_jobs_helper.log' or POSIX::_exit(1);
            open STDERR, '>>', '/var/log/comet_backup_jobs_helper.log' or POSIX::_exit(1);

            # Become session leader to fully detach
            POSIX::setsid() or POSIX::_exit(1);

            # Execute the backup runner with run_uuid; _exit if exec fails.
            # --bypass-schedule: the helper has already made its own scheduling
            # decision, so we skip the runner's redundant cooldown check. The
            # runner's "one runner at a time" guard still applies.
            exec( $backup_runner_path, '--bypass-schedule', '--job_uuid', $job_id, '--run_uuid', $run_uuid )
              or POSIX::_exit(1);
        }

        # Parent process - just log that we started the runner
        $logger->info( "Forked backup runner process (PID: $pid) for job: " . $job->{name} );
    };

    if ($@) {
        $logger->error( "Failed to execute backup job " . ( $job_id // 'job_id UNSET' ) . ": $@" );

        # Update job status to failed
        eval {
            $jobs_manager->update_backup_job(
                $job_id,
                status => 'failed',
            );
            $jobs_manager->clear_current_run_uuid($job_id);
        };
    }
}

# Run the main function if this script is executed directly
main() if !caller;

1;

__END__

=head1 SEE ALSO

L<Whostmgr::CometBackup::BackupJobs>, L<Whostmgr::CometBackup::Scheduling>

=head1 AUTHOR

WebPros International, LLC

=head1 COPYRIGHT

Copyright 2025 WebPros International, LLC. All rights reserved.

=cut

Rosenblum TV: Video training, virtual workshops, classes, tutorials
logologologologo
  • About
  • What We Do
  • Our Clients
  • Case Studies
    • The BBC
    • CBS News
    • New York Times Television
    • Spectrum News
    • The Newark Star-Ledger
    • The United Nations
    • McGraw/Hill
    • Oyster Yachts
    • Scottish Environmental Protection Agency
  • The Power of Storytelling
  • Why iPhones?
  • Michael on Media
  • Books
  • Contact
  • About
  • What We Do
  • Our Clients
  • Case Studies
    • The BBC
    • CBS News
    • New York Times Television
    • Spectrum News
    • The Newark Star-Ledger
    • The United Nations
    • McGraw/Hill
    • Oyster Yachts
    • Scottish Environmental Protection Agency
  • The Power of Storytelling
  • Why iPhones?
  • Michael on Media
  • Books
  • Contact

RE-INVENTING THE TELEVISION NEWS BUSINESS*

A revolution in video storytelling

Creating entirely new & cost-effective production methods

From the world leaders in video production training and the creators of Character Driven Storytelling™

*and every other business that uses video

WHAT WE DO

Over the past 35 years, we have designed, built or restructured some of the most powerful news and journalism companies in the world.

We replace the traditional TV news ‘crew’ with one highly trained journalist, working alone with nothing but an iPhone.

No more TV news ‘crews’, no editors and no field producers.

This is television news done the way newspaper journalism is done – one reporter with their electronic pad and pencil.

In doing this, we can cut the cost of production by as much as 75% while increasing ratings and audience engagement.

In the place of conventional TV news ‘packages’ – ie, reporter stand up, interview, b-roll, man on the street, we marry great journalism with Netflix and Hollywood storytelling.

It’s a combination that works.

We have taken most of our clients to #1 in their respective markets.

And it’s not just for news. Any company, any profit, any NGO and anyone else who is online needs to tell their story in compelling yet cost-effective video. We can teach you to do that. Either in person or virtually.

EXAMPLES OF WHAT WE CAN TEACH YOUR STAFF TO PRODUCE

ITAY HOD

Itay Hod, MMJ with KPIX/CBS in San Francisco, took the 5-Day Intensive Video Storytelling Bootcamp in 2018.

Because he works alone, with only an iPhone, he was able to embed himself with a homeless family.

Here’s the story he produced in a one-day turn.

KIET DO

Kiet Do, an MMJ with KPIX/CBS in San Francisco, took the 5-Day Intensive Video Storytelling Bootcamp in 2021.

Here is a story he produced, all on his own, with only an iPhone and in a one-day turn.

TAYLOR SCHAUB

Taylor Schaub, an MMJ with Spectrum News 1 in LA, took the 5-Day Intensive Video Storytelling Bootcamp in 2023.

Here is a story he turned in only one day, using only an iPhone. It was the first video story he ever did and it was nominated for an Emmy.

THE BOOTCAMP

How do we convert stations and whole networks to working in this way?

Since 1988, we have run intensive 5-Day Video Storytelling Bootcamps

We have done these all over the world.

These are hands-on bootcamps, and participants learn an entirely new way of creating TV news stories.

-We shoot at a 3:1 ratio or lower, so turnaround times are fast.

-We go directly from camera to timelilne and edit – no written scripts.  We work in the medium of pictures and sound.

-We are entirely character-driven.

-We are driven by pictures and real events.

-We are focused almost entirely on ’the viewer experience’.

Since 1988, more than 70,000 journalists around the world have taken our bootcamps, either in person on virtualy.

Case Studies

CBS Case Study Logos
CBS News

We have started to work with CBS News, bringing our ideas of character-driven storytelling to one of the most successful and biggest networks in the United States. Since beginning to work with them ratings have climbed and more importantly, audience engagement is through the ceiling.

Learn More
NYT Case Study Logos
New York Times Television

We started New York Times Television in 1990 and it was the first paper to be brought into the world of TV. It quickly became one of the most successful non-fiction production companies in the United States. The series and documentaries we produced won many awards including multiple Emmys.

Learn More
BBC Case Study Logos
The BBC

We have been working with the BBC since the year 2000 helping to convert their national news network to our visual storytelling technique. Most recently we have trained teams from their sports, documentaries, and comedy divisions to make character-driven stories using only smartphones.

Learn More
Spectrum Case Study Logos
Spectrum News

For the past five years we have worked with Spectrum News to introduce and train their journalists on visual, character driven storytelling using smartphones helping to create a different kind of local news for their network of 24-Hour News Stations across the United States.

Learn More
UN Case Study Logos
The United Nations

In 2006, we were approached by the United Nations. Rather than rely on news outlets, it would be much easier to train the field operatives to produce their own stories. We spent two years working with the UN, training more than 100 of their staff in bootcamps in Geneva and Nairobi.

Learn More
Star Ledger Case Study Logos
The Newark Star-Ledger

We trained 50 print reporters at the paper to shoot and tell their own stories, in conjunction with their print work. We built a TV newsroom in their existing print newsroom – you could not ask for a better set and they began to live stream their stories in conjunction with their print work.

Learn More
Mcgraw Hill Case Study Logos
Mcgraw Hill

We spent two years with McGraw Hill, training more than 150 of their staffers, making them completely video literate. McGraw/Hill media properties we transit included Business Week, Aviation Week, (what was the name of the architecture magazine), and JD Power and Associates.

Learn More
VOA Case Study Logos
Voice of America

In 1990, we were approached by The Voice of America, the official broadcasting agency for the United States Government. When we met with VOA, they were only a short wave radio broadcaster, but working with them, we took them into television, launching VOA-TV.

Learn More
Oyster Case Study Logos
Oyster Yachts

British based Oyster Yachts makes some of the finest yachts in the world. Like every other company, they had to find a way to feed the never-ending video demands of social media – sites like Instagram and TikTok. We trained the Oyster staff to tell their own stories, using only iPhones.

Learn More
SEPA Case Study Logos
Scottish Environmental Protection Agency

We were approached by SEPA, the Scottish Environmental Protection Agency because they had to continually find a way to ‘feed the media beast’. The result was that SEPA was able to tell their own stories, whenever they wanted, and at almost no additional cost.

Learn More
Image 11-11-22 at 6.25 PM

Michael on Media

Michael Rosenblum has been writing about the media since 1988. His work and ideas have appeared in The Guardian, The Huffington Post, Ilkeston Life and many other publications.

He has been blogging regularly for the past 35 years on this subject. Having taught media studies at Columbia University, NYU and now the University of Oxford, he is considered an expert on this subject.

Continue reading this post or look back at previous posts.

Read More

Do You Have Questions About Learning Video Skills?

If you would like to know more about our courses contact us and one of our training advisors will be happy to call you.

Contact Us

Copyright 2024. All rights reserved.