Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / rt / sbin / rt-importer.in
1 #!@PERL@
2 # BEGIN BPS TAGGED BLOCK {{{
3 #
4 # COPYRIGHT:
5 #
6 # This software is Copyright (c) 1996-2015 Best Practical Solutions, LLC
7 #                                          <sales@bestpractical.com>
8 #
9 # (Except where explicitly superseded by other copyright notices)
10 #
11 #
12 # LICENSE:
13 #
14 # This work is made available to you under the terms of Version 2 of
15 # the GNU General Public License. A copy of that license should have
16 # been provided with this software, but in any event can be snarfed
17 # from www.gnu.org.
18 #
19 # This work is distributed in the hope that it will be useful, but
20 # WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22 # General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
27 # 02110-1301 or visit their web page on the internet at
28 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
29 #
30 #
31 # CONTRIBUTION SUBMISSION POLICY:
32 #
33 # (The following paragraph is not intended to limit the rights granted
34 # to you to modify and distribute this software under the terms of
35 # the GNU General Public License and is only of importance to you if
36 # you choose to contribute your changes and enhancements to the
37 # community by submitting them to Best Practical Solutions, LLC.)
38 #
39 # By intentionally submitting any modifications, corrections or
40 # derivatives to this work, or any other work intended for use with
41 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
42 # you are the copyright holder for those contributions and you grant
43 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
44 # royalty-free, perpetual, license to use, copy, create derivative
45 # works based on those contributions, and sublicense and distribute
46 # those contributions and any derivatives thereof.
47 #
48 # END BPS TAGGED BLOCK }}}
49 use strict;
50 use warnings;
51
52 # fix lib paths, some may be relative
53 BEGIN {
54     require File::Spec;
55     my @libs = ("@RT_LIB_PATH@", "@LOCAL_LIB_PATH@");
56     my $bin_path;
57
58     for my $lib (@libs) {
59         unless ( File::Spec->file_name_is_absolute($lib) ) {
60             unless ($bin_path) {
61                 if ( File::Spec->file_name_is_absolute(__FILE__) ) {
62                     $bin_path = ( File::Spec->splitpath(__FILE__) )[1];
63                 }
64                 else {
65                     require FindBin;
66                     no warnings "once";
67                     $bin_path = $FindBin::Bin;
68                 }
69             }
70             $lib = File::Spec->catfile( $bin_path, File::Spec->updir, $lib );
71         }
72         unshift @INC, $lib;
73     }
74
75 }
76
77 use RT;
78 RT::LoadConfig();
79 RT::Init();
80
81 @RT::Record::ISA = qw( DBIx::SearchBuilder::Record RT::Base );
82
83 use RT::Migrate;
84 use RT::Migrate::Importer::File;
85 use Getopt::Long;
86 use Pod::Usage qw//;
87 use Time::HiRes qw//;
88
89 my %OPT = (resume => 1);
90 GetOptions(
91     \%OPT,
92     "help|?",
93     "quiet|q!",
94     "list|l!",
95
96     "resume!",
97     "originalid|i=s",
98
99     "ask",
100     "ignore-errors",
101
102     "dump=s@",
103 ) or Pod::Usage::pod2usage();
104
105 Pod::Usage::pod2usage(-verbose => 1) if $OPT{help};
106
107 Pod::Usage::pod2usage() unless @ARGV == 1;
108 my ($dir) = @ARGV;
109 $dir =~ s|/$||;
110 die "No such directory $dir\n" unless -d $dir;
111 die "$dir doesn't appear to contain serialized data\n"
112     unless -f "$dir/001.dat";
113
114 if ($OPT{dump}) {
115     die "Dumping objects only works in conjunction with --list\n"
116         unless $OPT{list};
117
118     $OPT{dump} = [ split /,/, join(',', @{$OPT{dump}}) ];
119 }
120
121 my $error_handler;
122 if ($OPT{ask}) {
123     die "Interactive mode (--ask) doesn't work when STDERR and STDIN aren't terminals.\n"
124         unless -t STDERR and -t STDIN;
125
126     $error_handler = sub {
127         my $importer = shift;
128         local $| = 1;
129         print STDERR "\n", @_, "\n";
130         print STDERR "Hit any key to abort import, or type 'ignore' to continue anyway.\n";
131         print STDERR "Continuing may leave you with a corrupt database. > ";
132         chomp( my $resp = <STDIN> );
133         return lc($resp) eq 'ignore';
134     };
135 }
136 elsif ($OPT{'ignore-errors'}) {
137     $error_handler = sub {
138         my $importer = shift;
139         warn "Ignoring error: ", @_;
140         return 1;
141     };
142 }
143
144 my $import = RT::Migrate::Importer::File->new(
145     Directory   => $dir,
146     OriginalId  => $OPT{originalid},
147     DumpObjects => $OPT{dump},
148     Resume      => $OPT{resume},
149     HandleError => $error_handler,
150 );
151
152 if ($import->Metadata and -t STDOUT and not $OPT{quiet}) {
153     $import->Progress(
154         RT::Migrate::progress(
155             counts => sub { $import->ObjectCount },
156             max    => $import->Metadata->{ObjectCount},
157         )
158     );
159 }
160
161 my $log = RT::Migrate::setup_logging( $dir => 'importer.log' );
162 print "Logging warnings and errors to $log\n" if $log;
163
164 my %counts;
165 if ($OPT{list}) {
166     %counts = $import->List;
167
168     my $org = $import->Organization;
169     print "=========== Dump of $org ===========\n\n";
170 } else {
171     %counts = $import->Import;
172
173     my $org = $import->Organization;
174     print "========== Import of $org ==========\n\n";
175 }
176
177 print "Total object counts:\n";
178 for (sort {$counts{$b} <=> $counts{$a}} keys %counts) {
179     printf "%8d %s\n", $counts{$_}, $_;
180 }
181
182 my @missing = $import->Missing;
183 if (@missing) {
184     warn "The following UIDs were expected but never observed:\n";
185     warn "    $_\n" for @missing;
186 }
187
188 my @invalid = $import->Invalid;
189 if (@invalid) {
190     warn "The following UIDs (serialized => imported) referred to objects missing from the original database:\n";
191     for my $info (@invalid) {
192         my $uid = delete $info->{uid};
193         my $obj = $import->LookupObj($uid);
194         warn sprintf "    %s => %s (%s)\n",
195                 $uid,
196                 ($obj && $obj->Id ? $obj->UID : '(not imported)'),
197                 join(", ", map  { "$_ => $info->{$_}" }
198                            grep { defined $info->{$_} }
199                                 sort keys %$info);
200     }
201 }
202
203 if ($log and -s $log) {
204     print STDERR "\n! Some warnings or errors occurred during import."
205                 ."\n! Please see $log for details.\n\n";
206 }
207
208 exit @missing;
209
210 =head1 NAME
211
212 rt-importer - Import a serialized RT database on top of the current one
213
214 =head1 SYNOPSIS
215
216     rt-importer path/to/export/directory
217
218 This script is used to import the contents of a dump created by
219 C<rt-serializer>.  It will create all of the objects in the dump in the
220 current database; this may include users, queues, and tickets.
221
222 It is possible to stop the import process with ^C; it can be later
223 resumed by re-running the importer.
224
225 =head2 OPTIONS
226
227 =over
228
229 =item B<--list>
230
231 Print a summary of the data contained in the dump.
232
233 =item B<--originalid> I<cfname>
234
235 Places the original ticket organization and ID into a global custom
236 field with the given name.  If no global ticket custom field with that
237 name is found in the current database, it will create one.
238
239 =item B<--ask>
240
241 Prompt for action when an error occurs inserting a record into the
242 database.  This can often happen when importing data from very old RTs
243 where some attachments (usually spam) contain invalid UTF-8.
244
245 The importer will pause and ask if you want to ignore the error and
246 continue on or abort (potentially to restart later).  Ignoring errors
247 will result in missing records in the database, which may cause database
248 integrity problems later.  If you ignored any errors, you should run
249 C<rt-validator> after import.
250
251 =item B<--ignore-errors>
252
253 Ignore all record creation errors and continue on when importing.  This
254 is equivalent to running with C<--ask> and manually typing "ignore" at
255 every prompt.  You should always run C<rt-validator> after importing
256 with errors ignored.
257
258 B<This option can be dangerous and leave you with a broken RT!>
259
260 =item B<--dump> I<class>[,I<class>]
261
262 Prints L<Data::Dumper> representations of the objects of type I<class> in the
263 serialized data.  This is mostly useful for debugging.
264
265 Works only in conjunction with C<--list>.
266
267 =back
268
269
270 =head1 CLONED DATA
271
272 Some dumps may have been taken as complete clones of the RT system,
273 which are only suitable for inserting into a schema with no data in it.
274 You can setup the required database state for the receiving RT instance
275 by running:
276
277     @RT_SBIN_PATH_R@/rt-setup-database --action create,schema,acl --prompt-for-dba-password
278
279 The normal C<make initdb> step will B<not> work because it also inserts
280 core system data.
281
282
283 =cut