Startup.pm 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package TPSGI::Startup;
  2. # Lightweight startup helpers used by bin/tarbaby before the full TPSGI.pm
  3. # is loaded into workers. Keeping these separate means updating TPSGI.pm
  4. # doesn't require restarting tarbaby to pick up get_config / inotify changes.
  5. use strict;
  6. use warnings;
  7. use Cwd;
  8. use File::Basename qw{dirname};
  9. use File::Find;
  10. use Linux::Perl::inotify;
  11. use Config::Simple;
  12. our @wds;
  13. our $inotify;
  14. =head2 get_config()
  15. Read ~/.tpsgi.ini and return a merged options hash.
  16. =cut
  17. sub get_config {
  18. $ENV{HOME} ||= Cwd::getcwd();
  19. my %options = (
  20. verbose => 0,
  21. custom_log => undef,
  22. routers => [],
  23. loggers => [],
  24. auth => undef,
  25. domain => '',
  26. user => '',
  27. binds => [],
  28. basedir => '.',
  29. http_user => '',
  30. tpsgi_dir => Cwd::getcwd(),
  31. autoreload => 0,
  32. );
  33. my $config_file = "$ENV{HOME}/.tpsgi.ini";
  34. if ( -f $config_file ) {
  35. my $conf = Config::Simple->new($config_file);
  36. my %config;
  37. %config = %{ $conf->param( -block => 'default' ) } if $conf;
  38. foreach my $opt ( keys(%options) ) {
  39. if ( ref $options{$opt} eq 'ARRAY' ) {
  40. next unless exists $config{$opt};
  41. my @arrayed = ref $config{$opt} eq 'ARRAY' ? @{ $config{$opt} } : ( $config{$opt} );
  42. push( @{ $options{$opt} }, @arrayed );
  43. next;
  44. }
  45. $options{$opt} = $config{$opt} if exists $config{$opt};
  46. }
  47. }
  48. my $LOGNAME = "$options{tpsgi_dir}/log/tpsgi.log";
  49. $LOGNAME = $options{custom_log} if $options{custom_log};
  50. my $LOGDIR = dirname($LOGNAME);
  51. $options{log_dir} = $LOGDIR;
  52. $options{log_name} = $LOGNAME;
  53. return %options;
  54. }
  55. =head2 watch_for_changes(@dirs)
  56. Set up inotify watches on the given directories (and any .pm files within them).
  57. Idempotent: no-op if watches are already active.
  58. =cut
  59. sub watch_for_changes {
  60. my (@dirs) = @_;
  61. return if @wds;
  62. $inotify //= Linux::Perl::inotify->new( flags => [qw{NONBLOCK}] );
  63. my @to_watch = _readdir(@dirs);
  64. foreach my $f2watch (@to_watch) {
  65. print "Watching $f2watch for changes\n";
  66. push( @wds, $inotify->add( path => $f2watch, events => [qw{CREATE MODIFY DELETE MOVE}] ) );
  67. }
  68. }
  69. sub _readdir {
  70. my @dirs = @_;
  71. File::Find::find(
  72. {
  73. wanted => sub {
  74. my $object = $_;
  75. push( @dirs, $object ) if ( -f $object && $object =~ m/\.pm$/ );
  76. },
  77. no_chdir => 1,
  78. bydepth => 1,
  79. },
  80. @dirs
  81. );
  82. return @dirs;
  83. }
  84. 1;