summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/pinger.pm
blob: 614d428853c7d0d2efbaa74987edc97e6643a452 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::pinger;
  3. use warnings;
  4. use strict;
  5. use IkiWiki 2.00;
  6. my %pages;
  7. my $pinged=0;
  8. sub import { #{{{
  9. hook(type => "needsbuild", id => "pinger", call => \&needsbuild);
  10. hook(type => "preprocess", id => "ping", call => \&preprocess);
  11. hook(type => "delete", id => "pinger", call => \&ping);
  12. hook(type => "change", id => "pinger", call => \&ping);
  13. } # }}}
  14. sub needsbuild (@) { #{{{
  15. my $needsbuild=shift;
  16. foreach my $page (keys %pagestate) {
  17. if (exists $pagestate{$page}{pinger}) {
  18. $pages{$page}=1;
  19. if (exists $pagesources{$page} &&
  20. grep { $_ eq $pagesources{$page} } @$needsbuild) {
  21. # remove state, will be re-added if
  22. # the ping directive is still present
  23. # on rebuild.
  24. delete $pagestate{$page}{pinger};
  25. }
  26. }
  27. }
  28. } # }}}
  29. sub preprocess (@) { #{{{
  30. my %params=@_;
  31. if (! exists $params{from} || ! exists $params{to}) {
  32. error gettext("requires 'from' and 'to' parameters");
  33. }
  34. if ($params{from} eq $config{url}) {
  35. $pagestate{$params{destpage}}{pinger}{$params{to}}=1;
  36. $pages{$params{destpage}}=1;
  37. return sprintf(gettext("Will ping %s"), $params{to});
  38. }
  39. else {
  40. return sprintf(gettext("Ignoring ping directive for wiki %s (this wiki is %s)"), $params{from}, $config{url});
  41. }
  42. } # }}}
  43. sub ping {
  44. if (! $pinged && %pages) {
  45. $pinged=1;
  46. my $ua;
  47. eval q{use LWPx::ParanoidAgent};
  48. if (!$@) {
  49. $ua=LWPx::ParanoidAgent->new;
  50. }
  51. else {
  52. eval q{use LWP};
  53. if ($@) {
  54. debug(gettext("LWP not found, not pinging"));
  55. return;
  56. }
  57. $ua=LWP::UserAgent->new;
  58. }
  59. $ua->timeout($config{pinger_timeout} || 15);
  60. # daemonise here so slow pings don't slow down wiki updates
  61. defined(my $pid = fork) or error("Can't fork: $!");
  62. return if $pid;
  63. chdir '/';
  64. open STDIN, '/dev/null';
  65. open STDOUT, '>/dev/null';
  66. POSIX::setsid() or error("Can't start a new session: $!");
  67. open STDERR, '>&STDOUT' or error("Can't dup stdout: $!");
  68. # Don't need to keep a lock on the wiki as a daemon.
  69. IkiWiki::unlockwiki();
  70. my %urls;
  71. foreach my $page (%pages) {
  72. if (exists $pagestate{$page}{pinger}) {
  73. $urls{$_}=1 foreach keys %{$pagestate{$page}{pinger}};
  74. }
  75. }
  76. foreach my $url (keys %urls) {
  77. # Try to avoid pinging ourselves. If this check
  78. # fails, it's not the end of the world, since we
  79. # only ping when a page was changed, so a ping loop
  80. # will still be avoided.
  81. next if $url=~/^\Q$config{cgiurl}\E/;
  82. $ua->head($url);
  83. }
  84. exit 0;
  85. }
  86. }
  87. 1