Merge branch 'tova' into autoconfig
[ikiwiki.git] / IkiWiki / Plugin / amazon_s3.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::amazon_s3;
3
4 use warnings;
5 no warnings 'redefine';
6 use strict;
7 use IkiWiki 2.00;
8 use IkiWiki::Render;
9 use Net::Amazon::S3;
10
11 # Store references to real subs before overriding them.
12 our %subs;
13 BEGIN {
14         foreach my $sub (qw{IkiWiki::writefile IkiWiki::prune}) {
15                 $subs{$sub}=\&$sub;
16         }
17 };
18
19 sub import { #{{{
20         hook(type => "getopt", id => "amazon_s3", call => \&getopt);
21         hook(type => "getsetup", id => "amazon_s3", call => \&getsetup);
22         hook(type => "checkconfig", id => "amazon_s3", call => \&checkconfig);
23 } # }}}
24
25 sub getopt () { #{{{
26         eval q{use Getopt::Long};
27         error($@) if $@;
28         Getopt::Long::Configure('pass_through');
29         GetOptions("delete-bucket" => sub {
30                 my $bucket=getbucket();
31                 debug(gettext("deleting bucket.."));
32                 my $resp = $bucket->list_all or die $bucket->err . ": " . $bucket->errstr;
33                 foreach my $key (@{$resp->{keys}}) {
34                         debug("\t".$key->{key});
35                         $bucket->delete_key($key->{key}) or die $bucket->err . ": " . $bucket->errstr;
36                 }
37                 $bucket->delete_bucket or die $bucket->err . ": " . $bucket->errstr;
38                 debug(gettext("done"));
39                 exit(0);
40         });
41 } #}}}
42
43 sub getsetup () { #{{{
44         return
45                  amazon_s3_key_id => {
46                         type => "string",
47                         example => "XXXXXXXXXXXXXXXXXXXX",
48                         description => "public access key id",
49                         safe => 1,
50                         rebuild => 0,
51                 },
52                 amazon_s3_key_id => {
53                         type => "string",
54                         example => "$ENV{HOME}/.s3_key",
55                         description => "file holding secret key (must not be readable by others!)",
56                         safe => 0, # ikiwiki reads this file
57                         rebuild => 0,
58                 },
59                 amazon_s3_bucket => {
60                         type => "string",
61                         example => "mywiki",
62                         description => "globally unique name of bucket to store wiki in",
63                         safe => 1,
64                         rebuild => 1,
65                 },
66                 amazon_s3_prefix => {
67                         type => "string",
68                         example => "wiki/",
69                         description => "a prefix to prepend to each page name",
70                         safe => 1,
71                         rebuild => 1,
72                 },
73                 amazon_s3_location => {
74                         type => "string",
75                         example => "EU",
76                         description => "which S3 datacenter to use (leave blank for default)",
77                         safe => 1,
78                         rebuild => 1,
79                 },
80                 amazon_s3_dupindex => {
81                         type => "boolean",
82                         example => 0,
83                         description => "store each index file twice? (allows urls ending in \"/index.html\" and \"/\")",
84                         safe => 1,
85                         rebuild => 1,
86                 },
87 } #}}}
88
89 sub checkconfig { #{{{
90         foreach my $field (qw{amazon_s3_key_id amazon_s3_key_file
91                               amazon_s3_bucket}) {
92                 if (! exists $config{$field} || ! defined $config{$field}) {
93                         error(sprintf(gettext("Must specify %s"), $field));
94                 }
95         }
96         if (! exists $config{amazon_s3_prefix} ||
97             ! defined $config{amazon_s3_prefix}) {
98             $config{amazon_s3_prefix}="wiki/";
99         }
100 } #}}}
101
102 {
103 my $bucket;
104 sub getbucket { #{{{
105         return $bucket if defined $bucket;
106         
107         open(IN, "<", $config{amazon_s3_key_file}) || error($config{amazon_s3_key_file}.": ".$!);
108         my $key=<IN>;
109         chomp $key;
110         close IN;
111
112         my $s3=Net::Amazon::S3->new({
113                 aws_access_key_id => $config{amazon_s3_key_id},
114                 aws_secret_access_key => $key,
115                 retry => 1,
116         });
117
118         # make sure the bucket exists
119         if (exists $config{amazon_s3_location}) {
120                 $bucket=$s3->add_bucket({
121                         bucket => $config{amazon_s3_bucket},
122                         location_constraint => $config{amazon_s3_location},
123                 });
124         }
125         else {
126                 $bucket=$s3->add_bucket({
127                         bucket => $config{amazon_s3_bucket},
128                 });
129         }
130
131         if (! $bucket) {
132                 error(gettext("Failed to create bucket in S3: ").
133                         $s3->err.": ".$s3->errstr."\n");
134         }
135
136         return $bucket;
137 } #}}}
138 }
139
140 # Given a file, return any S3 keys associated with it.
141 sub file2keys ($) { #{{{
142         my $file=shift;
143
144         my @keys;
145         if ($file =~ /^\Q$config{destdir}\/\E(.*)/) {
146                 push @keys, $config{amazon_s3_prefix}.$1;
147
148                 # Munge foo/index.html to foo/
149                 if ($keys[0]=~/(^|.*\/)index.$config{htmlext}$/) {
150                         # A duplicate might need to be stored under the
151                         # unmunged name too.
152                         if (!$config{usedirs} || $config{amazon_s3_dupindex}) {
153                                 push @keys, $1;
154                         }
155                         else {
156                                 @keys=($1);
157                         }
158                 }
159         }
160         return @keys;
161 } #}}}
162
163 package IkiWiki;
164 use File::MimeInfo;
165 use Encode;
166
167 # This is a wrapper around the real writefile.
168 sub writefile ($$$;$$) { #{{{
169         my $file=shift;
170         my $destdir=shift;
171         my $content=shift;
172         my $binary=shift;
173         my $writer=shift;
174
175         # First, write the file to disk.
176         my $ret=$IkiWiki::Plugin::amazon_s3::subs{'IkiWiki::writefile'}->($file, $destdir, $content, $binary, $writer);
177                 
178         my @keys=IkiWiki::Plugin::amazon_s3::file2keys("$destdir/$file");
179
180         # Store the data in S3.
181         if (@keys) {
182                 my $bucket=IkiWiki::Plugin::amazon_s3::getbucket();
183
184                 # The http layer tries to downgrade utf-8
185                 # content, but that can fail (see
186                 # http://rt.cpan.org/Ticket/Display.html?id=35710),
187                 # so force convert it to bytes.
188                 $content=encode_utf8($content) if defined $content;
189
190                 my %opts=(
191                         acl_short => 'public-read',
192                         content_type => mimetype("$destdir/$file"),
193                 );
194
195                 # If there are multiple keys to write, data is sent
196                 # multiple times.
197                 # TODO: investigate using the new copy operation.
198                 #       (It may not be robust enough.)
199                 foreach my $key (@keys) {
200                         my $res;
201                         if (! $writer) {
202                                 $res=$bucket->add_key($key, $content, \%opts);
203                         }
204                         else {
205                                 # This test for empty files is a workaround
206                                 # for this bug:
207                                 # http://rt.cpan.org//Ticket/Display.html?id=35731
208                                 if (-z "$destdir/$file") {
209                                         $res=$bucket->add_key($key, "", \%opts);
210                                 }
211                                 else {
212                                         # read back in the file that the writer emitted
213                                         $res=$bucket->add_key_filename($key, "$destdir/$file", \%opts);
214                                 }
215                         }
216                         if (! $res) {
217                                 error(gettext("Failed to save file to S3: ").
218                                         $bucket->err.": ".$bucket->errstr."\n");
219                         }
220                 }
221         }
222
223         return $ret;
224 } #}}}
225
226 # This is a wrapper around the real prune.
227 sub prune ($) { #{{{
228         my $file=shift;
229
230         my @keys=IkiWiki::Plugin::amazon_s3::file2keys($file);
231
232         # Prune files out of S3 too.
233         if (@keys) {
234                 my $bucket=IkiWiki::Plugin::amazon_s3::getbucket();
235
236                 foreach my $key (@keys) {
237                         my $res=$bucket->delete_key($key);
238                         if (! $res) {
239                                 error(gettext("Failed to delete file from S3: ").
240                                         $bucket->err.": ".$bucket->errstr."\n");
241                         }
242                 }
243         }
244
245         return $IkiWiki::Plugin::amazon_s3::subs{'IkiWiki::prune'}->($file);
246 } #}}}
247
248 1