blib/script/amberdb_daemon.pl untested

filter: Statementstmt 0.0% 0 / 219 Branchbran 0.0% 0 / 112 Conditioncond 0.0% 0 / 77 MC/DCmcdc 0.0% 0 / 45 Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 484 CC 41 SCAR 40.0
CC
41
Cov
0%
cmd_run
132.0
cmd_start
90.0
get_daemon_pid
56.0
CRAP 54.4
1 #!/usr/local/bin/perl
2  
3 # bin/amberdb_daemon.pl - Unified AmberDB Background Sync Engine & Service Supervisor
4 # Handles runtime lifecycle (start, stop, restart, status, flush) and self-healing cron watchdog.
5  
6 use 5.016;
7 use strict;
8 use warnings;
9 use Getopt::Long qw(:config pass_through);
10 use Fcntl qw(:flock);
11 use File::Spec;
12 use File::Basename qw(dirname);
13 use Cwd qw(abs_path getcwd);
14  
15 BEGIN {
16 use File::Basename qw(dirname);
17 use Cwd qw(abs_path);
18 my $bin_dir = dirname(abs_path(__FILE__));
19 my $lib_dir = abs_path("$bin_dir/../lib");
20 unshift @INC, $lib_dir if -d $lib_dir;
21 }
22  
23 use AmberDB;
24  
25 # Resolve project paths
26 my $script_path = abs_path(__FILE__);
27 my $script_dir = dirname($script_path);
28 my $project_dir = abs_path( File::Spec->catdir( $script_dir, ".." ) );
29 my $lib_dir = File::Spec->catdir( $project_dir, "lib" );
30  
31 my $opt_interval = 1;
32 my $opt_dbase = '';
33 my $opt_ramdisk = '';
34 my $opt_table = undef;
35 my $opt_verbose = 0;
36 my $opt_once = 0;
37 my $opt_help = 0;
38  
39 GetOptions(
40 'interval=i' => \$opt_interval,
41 'dbase_dir=s' => \$opt_dbase,
42 'ramdisk_dir=s' => \$opt_ramdisk,
43 'table=s' => \$opt_table,
44 'verbose|v' => \$opt_verbose,
45 'once' => \$opt_once,
46 'help|h' => \$opt_help,
47 );
48  
49 my $command = shift(@ARGV) // '';
50  
51 # Determine dbase directory
52 my $dbase_dir = $opt_dbase;
53 if ( !defined $dbase_dir || $dbase_dir eq '' ) {
54 my $cwd = abs_path(getcwd());
55 if ( -d File::Spec->catdir( $cwd, "dbstore" ) ) {
56 $dbase_dir = File::Spec->catdir( $cwd, "dbstore" );
57 }
58 elsif ( -d File::Spec->catdir( $cwd, "dbase" ) ) {
59 $dbase_dir = File::Spec->catdir( $cwd, "dbase" );
60 }
61 elsif ( -d File::Spec->catdir( $cwd, "tables" ) ) {
62 $dbase_dir = $cwd;
63 }
64 elsif ( -d File::Spec->catdir( $project_dir, "dbstore" ) ) {
65 $dbase_dir = File::Spec->catdir( $project_dir, "dbstore" );
66 }
67 elsif ( -d File::Spec->catdir( $project_dir, "dbase" ) ) {
68 $dbase_dir = File::Spec->catdir( $project_dir, "dbase" );
69 }
70 else {
71 $dbase_dir = $project_dir;
72 }
73 }
74 $dbase_dir = abs_path($dbase_dir);
75  
76 # Alias --once to flush command
77 if ($opt_once) {
78 $command = 'flush';
79 }
80  
81 if ( $opt_help || $command eq 'usage' || $command eq 'help' || $command eq '' ) {
82 show_usage();
83 exit 0;
84 }
85  
86 # Initialize AmberDB
87 my %adb_paths = ( dbase_dir => $dbase_dir );
88 $adb_paths{ramdisk_dir} = abs_path($opt_ramdisk) if defined $opt_ramdisk && length $opt_ramdisk;
89  
90 my $adb = AmberDB->new( path => \%adb_paths );
91  
92 my $lock_file = File::Spec->catfile( $dbase_dir, "amberdb_sync_daemon.lock" );
93 my $pid_file = File::Spec->catfile( $dbase_dir, "amberdb_daemon.pid" );
94  
95 # Dispatch command
96 if ( $command eq 'start' ) {
97 cmd_start();
98 }
99 elsif ( $command eq 'stop' ) {
100 cmd_stop();
101 }
102 elsif ( $command eq 'restart' ) {
103 cmd_stop();
104 sleep 1;
105 cmd_start();
106 }
107 elsif ( $command eq 'status' ) {
108 cmd_status();
109 }
110 elsif ( $command eq 'flush' ) {
111 cmd_flush();
112 }
113 elsif ( $command eq 'watchdog' || $command eq 'check' ) {
114 cmd_watchdog();
115 }
116 elsif ( $command eq 'run' ) {
117 cmd_run();
118 }
119 else {
120 print STDERR "Unknown command '$command'. Use 'perl $0 usage' for help.\n";
121 exit 1;
122 }
123  
124 # ============================================================================
125 # COMMAND IMPLEMENTATIONS
126 # ============================================================================
127  
128 sub is_daemon_running {
129 return 0 unless -e $lock_file;
130  
131 open my $fh, '<', $lock_file or return 0;
132 if ( flock( $fh, LOCK_EX | LOCK_NB ) ) {
133 # Lock acquired: daemon is NOT running
134 flock( $fh, LOCK_UN );
135 close $fh;
136 return 0;
137 }
138 close $fh;
139  
140 # Lock held by running daemon
141 return 1;
142 }
143  
144 sub get_daemon_pid {
145 if ( -e $pid_file && open my $pfh, '<', $pid_file ) {
146 my $p = <$pfh>;
147 close $pfh;
148 chomp $p if $p;
149 return $p if $p && $p =~ /^\d+$/;
150 }
151 if ( -e $lock_file && open my $lfh, '<', $lock_file ) {
152 my $p = <$lfh>;
153 close $lfh;
154 chomp $p if $p;
155 return $p if $p && $p =~ /^\d+$/;
156 }
157 return undef;
158 }
159  
160 sub cmd_start {
161 if ( is_daemon_running() ) {
162 my $pid = get_daemon_pid() // 'unknown';
163 print "[amberdb_daemon] Daemon is already running (PID: $pid).\n";
164 return;
165 }
166  
167 # Ensure RAM-disk is mounted
168 unless ( $adb->ramdisk_is_mounted() ) {
169 print "[amberdb_daemon] RAM-disk is not mounted. Attempting mount via setup tool...\n" if $opt_verbose;
170 my $setup_pl = File::Spec->catfile( $script_dir, "amberdb_setup.pl" );
171 if ( -e $setup_pl ) {
172 system( qq{"$^X" -Ilib "$setup_pl" --action=ramdisk --start} );
173 }
174 }
175  
176 # Launch background worker process
177 my $perl_bin = $^X;
178 my @cmd_args = (
179 qq{"$perl_bin"},
180 qq{-I"$lib_dir"},
181 qq{"$script_path"},
182 "run",
183 qq{--dbase_dir="$dbase_dir"},
184 qq{--interval=$opt_interval},
185 );
186 push @cmd_args, qq{--ramdisk_dir="$opt_ramdisk"} if $opt_ramdisk;
187 push @cmd_args, qq{--verbose} if $opt_verbose;
188  
189 my $spawn_cmd = join( " ", @cmd_args );
190  
191 if ( $^O eq 'MSWin32' || $^O eq 'msys' || $^O eq 'cygwin' ) {
192 # Detached spawn on Windows
193 system(qq{powershell -NoProfile -Command "Start-Process -FilePath '$perl_bin' -ArgumentList '-I\\"$lib_dir\\" \\"$script_path\\" run --dbase_dir \\"$dbase_dir\\" --interval $opt_interval' -WindowStyle Hidden"});
194 }
195 else {
196 # Detached spawn on Linux / macOS
197 system(qq{nohup $spawn_cmd > /dev/null 2>&1 &});
198 }
199  
200 # Verify startup
201 sleep 1;
202 if ( is_daemon_running() ) {
203 my $pid = get_daemon_pid() // 'active';
204 print "[amberdb_daemon] Started successfully in background (PID: $pid).\n";
205 }
206 else {
207 print STDERR "[amberdb_daemon] Failed to start background daemon. Check logs or permissions.\n";
208 exit 1;
209 }
210 }
211  
212 sub cmd_stop {
213 unless ( is_daemon_running() ) {
214 print "[amberdb_daemon] Daemon is not running.\n";
215 unlink $pid_file if -e $pid_file;
216 return;
217 }
218  
219 my $pid = get_daemon_pid();
220 if ($pid) {
221 print "[amberdb_daemon] Stopping daemon (PID: $pid)...\n";
222 if ( $^O eq 'MSWin32' ) {
223 system("taskkill /PID $pid /F >nul 2>&1");
224 }
225 else {
226 kill( 'TERM', $pid );
227 }
228  
229 # Wait up to 5s for clean shutdown
230 my $wait = 5;
231 while ( is_daemon_running() && $wait > 0 ) {
232 sleep 1;
233 $wait--;
234 }
235 }
236  
237 unlink $pid_file if -e $pid_file;
238  
239 # Flush remaining events upon stop
240 print "[amberdb_daemon] Flushing pending dirty events to disk...\n" if $opt_verbose;
241 my $flushed = $adb->ramdisk_sync_all();
242 print "[amberdb_daemon] Stopped. (Flushed $flushed events on exit)\n";
243 }
244  
245 sub cmd_status {
246 print "=================================================================\n";
247 print " AmberDB Daemon & Sync Subsystem Status \n";
248 print "=================================================================\n";
249 print "Database Root : $dbase_dir\n";
250  
251 my $running = is_daemon_running();
252 my $pid = get_daemon_pid() // '-';
253 print "Daemon Status : " . ( $running ? "RUNNING (PID: $pid)" : "STOPPED" ) . "\n";
254 print "Sync Interval : ${opt_interval}s\n";
255  
256 # RAM-disk status
257 my $setup_info = eval { $adb->ramdisk_setup() } // {};
258 my $is_mounted = $adb->config('ramdisk_mounted') || 0;
259 print "RAM-Disk Status : " . ( $is_mounted ? "MOUNTED (" . ($setup_info->{mount_desc} // 'active') . ")" : "UNMOUNTED" ) . "\n";
260 print "RAM-Disk Path : " . ( $setup_info->{ramdisk_dir} // '-' ) . "\n";
261  
262 # Journal status
263 my $jdir = eval { $adb->journal_dir() };
264 if ( $jdir && -d $jdir ) {
265 my $sync_file = $adb->journal_slot('sync_ramdisk');
266 my $active_lines = 0;
267 if ( -e $sync_file && open my $sfh, '<', $sync_file ) {
268 while (<$sfh>) { $active_lines++; }
269 close $sfh;
270 }
271 my @rotated = eval { $adb->journal_scan('sync_ramdisk_') };
272 print "Journal Queue : $active_lines active event(s) in live queue\n";
273 print "Rotated Batches : " . scalar(@rotated) . " rotated file(s) awaiting flush\n";
274 }
275 print "=================================================================\n";
276 }
277  
278 sub cmd_flush {
279 print "[amberdb_daemon] Running synchronous journal flush to persistent disk...\n" if $opt_verbose;
280 my $synced = 0;
281 if ( defined $opt_table && length $opt_table ) {
282 $synced = $adb->ramdisk_sync($opt_table);
283 }
284 else {
285 $synced = $adb->ramdisk_sync_all();
286 }
287 print "[amberdb_daemon] Flushed $synced dirty event(s) to persistent disk.\n";
288 }
289  
290 sub cmd_watchdog {
291 if ( is_daemon_running() ) {
292 # Daemon is healthy, exit silently in 1ms
293 exit 0;
294 }
295  
296 # Daemon has died or was never started: resurrect it!
297 my ($sec, $min, $hour, $mday, $mon, $year) = localtime();
298 my $stamp = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec );
299 print "[$stamp] [WATCHDOG] AmberDB sync daemon is not running for $dbase_dir. Starting...\n";
300  
301 cmd_start();
302 }
303  
304 sub cmd_run {
305 # Acquire exclusive single-writer daemon lock
306 open my $lock_fh, '>', $lock_file or die "[amberdb_daemon] Could not create lock file '$lock_file': $!\n";
307 unless ( flock( $lock_fh, LOCK_EX | LOCK_NB ) ) {
308 die "[amberdb_daemon] Another instance of the sync daemon is already running for '$dbase_dir'. Exiting.\n";
309 }
310  
311 print $lock_fh "$$\n";
312 $lock_fh->flush();
313  
314 # Write PID file
315 if ( open my $pfh, '>', $pid_file ) {
316 print $pfh "$$\n";
317 close $pfh;
318 }
319  
320 # Setup graceful shutdown handlers
321 my $running = 1;
322 my $sig_handler = sub {
323 my ($sig) = @_;
324 print "\n[amberdb_daemon] Received SIG$sig, shutting down cleanly...\n" if $opt_verbose;
325 $running = 0;
326 };
327 $SIG{INT} = $sig_handler;
328 $SIG{TERM} = $sig_handler;
329  
330 print "[amberdb_daemon] Started worker process (PID: $$, interval: ${opt_interval}s, dbase: $dbase_dir)\n" if $opt_verbose;
331  
332 while ($running) {
333 my $synced = 0;
334 eval {
335 if ( defined $opt_table && length $opt_table ) {
336 $synced = $adb->ramdisk_sync($opt_table);
337 }
338 else {
339 $synced = $adb->ramdisk_sync_all();
340 }
341 };
342 if ($@) {
343 warn "[amberdb_daemon] Error during sync: $@\n";
344 }
345 elsif ( $synced > 0 || $opt_verbose ) {
346 my ($sec, $min, $hour, $mday, $mon, $year) = localtime();
347 my $stamp = sprintf( "%04d-%02d-%02d %02d:%02d:%02d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec );
348 print "[$stamp] [amberdb_daemon] Flushed $synced dirty event(s) to persistent disk.\n";
349 }
350  
351 # Sleep responsive to shutdown
352 my $sleep_left = $opt_interval;
353 while ( $running && $sleep_left > 0 ) {
354 sleep 1;
355 $sleep_left--;
356 }
357 }
358  
359 # Clean up lock and PID
360 flock( $lock_fh, LOCK_UN );
361 close $lock_fh;
362 unlink $lock_file if -e $lock_file;
363 unlink $pid_file if -e $pid_file;
364  
365 print "[amberdb_daemon] Worker process exited cleanly.\n" if $opt_verbose;
366 exit 0;
367 }
368  
369 sub show_usage {
370 print <<"USAGE";
371 =================================================================
372 AmberDB Service Daemon & Runtime Controller
373 =================================================================
374  
375 Usage:
376 perl bin/amberdb_daemon.pl <command> [options]
377  
378 Commands:
379 start Check RAM-disk and start sync daemon in background
380 stop Gracefully stop running daemon and flush queue
381 restart Restart daemon process
382 status Display daemon status, RAM-disk state, and journal queue
383 flush Execute a single synchronous sync pass and exit
384 watchdog Check health; exit immediately if alive, restart if stopped
385 run Run daemon worker in foreground (internal loop)
386 usage, help Show this help message
387  
388 Options:
389 --interval N Sync flush interval in seconds (default: 1)
390 --dbase_dir PATH AmberDB dbase root directory (default: auto-detected)
391 --ramdisk_dir PATH AmberDB RAM-disk directory (default: auto-detected OS RAM-disk)
392 --table NAME Limit sync operations to a specific table
393 --verbose, -v Print verbose operational logs
394  
395 Examples:
396 perl bin/amberdb_daemon.pl start
397 perl bin/amberdb_daemon.pl status
398 perl bin/amberdb_daemon.pl flush
399 perl bin/amberdb_daemon.pl watchdog
400 =================================================================
401 USAGE
402 }
403  
404 1;