summaryrefslogtreecommitdiff
path: root/rt/sbin/rt-fulltext-indexer.in
blob: 53dc3fd2afdd5386ec098360b24a0d5a5aa74c22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!@PERL@
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2017 Best Practical Solutions, LLC
#                                          <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}
use strict;
use warnings;
use 5.010;

# fix lib paths, some may be relative
BEGIN { # BEGIN RT CMD BOILERPLATE
    require File::Spec;
    require Cwd;
    my @libs = ("@RT_LIB_PATH@", "@LOCAL_LIB_PATH@");
    my $bin_path;

    for my $lib (@libs) {
        unless ( File::Spec->file_name_is_absolute($lib) ) {
            $bin_path ||= ( File::Spec->splitpath(Cwd::abs_path(__FILE__)) )[1];
            $lib = File::Spec->catfile( $bin_path, File::Spec->updir, $lib );
        }
        unshift @INC, $lib;
    }

}

use RT -init;
use RT::Interface::CLI ();
use HTML::Entities;

use Getopt::Long qw(GetOptions);
my %OPT = ( memory => '2M', limit => 0 );
GetOptions( \%OPT,
    "help|h!",
    "debug!",
    "quiet!",

    "all!",
    "limit=i",

    "memory=s",
);
$OPT{limit} ||= 200;

RT::Interface::CLI->ShowHelp if $OPT{help};

use Fcntl ':flock';
if ( !flock main::DATA, LOCK_EX | LOCK_NB ) {
    if ( $OPT{quiet} ) {
        RT::Logger->info("$0 is already running; aborting silently, as requested");
        exit;
    }
    else {
        print STDERR "$0 is already running\n";
        exit 1;
    }
}

my $max_size = RT->Config->Get('MaxFulltextAttachmentSize');

my $db_type = RT->Config->Get('DatabaseType');
my $fts_config = $ENV{RT_FTS_CONFIG} ? JSON::from_json($ENV{RT_FTS_CONFIG})
    : RT->Config->Get('FullTextSearch') || {};
unless ( $fts_config->{'Enable'} ) {
    print STDERR <<EOT;

Full text search is disabled in your RT configuration.  Run
@RT_SBIN_PATH_R@/rt-setup-fulltext-index to configure and enable it.

EOT
    exit 1;
}
unless ( $fts_config->{'Indexed'} ) {
    print STDERR <<EOT;

Full text search is enabled in your RT configuration, but not with any
full-text database indexing -- hence this tool is not required.  Read
the documentation for %FullTextSearch in your RT_Config for more details.

EOT
    exit 1;
}

if ( $db_type eq 'Oracle' ) {
    my $index = $fts_config->{'IndexName'} || 'rt_fts_index';
    $RT::Handle->dbh->do(
        "begin ctx_ddl.sync_index(?, ?); end;", undef,
        $index, $OPT{'memory'}
    );
    exit;
} elsif ( $fts_config->{Sphinx} ) {
    print STDERR <<EOT;

Updates to the external Sphinx index are done via running the sphinx
`indexer` tool:

    indexer rt

EOT
    exit 1;
}

# Skip ACL checks.  This saves a large number of unnecessary queries
# (for tickets, ACLs, and users) which are unnecessary, as we are
# running as the system user.
{
    no warnings 'redefine';
    no warnings 'once';
    *RT::Attachment::_Value = \&DBIx::SearchBuilder::Record::_Value;
    *RT::Attachments::Next  = \&DBIx::SearchBuilder::Next;
}

my $LAST;
if ($db_type eq 'mysql') {
    process_mysql();
} elsif ($db_type eq 'Pg') {
    process_pg();
}

sub attachment_loop {
    my $subref = shift;
    my $table = $fts_config->{'Table'};
    $LAST //= 0;

    # Fetch in batches of size --limit
    {
        # Indexes all text/plain and text/html attachments
        my $attachments = RT::Attachments->new( RT->SystemUser );
        $attachments->Limit(
            FIELD    => 'ContentType',
            OPERATOR => 'IN',
            VALUE    => ['text/plain', 'text/html'],
        );
        $attachments->Limit( FIELD => 'id', OPERATOR => '>', VALUE => $LAST );
        $attachments->OrderBy( FIELD => 'id', ORDER => 'asc' );
        $attachments->RowsPerPage( $OPT{'limit'} );

        # Call back to the DB-specific part
        $subref->($attachments);

        $LAST = $attachments->Last->id if $attachments->Count;

        redo if $OPT{'all'} and $attachments->Count == $OPT{'limit'};
    }
}

sub process_bulk_insert {
    my $dbh = $RT::Handle->dbh;
    my ($statement, $error) = @_;

    # Doing large inserts is faster than individual statements, but
    # comes at a parsing cost; cache the statement handles (99% of which
    # will be the same size) for a notable (2x) speed gain.
    my %sthandles;

    $sthandles{1} =
        $dbh->prepare($statement->(1));

    attachment_loop( sub {
        my ($attachments) = @_;
        my @insert;
        my $found = 0;

        while ( my $a = $attachments->Next ) {
            debug("Found attachment #". $a->id );
            if ( $max_size and $a->ContentLength > $max_size ){
                debug("Attachment #" . $a->id . " is " . $a->ContentLength .
                      " bytes which is larger than configured MaxFulltextAttachmentSize " .
                      " of " . $max_size . ", skipping");
                next;
            }

            my $text = $a->Content // "";
            HTML::Entities::decode_entities($text) if $a->ContentType eq "text/html";
            push @insert, $text, $a->id;
            $found++;
        }
        return unless $found;

        # $found should be the limit size on all but the last go-around.
        $sthandles{$found} ||= $dbh->prepare($statement->($found));

        return if eval { $sthandles{$found}->execute(@insert); };

        # We can catch and recover from some errors; re-do row-by-row to
        # know which row had which errors
        while (@insert) {
            my ($content, $id) = splice(@insert,0,2);
            next if eval { $sthandles{1}->execute($content, $id); };
            $error->($id, $content);

            # If this was a semi-expected error, insert an empty
            # tsvector, so we count this row as "indexed" for
            # purposes of knowing where to pick up
            eval { $sthandles{1}->execute( "", $id ) }
                or die "Failed to insert empty row for attachment $id: " . $dbh->errstr;
        }
    });
}

sub process_mysql {
    my $dbh = $RT::Handle->dbh;
    my $table = $fts_config->{'Table'};

    ($LAST) = $dbh->selectrow_array("SELECT MAX(id) FROM $table");

    my $insert = $fts_config->{Engine} eq "MyISAM" ? "INSERT DELAYED" : "INSERT";

    process_bulk_insert(
        sub {
            my ($n) = @_;
            return "$insert INTO $table(Content, id) VALUES "
                . join(", ", ("(?,?)") x $n);
        },
        sub {
            my ($id) = @_;
            if ($dbh->err == 1366 and $dbh->state eq "HY000") {
                warn "Attachment $id cannot be indexed. Most probably it contains invalid UTF8 bytes. ".
                    "Error: ". $dbh->errstr;
            } else {
                die "Attachment $id cannot be indexed: " . $dbh->errstr;
            }
        }
    );
}


sub process_pg {
    if ( $fts_config->{'Table'} ne 'Attachments' ) {
        process_pg_insert();
    } else {
        process_pg_update();
    }
}

sub process_pg_insert {
    my $dbh = $RT::Handle->dbh;
    my $table = $fts_config->{'Table'};
    my $column = $fts_config->{'Column'};
    ($LAST) = $dbh->selectrow_array("SELECT MAX(id) FROM $table");

    process_bulk_insert(
        sub {
            my ($n) = @_;
            return "INSERT INTO $table($column, id) VALUES "
                . join(", ", ("(TO_TSVECTOR(?),?)") x $n);
        },
        sub {
            my ($id) = @_;
            if ( $dbh->err == 7 && $dbh->state eq '54000' ) {
                warn "Attachment $id cannot be indexed. Most probably it contains too many unique words. ".
                  "Error: ". $dbh->errstr;
            } elsif ( $dbh->err == 7 && $dbh->state eq '22021' ) {
                warn "Attachment $id cannot be indexed. Most probably it contains invalid UTF8 bytes. ".
                  "Error: ". $dbh->errstr;
            } else {
                die "Attachment $id cannot be indexed: " . $dbh->errstr;
            }
        }
    );
}

sub process_pg_update {
    my $dbh = $RT::Handle->dbh;
    my $column = $fts_config->{'Column'};

    ($LAST) = $dbh->selectrow_array("SELECT MAX(id) FROM Attachments WHERE $column IS NOT NULL");

    my $sth = $dbh->prepare("UPDATE Attachments SET $column = TO_TSVECTOR(?) WHERE id = ?");

    attachment_loop( sub {
        my ($attachments) = @_;
        my @insert;

        while ( my $a = $attachments->Next ) {
            debug("Found attachment #". $a->id );

            if ( $max_size and $a->ContentLength > $max_size ){
                debug("Attachment #" . $a->id . " is " . $a->ContentLength .
                      " bytes which is larger than configured MaxFulltextAttachmentSize " .
                      " of " . $max_size . ", skipping");
                next;
            }

            my $text = $a->Content // "";
            HTML::Entities::decode_entities($text) if $a->ContentType eq "text/html";

            push @insert, [$text, $a->id];
        }

        # Try in one database transaction; if it fails, we roll it back
        # and try one statement at a time.
        $dbh->begin_work;
        my $ok = 1;
        for (@insert) {
            $ok = eval { $sth->execute( $_->[0], $_->[1] ) };
            last unless $ok;
        }
        if ($ok) {
            $dbh->commit;
            return;
        }
        $dbh->rollback;

        # Things didn't go well.  Retry the UPDATE statements one row at
        # a time, outside of the transaction.
        for (@insert) {
            my ($content, $id) = ($_->[0], $_->[1]);
            next if eval { $sth->execute( $content, $id ) };
            if ( $dbh->err == 7  && $dbh->state eq '54000' ) {
                warn "Attachment $id cannot be indexed. Most probably it contains too many unique words. ".
                  "Error: ". $dbh->errstr;
            } elsif ( $dbh->err == 7 && $dbh->state eq '22021' ) {
                warn "Attachment $id cannot be indexed. Most probably it contains invalid UTF8 bytes. ".
                  "Error: ". $dbh->errstr;
            } else {
                die "Attachment $id cannot be indexed: " . $dbh->errstr;
            }

            # If this was a semi-expected error, insert an empty
            # tsvector, so we count this row as "indexed" for
            # purposes of knowing where to pick up
            eval { $sth->execute( "", $id ) }
                or die "Failed to insert empty row for attachment $id: " . $dbh->errstr;
        }
    });
}


# helper functions
sub debug    { print @_, "\n" if $OPT{debug}; 1 }
sub error    { $RT::Logger->error(_(@_)); 1 }
sub warning  { $RT::Logger->warn(_(@_)); 1 }

=head1 NAME

rt-fulltext-indexer - Indexer for full text search

=head1 DESCRIPTION

This is a helper script to keep full text indexes in sync with data.
Read F<docs/full_text_indexing.pod> for complete details on how and when
to run it.

=cut

__DATA__