first cut at DaemonService
Matt S Trout [Tue, 29 Nov 2011 21:33:34 +0000 (21:33 +0000)]
lib/Tak/Daemon/DaemonService.pm [new file with mode: 0644]

diff --git a/lib/Tak/Daemon/DaemonService.pm b/lib/Tak/Daemon/DaemonService.pm
new file mode 100644 (file)
index 0000000..d608dca
--- /dev/null
@@ -0,0 +1,56 @@
+package Tak::Daemon::DaemonService;
+
+use POSIX;
+use Log::Contextual ();
+use Log::Contextual::SimpleLogger;
+use Tak::Router;
+use Moo;
+
+with 'Tak::Role::Service';
+
+has 'set_done_cb' => (is => 'rw');
+
+has 'router' => (is => 'lazy');
+
+sub _build_router { Tak::Router->new }
+
+sub handle_daemonize {
+  my ($self) = @_;
+  fork and exit;
+  POSIX::setsid or die "Couldn't setsid: $!";
+  fork and exit;
+  close STDERR;
+  open STDERR, '>', '/dev/null' or die "Couldn't re-open stderr: $!";
+  Log::Contextual::set_logger( # there's no NullLogger? I thought I wrote one
+    Log::Contextual::SimpleLogger->new({ levels => [] })
+  );
+  return 'done';
+}
+
+sub handle_become_successor {
+  my ($self) = @_;
+  my $done;
+  $self->set_done_cb(sub { $done = 1 });
+  $Tak::STDIOSetup::Next = $Tak::STDIOSetup::Next = sub {
+    my $x = $self; # close over
+    $0 = 'tak-daemon-node';
+    Tak->loop_until($done);
+  };
+  return 'done';
+}
+
+sub handle_shutdown {
+  my ($self) = @_;
+  $self->set_done_cb->();
+  return 'done';
+}
+
+sub start_router_request {
+  shift->router->start_request(@_);
+}
+
+sub receive_router {
+  shift->router->receive(@_);
+}
+
+1;