Developer-Dashboard

 view release on metacpan or  search on metacpan

lib/Developer/Dashboard/RuntimeManager.pm  view on Meta::CPAN

}

# start_web(%args)
# Starts the dashboard web service in foreground or background mode.
# Input: host, port, worker count, ssl flag, and foreground options.
# Output: server return value in foreground mode or child pid in background mode.
sub start_web {
    my ( $self, %args ) = @_;
    my $host = '0.0.0.0';
    if ( defined $args{host} ) {
        $host = $args{host};
    }
    my $port = 7890;
    if ( defined $args{port} ) {
        $port = $args{port};
    }
    my $workers = 1;
    if ( defined $args{workers} ) {
        $workers = $args{workers};
    }
    my $ssl = $args{ssl} ? 1 : 0;
    die 'Worker count must be a positive integer' if $workers !~ /^\d+$/ || $workers < 1;
    my $foreground = $args{foreground} ? 1 : 0;

    if ($foreground) {
        $self->_close_inherited_fds( preserve_harness => 1 );
        local $ENV{DEVELOPER_DASHBOARD_WEB_SERVICE} = 1;
        local $ENV{DEVELOPER_DASHBOARD_WEB_HOST}    = $host;
        local $ENV{DEVELOPER_DASHBOARD_WEB_PORT}    = $port;
        local $ENV{DEVELOPER_DASHBOARD_WEB_WORKERS} = $workers;
        local $ENV{DEVELOPER_DASHBOARD_WEB_SSL}     = $ssl;
        local $0 = $self->_web_process_title( $host, $port );
        my $server = $self->{app_builder}->( host => $host, port => $port, workers => $workers, ssl => $ssl );
        return $server->run;
    }

    my $running = $self->running_web;
    return $running->{pid}
      if $running
      && $self->_running_web_satisfies_request( $running, $host, $port, $workers, $ssl );

    if (is_windows()) {
        return $self->_start_web_windows_background(
            host    => $host,
            port    => $port,
            workers => $workers,
            ssl     => $ssl,
        );
    }

    return $self->_start_web_background(
        host    => $host,
        port    => $port,
        workers => $workers,
        ssl     => $ssl,
    );
}

# serve_ssl_backend_foreground(%args)
# Rebuilds the normal web application in the isolated TLS backend helper and
# runs its Starman runner against the frontend's internal loopback endpoint.
# Input: internal host, internal port, and worker count.
# Output: backend runner exit status.
sub serve_ssl_backend_foreground {
    my ( $self, %args ) = @_;
    my $host = $args{host} // die 'Missing SSL backend host';
    my $port = $args{port} // die 'Missing SSL backend port';
    my $workers = $args{workers} // 1;
    die 'SSL backend port must be a positive integer' if $port !~ /\A\d+\z/ || $port < 1;
    die 'Worker count must be a positive integer' if $workers !~ /\A\d+\z/ || $workers < 1;
    my $server = $self->{app_builder}->(
        host    => $host,
        port    => $port,
        workers => $workers,
        ssl     => 1,
    );
    require Developer::Dashboard::Web::Server::Daemon;
    my $daemon = Developer::Dashboard::Web::Server::Daemon->new(
        host          => $host,
        port          => $port,
        internal_host => $host,
        internal_port => $port,
    );
    return $server->_run_ssl_backend_process($daemon);
}

# _start_web_background(%args)
# Launches the web listener as an independently supervised GoRoutine child and
# persists its identity after the configured endpoint accepts connections.
# Input: host, port, worker count, and ssl flag.
# Output: listener process id; dies with the child status if startup fails.
sub _start_web_background {
    my ( $self, %args ) = @_;
    my $host = defined $args{host} ? $args{host} : '0.0.0.0';
    my $port = defined $args{port} ? $args{port} : 7890;
    my $workers = defined $args{workers} ? $args{workers} : 1;
    my $ssl = $args{ssl} ? 1 : 0;

    $self->_cleanup_web_files;
    my @command = $self->_background_web_command(
        host    => $host,
        port    => $port,
        workers => $workers,
        ssl     => $ssl,
    );
    require Developer::Dashboard::GoRoutine;
    my $log = $self->{files}->dashboard_log;
    my $pid = Developer::Dashboard::GoRoutine::spawn(
        \@command,
        {
            stdin  => File::Spec->devnull(),
            stdout => $log,
            stderr => $log . '.stderr',
            env    => {
                DEVELOPER_DASHBOARD_WEB_SERVICE => 1,
                DEVELOPER_DASHBOARD_WEB_HOST    => $host,
                DEVELOPER_DASHBOARD_WEB_PORT    => $port,
                DEVELOPER_DASHBOARD_WEB_WORKERS => $workers,
                DEVELOPER_DASHBOARD_WEB_SSL     => $ssl,
            },
        },
    );
    die "Unable to launch dashboard web service process\n" if !$pid;

    for ( 1 .. $self->_runtime_stability_polls ) {
        # R343: a restart deadline bails out of the start poll as soon as
        # it passes, instead of running the full 300-poll budget while
        # the listener never appears. The caller then terminates the
        # child and dies, as on a poll exhaustion. The deadline lives in
        # $self->{_restart_deadline} while a restart is running, so a
        # plain start keeps its full poll budget.
        last if defined $self->{_restart_deadline} && time() >= $self->{_restart_deadline};
        my @listener_pids = $self->_listener_pids_for_port($port);
        if (@listener_pids && $self->_port_accepting_connections($port)) {
            my $listener_pid = $listener_pids[0];
            $listener_pid = $pid if !$listener_pid;
            # The spawned helper becomes the Starman master in-process, but
            # every worker also holds the listen socket, so the ss order may
            # list a worker first. Recording a worker means stop_web only
            # ever signals that worker directly: the master survives a stop
            # whenever listener discovery misses it (for example when the
            # persisted port is stale) and respawns a replacement worker.
            # Prefer the spawned pid whenever it is one of the listeners:
            # it is the master, and also our direct child, so it is the pid
            # stop_web can terminate and reap.
            $listener_pid = $pid if grep { $_ == $pid } @listener_pids;
            my $state = {
                host         => $host,
                pid          => $listener_pid,

lib/Developer/Dashboard/RuntimeManager.pm  view on Meta::CPAN

        # it passes, instead of running the full 300-poll budget while
        # the listener never appears. The caller then confirms the
        # runtime, which fails fast on the same deadline. The deadline
        # lives in $self->{_restart_deadline} while a restart is running,
        # so a plain start keeps its full poll budget.
        last if defined $self->{_restart_deadline} && time() >= $self->{_restart_deadline};
        # The pid query runs on every poll, as the tests pin: a listener
        # is adopted as soon as the query reports it, even before the
        # port accepts connections. But the query's PowerShell fallback
        # costs ~5-9s per call on Windows (solo #351), and before the
        # child has bound there is no listener for it to find - every
        # pre-bind poll paid it. So the query is asked to run its
        # fallback only once the port accepts: the listener is then up,
        # netstat finds it directly in the normal case, and the fallback
        # runs at most once, for a live listener netstat cannot see
        # (build #98). The flag changes nothing when the port already
        # accepts, and nothing when netstat sees the listener.
        my @listener_pids = $self->_listener_pids_for_port( $port, 1 );
        if (@listener_pids) {
            my $listener_pid = $listener_pids[0];
            # See _start_web_background: prefer the spawned master pid over
            # a worker that ss happens to list first.
            $listener_pid = $pid if grep { $_ == $pid } @listener_pids;
            $running = {
                host         => $host,
                pid          => $listener_pid,
                port         => $port + 0,
                process_name => $self->_web_process_title( $host, $port ),
                started_at   => _now_iso8601( tz => "utc" ),
                status       => 'running',
                workers      => $workers + 0,
                ssl          => $ssl + 0,
            };
            last if $self->_port_accepting_connections($port);
        }
        sleep $self->_runtime_poll_interval;
    }

    if ($running) {
        my $state = {
            %{$running},
            host         => $host,
            pid          => $running->{pid} ? $running->{pid} : $pid,
            port         => $port + 0,
            process_name => $running->{process_name},
            started_at   => $running->{started_at},
            status       => 'running',
            workers      => $workers + 0,
            ssl          => $ssl + 0,
        };
        $self->{files}->write( 'web_pid', "$state->{pid}\n" );
        $self->_write_web_state($state);
        return $state->{pid};
    }

    return $pid;
}

# _running_web_satisfies_request($running, $host, $port, $workers, $ssl)
# Decides whether an already running web service satisfies a background start
# request. The endpoint decides identity and must be known: an unknown host or
# port is a mismatch, never an uninitialized-value warning. A property the
# persisted payload does not carry is unverifiable rather than different, so it
# never justifies forking a second listener onto an endpoint that already
# matches, which would strand the running child as an untrackable orphan.
# Input: running web state hash reference, requested host, port, worker count,
# and ssl flag.
# Output: boolean true when the running service already satisfies the request.
sub _running_web_satisfies_request {
    my ( $self, $running, $host, $port, $workers, $ssl ) = @_;
    return 0 if !defined $running->{host} || !defined $running->{port};
    return 0 if $running->{host} ne $host;
    return 0 if $running->{port} != $port;
    return 0 if defined $running->{workers} && $running->{workers} != $workers;
    return 0 if defined $running->{ssl} && $running->{ssl} != $ssl;
    return 1;
}

# _state_settle_polls()
# Returns how many times a lifecycle read re-checks a state file that exists but
# yields no usable payload before concluding there is no state to read. The
# budget stays small on purpose: the window it covers is a single file
# replacement, and every probe pays it when a state file is corrupt rather than
# merely mid-write.
# Input: none.
# Output: positive poll count integer.
sub _state_settle_polls {
    return 10;
}

# _state_settle_interval()
# Returns the pause between re-checks of a state file that exists but yields no
# usable payload.
# Input: none.
# Output: fractional seconds.
sub _state_settle_interval {
    return 0.01;
}

# _read_settled_web_state()
# Reads persisted web state for lifecycle decisions, tolerating the brief window
# in which an existing state file is observable as empty or partially written.
# The lifecycle uses this answer to deduplicate starts and to delete persisted
# files, so a transient observation must never be treated as a fact.
# Input: none.
# Output: two-element list of the state hash reference or undef, and a flag that
# is true when a state file exists but never yielded a usable payload.
sub _read_settled_web_state {
    my ($self) = @_;
    my $file  = $self->{files}->web_state;
    my $polls = $self->_state_settle_polls;
    for my $attempt ( 1 .. $polls ) {
        my $state = $self->web_state;
        return ( $state, 0 ) if ref($state) eq 'HASH';
        return ( undef, 0 ) if !-f $file;
        sleep $self->_state_settle_interval if $attempt < $polls;
    }
    return ( undef, 1 );
}

# _web_state_with_endpoint($state, $pid)
# Builds the running-web answer for one live managed pid, filling a host or port
# the persisted payload does not carry from the live process title. Callers
# compare the reported endpoint against a requested one, so a gap in the
# persisted payload must never surface as an unknown endpoint.
# Input: persisted state hash reference and live process id.
# Output: web state hash reference carrying the live pid.
sub _web_state_with_endpoint {
    my ( $self, $state, $pid ) = @_;
    my $running = {
        %{$state},
        pid => $pid + 0,
    };
    return $running if defined $running->{host} && defined $running->{port};

    my $title = $self->_read_process_title($pid);
    if ( defined $title && $title =~ /^d2 web:\s+(\S+):(\d+)$/ ) {
        $running->{host} = defined $running->{host} ? $running->{host} : $1;
        $running->{port} = defined $running->{port} ? $running->{port} : $2 + 0;
    }
    return $running;
}

# running_web()
# Discovers the currently running managed web service if present.
# Input: none.
# Output: web state hash reference or undef.
sub running_web {
    my ($self) = @_;

    my ( $settled, $unresolved ) = $self->_read_settled_web_state;
    my $state = $settled || {};
    if ( my $pid = $self->{files}->read('web_pid') ) {
        chomp $pid;
        $pid = $self->_normalized_process_id($pid);
        if ( $pid && $self->_pid_is_running($pid) && $self->_same_pid_namespace($pid) ) {
            if ( $self->_is_managed_web($pid) || ( $state->{status} || '' ) eq 'running' ) {
                return $self->_web_state_with_endpoint( $state, $pid );
            }
        }
    }

    for my $proc ( $self->_find_web_processes ) {
        if ( $proc->{args} =~ /^d2 web:\s+(\S+):(\d+)$/ ) {
            return {
                %$state,
                pid          => $proc->{pid},
                host         => $1,
                port         => $2 + 0,
                process_name => $proc->{args},
                status       => 'running',
            };
        }

        return {
            %$state,
            pid          => $proc->{pid},
            host         => $state->{host} || '0.0.0.0',
            port         => $state->{port} || 7890,
            process_name => $proc->{args},
            status       => 'running',
        };
    }

    if ( ( $state->{status} || '' ) eq 'running' ) {
        my @listener_pids = $self->_listener_pids_from_state($state);
        if (@listener_pids) {
            return {
                %$state,
                pid          => $listener_pids[0],
                process_name => $self->_read_process_title( $listener_pids[0] ) || ( $state->{process_name} || '' ),
                status       => 'running',
            };
        }
    }

    # A state file that exists but never yielded a usable payload is evidence of
    # nothing. Removing it here would destroy the persisted identity of a service
    # this probe merely failed to observe, so leave the files for the next read.
    return if $unresolved;

    $self->_cleanup_web_files;
    return;
}

# stop_web()
# Stops the managed web service, including older compatible process shapes.
# Input: none.
# Output: stopped pid or undef.
sub stop_web {
    my ( $self, %args ) = @_;
    my $progress = $args{progress};
    $self->_progress_emit(
        $progress,
        {
            task_id => 'stop_web',
            status  => 'running',
            label   => 'Stop dashboard web service',

lib/Developer/Dashboard/RuntimeManager.pm  view on Meta::CPAN

}

# _run_web_child($writer, $host, $port, %args)
# Runs the daemonized web child lifecycle and reports startup status.
# Input: pipe writer handle, host, port, worker count, ssl flag, and detach/redirect options.
# Output: process exit code.
sub _run_web_child {
    my ( $self, $writer, $host, $port, %args ) = @_;
    my $detach   = exists $args{detach}   ? $args{detach}   : 1;
    my $redirect = exists $args{redirect} ? $args{redirect} : 1;
    my $workers  = exists $args{workers}  ? $args{workers}  : 1;
    my $ssl      = exists $args{ssl}      ? $args{ssl}      : 0;
    if ($detach) {
        my $pid = $self->_start_web_background(
            host    => $host,
            port    => $port,
            workers => $workers,
            ssl     => $ssl,
        );
        $self->_write_startup_pipe_message( $writer, join( '|', 'ok', $pid, $host, $port ) . "\n" );
        return 0;
    }
    if ($redirect) {
        open STDIN, '<', File::Spec->devnull() or die $!;
        open STDOUT, '>>', $self->{files}->dashboard_log or die $!;
        open STDERR, '>>', $self->{files}->dashboard_log or die $!;
    }
    $ENV{DEVELOPER_DASHBOARD_WEB_SERVICE} = 1;
    $ENV{DEVELOPER_DASHBOARD_WEB_HOST}    = $host;
    $ENV{DEVELOPER_DASHBOARD_WEB_PORT}    = $port;
    $ENV{DEVELOPER_DASHBOARD_WEB_WORKERS} = $workers;
    $ENV{DEVELOPER_DASHBOARD_WEB_SSL}     = $ssl;
    local $0 = $self->_web_process_title( $host, $port );
    local $SIGNAL_MANAGER = $self;
    my $shutdown = sub { $self->_shutdown_web('stopped') };
    local $SIG{TERM} = $shutdown;
    local $SIG{INT}  = $shutdown;
    local $SIG{HUP}  = $shutdown;

    my $server = eval { $self->{app_builder}->( host => $host, port => $port, workers => $workers, ssl => $ssl ) };
    if ($@) {
        $self->_write_startup_pipe_message( $writer, "err: $@" );
        return 1;
    }

    my $daemon = eval { $server->start_daemon };
    if ($@) {
        $self->_write_startup_pipe_message( $writer, "err: $@" );
        return 1;
    }

    my $bound_host = $daemon->sockhost;
    my $bound_port = $daemon->sockport;
    my $child_pid = $self->_normalized_process_id($$);

    # The startup pipe is a private handshake with the forking parent, which
    # persists pid and state synchronously before start_web returns. Signalling it
    # before this child's own state write therefore exposes no consumer-visible
    # window: every caller that learns about the service through start_web already
    # sees persisted state, and the write below only refreshes it with the bound
    # endpoint. Keep the order - reversing it would delay the parent's read
    # without closing any window.
    $self->_write_startup_pipe_message( $writer, join( '|', 'ok', $child_pid, $bound_host, $bound_port ) . "\n" );
    # Detached startup returned above, so this child path only needs the
    # inherited-fd cleanup when its I/O was redirected.
    $self->_close_inherited_fds( close_ipc => 1 ) if $redirect;

    $self->_write_web_state(
        {
            host         => $host,
            pid          => $child_pid,
            port         => $bound_port + 0,
            process_name => $self->_web_process_title( $host, $port ),
            started_at   => _now_iso8601( tz => "utc" ),
            status       => 'running',
            bound_host   => $bound_host,
            workers      => $workers + 0,
            ssl          => $ssl + 0,
        }
    );

    eval { $server->serve_daemon($daemon) };
    if ($@) {
        my $message = sprintf "[%s][web] %s\n", _now_iso8601( tz => "utc" ), $@;
        $self->{files}->append( 'dashboard_log', $message );
        $self->_write_web_state(
            {
                host       => $host,
                pid        => $child_pid,
                port       => $bound_port + 0,
                status     => 'error',
                error      => "$@",
                updated_at => _now_iso8601( tz => "utc" ),
                bound_host => $bound_host,
                workers    => $workers + 0,
            }
        );
        return 1;
    }

    $self->_write_web_state(
        {
            host       => $host,
            pid        => $child_pid,
            port       => $bound_port + 0,
            status     => 'stopped',
            updated_at => _now_iso8601( tz => "utc" ),
            bound_host => $bound_host,
            workers    => $workers + 0,
        }
    );
    return 0;
}

# _write_startup_pipe_message($writer, $message)
# Writes one startup status payload to the parent startup pipe without relying
# on buffered stdio semantics in detached children.
# Input: writable startup pipe handle and message string.
# Output: true value after the whole message is written and the handle closed.
sub _write_startup_pipe_message {
    my ( $self, $writer, $message ) = @_;

lib/Developer/Dashboard/RuntimeManager.pm  view on Meta::CPAN

sub _slurp_proc_file {
    my ( $self, $path ) = @_;
    return if !defined $path || $path eq '';
    return if !-r $path;
    open my $fh, '<', $path or return;
    local $/;
    return scalar <$fh>;
}

1;

__END__

=head1 NAME

Developer::Dashboard::RuntimeManager - runtime lifecycle manager

=head1 SYNOPSIS

  my $runtime = Developer::Dashboard::RuntimeManager->new(...);
  my $pid = $runtime->start_web;

=head1 DESCRIPTION

This module manages the lifecycle of the dashboard web service and managed
collector loops, including stop and restart orchestration plus the collector
watchdog that restarts unexpectedly-dead loops and records explicit
attention-required state after repeated crashes. Shutdown uses numeric POSIX
signals internally so minimal Perl builds that reject named signals still stop
managed processes correctly. Cron loops are monitored by their scheduler
heartbeat rather than the age of the last scheduled job execution, so a valid
quiet period does not trigger repeated restart warnings.

=head1 METHODS

=head2 new, start_web, serve_ssl_backend_foreground, running_web, stop_web, start_collectors, serve_all, stop_collectors, stop_all, restart_all, web_state, web_log

Construct and manage the dashboard runtime.

=for comment FULL-POD-DOC START

=head1 PURPOSE

This module manages the dashboard runtime processes. It starts, stops, and restarts the web listener, tracks the web pid, coordinates collector lifecycle around restart/stop flows, supervises managed collector loops with a watchdog, sends numeric POS...

=head1 WHY IT EXISTS

It exists because runtime lifecycle management needs one owner for pid files, process validation, restart ordering, watchdog restart thresholds, and port-release races. That keeps the browser server and collector loops moving together instead of leav...

=head1 WHEN TO USE

Use this file when changing how the web process is launched, how restart waits for ports to free up, how collectors are stopped, restarted, or watchdog-supervised with the web process, or how runtime state is validated before a lifecycle command acts...

For cron collectors, keep scheduler-loop heartbeat separate from job progress:
an old execution timestamp is normal between scheduled runs, while a stale
loop heartbeat still indicates that the scheduler may need recovery.

The C<serve_ssl_backend_foreground> helper entry point rebuilds the normal
dashboard application in the separately supervised internal TLS backend
process. It accepts a host, positive port, and positive worker count, then
serves the TLS Starman runner on that internal endpoint and returns its exit
status. The public SSL frontend launches it through GoRoutine's native process
API so foreground and managed web serving share the same lifecycle contract.

The C<web_log> method reads the d2 log, optionally returns only the last
N lines, or follows appended data after printing that tail. A zero line count
prints no existing lines before follow mode begins; line counts must be
non-negative integers.

=head1 HOW TO USE

Construct it with the path registry and any required collaborators, then call the lifecycle methods from CLI helpers. Keep process orchestration here and let the command wrappers only parse arguments and print results.

=head1 WHAT USES IT

It is used by the C<d2 serve>, C<d2 restart>, and C<d2 stop> helpers, by integration smoke that exercises lifecycle commands, and by tests that cover pid handling and process validation.

=head1 EXAMPLES

Example 1:

  perl -Ilib -MDeveloper::Dashboard::RuntimeManager -e 1

Do a direct compile-and-load check against the module from a source checkout.

Example 2:

  prove -lv t/00-load.t t/21-refactor-coverage.t

Run the focused regression tests that most directly exercise this module's behavior.

Example 3:

  HARNESS_PERL_SWITCHES=-MDevel::Cover prove -lr t

Recheck the module under the repository coverage gate rather than relying on a load-only probe.

Example 4:

  prove -lr t

Put any module-level change back through the entire repository suite before release.

Example 5:

  d2 serve logs -t --tail=0

Read no current log lines with timestamps enabled. When combined with C<-f>,
this starts following future log entries without first printing the existing
content.


=for comment FULL-POD-DOC END

=cut



( run in 0.692 second using v1.01-cache-2.11-cpan-eb134014566 )