This repository has been archived by the owner on Jul 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 587
/
SqoopOptions.java
2668 lines (2236 loc) · 76.3 KB
/
SqoopOptions.java
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sqoop;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.sqoop.accumulo.AccumuloConstants;
import org.apache.sqoop.mapreduce.mainframe.MainframeConfiguration;
import org.apache.sqoop.util.CredentialsUtil;
import org.apache.sqoop.util.LoggingUtils;
import org.apache.sqoop.util.SqoopJsonUtil;
import org.apache.sqoop.util.password.CredentialProviderHelper;
import org.apache.sqoop.validation.AbortOnFailureHandler;
import org.apache.sqoop.validation.AbsoluteValidationThreshold;
import org.apache.sqoop.validation.RowCountValidator;
import com.cloudera.sqoop.SqoopOptions.FileLayout;
import com.cloudera.sqoop.SqoopOptions.IncrementalMode;
import com.cloudera.sqoop.SqoopOptions.UpdateMode;
import com.cloudera.sqoop.lib.DelimiterSet;
import com.cloudera.sqoop.lib.LargeObjectLoader;
import com.cloudera.sqoop.tool.SqoopTool;
import com.cloudera.sqoop.util.RandomHash;
import com.cloudera.sqoop.util.StoredAsProperty;
/**
* Configurable state used by Sqoop tools.
*/
public class SqoopOptions implements Cloneable {
private static final String OLD_SQOOP_TEST_IMPORT_ROOT_DIR = "sqoop.test.import.rootDir";
public static final Log LOG = LogFactory.getLog(SqoopOptions.class.getName());
/**
* Set to true in configuration if you want to put db passwords
* in the metastore.
*/
public static final String METASTORE_PASSWORD_KEY =
"sqoop.metastore.client.record.password";
// Default hive and hcat locations.
public static final String DEF_HIVE_HOME = "/usr/lib/hive";
public static final String DEF_HCAT_HOME = "/usr/lib/hive-hcatalog";
public static final String DEF_HCAT_HOME_OLD = "/usr/lib/hcatalog";
public static final boolean METASTORE_PASSWORD_DEFAULT = false;
/**
* Thrown when invalid cmdline options are given.
*/
@SuppressWarnings("serial")
public static class InvalidOptionsException extends Exception {
private String message;
public InvalidOptionsException(final String msg) {
this.message = msg;
}
public String getMessage() {
return message;
}
public String toString() {
return getMessage();
}
}
@StoredAsProperty("customtool.options.jsonmap")
private Map<String, String> customToolOptions;
// TODO(aaron): Adding something here? Add a setter and a getter. Add a
// default value in initDefaults() if you need one. If this value needs to
// be serialized in the metastore, it should be marked with
// @StoredAsProperty(), if it is an int, long, boolean, String, or Enum.
// Arrays and other "special" types should be added directly to the
// loadProperties() and writeProperties() methods. Then add command-line
// arguments in the appropriate tools. The names of all command-line args
// are stored as constants in BaseSqoopTool.
@StoredAsProperty("verbose") private boolean verbose;
@StoredAsProperty("temporary.dirRoot") private String tempRootDir;
@StoredAsProperty("mapreduce.job.name") private String mapreduceJobName;
@StoredAsProperty("db.connect.string") private String connectString;
@StoredAsProperty("db.table") private String tableName;
private String [] columns; // Array stored as db.column.list.
@StoredAsProperty("db.username") private String username;
@StoredAsProperty("db.export.staging.table") private String stagingTableName;
@StoredAsProperty("db.clear.staging.table") private boolean clearStagingTable;
@StoredAsProperty("db.export.call") private String call;
private Properties connectionParams; //Properties stored as db.connect.params
// May not be serialized, based on configuration.
// db.require.password is used to determine whether 'some' password is
// used. If so, it is stored as 'db.password'.
private String password;
// This represents path to a file on ${user.home} containing the password
// with 400 permissions so its only readable by user executing the tool
@StoredAsProperty("db.password.file") private String passwordFilePath;
@StoredAsProperty("db.password.alias") private String passwordAlias;
@StoredAsProperty("null.string") private String nullStringValue;
@StoredAsProperty("input.null.string") private String inNullStringValue;
@StoredAsProperty("null.non-string") private String nullNonStringValue;
@StoredAsProperty("input.null.non-string")
private String inNullNonStringValue;
@StoredAsProperty("codegen.output.dir") private String codeOutputDir;
@StoredAsProperty("codegen.compile.dir") private String jarOutputDir;
// Boolean specifying whether jarOutputDir is a nonce tmpdir (true), or
// explicitly set by the user (false). If the former, disregard any value
// for jarOutputDir saved in the metastore.
@StoredAsProperty("codegen.auto.compile.dir") private boolean jarDirIsAuto;
private String hadoopMapRedHome; // not serialized to metastore.
@StoredAsProperty("db.split.column") private String splitByCol;
@StoredAsProperty("split.limit") private Integer splitLimit;
@StoredAsProperty("db.where.clause") private String whereClause;
@StoredAsProperty("db.query") private String sqlQuery;
@StoredAsProperty("db.query.boundary") private String boundaryQuery;
@StoredAsProperty("jdbc.driver.class") private String driverClassName;
@StoredAsProperty("hdfs.warehouse.dir") private String warehouseDir;
@StoredAsProperty("hdfs.target.dir") private String targetDir;
@StoredAsProperty("hdfs.append.dir") private boolean append;
@StoredAsProperty("hdfs.delete-target.dir") private boolean delete;
@StoredAsProperty("hdfs.file.format") private FileLayout layout;
@StoredAsProperty("direct.import") private boolean direct; // "direct mode."
@StoredAsProperty("db.batch") private boolean batchMode;
private String tmpDir; // where temp data goes; usually /tmp; not serialized.
private String hiveHome; // not serialized to metastore.
@StoredAsProperty("hive.import") private boolean hiveImport;
@StoredAsProperty("hive.overwrite.table") private boolean overwriteHiveTable;
@StoredAsProperty("hive.fail.table.exists")
private boolean failIfHiveTableExists;
@StoredAsProperty("hive.table.name") private String hiveTableName;
@StoredAsProperty("hive.database.name") private String hiveDatabaseName;
@StoredAsProperty("hive.drop.delims") private boolean hiveDropDelims;
@StoredAsProperty("hive.delims.replacement")
private String hiveDelimsReplacement;
@StoredAsProperty("hive.partition.key") private String hivePartitionKey;
@StoredAsProperty("hive.partition.value") private String hivePartitionValue;
@StoredAsProperty("hcatalog.table.name")
private String hCatTableName;
@StoredAsProperty("hcatalog.database.name")
private String hCatDatabaseName;
@StoredAsProperty("hcatalog.create.table")
private boolean hCatCreateTable;
@StoredAsProperty("hcatalog.drop.and.create.table")
private boolean hCatDropAndCreateTable;
@StoredAsProperty("hcatalog.storage.stanza")
private String hCatStorageStanza;
private String hCatHome; // not serialized to metastore.
private boolean skipDistCache;
@StoredAsProperty("hcatalog.partition.keys")
private String hCatalogPartitionKeys;
@StoredAsProperty("hcatalog.partition.values")
private String hCatalogPartitionValues;
// User explicit mapping of types
private Properties mapColumnJava; // stored as map.colum.java
private Properties mapColumnHive; // stored as map.column.hive
// An ordered list of column names denoting what order columns are
// serialized to a PreparedStatement from a generated record type.
// Not serialized to metastore.
private String [] dbOutColumns;
// package to prepend to auto-named classes.
@StoredAsProperty("codegen.java.packagename") private String packageName;
// package+class to apply to individual table import.
// also used as an *input* class with existingJarFile.
@StoredAsProperty("codegen.java.classname") private String className;
// Name of a jar containing existing table definition
// class to use.
@StoredAsProperty("codegen.jar.file") private String existingJarFile;
@StoredAsProperty("mapreduce.num.mappers") private int numMappers;
@StoredAsProperty("enable.compression") private boolean useCompression;
@StoredAsProperty("compression.codec") private String compressionCodec;
// In direct mode, open a new stream every X bytes.
@StoredAsProperty("import.direct.split.size") private long directSplitSize;
// Max size of an inline LOB; larger LOBs are written
// to external files on disk.
@StoredAsProperty("import.max.inline.lob.size") private long maxInlineLobSize;
// Max number 'n' of rows to fetch from the
// database when more rows are needed.
@StoredAsProperty("import.fetch.size") private Integer fetchSize;
// HDFS path to read from when performing an export
@StoredAsProperty("export.source.dir") private String exportDir;
// Column to use for the WHERE clause in an UPDATE-based export.
@StoredAsProperty("export.update.col") private String updateKeyCol;
@StoredAsProperty("export.new.update") private UpdateMode updateMode;
private DelimiterSet inputDelimiters; // codegen.input.delimiters.
private DelimiterSet outputDelimiters; // codegen.output.delimiters.
private boolean areOutputDelimsManuallySet;
private boolean areInputDelimsManuallySet;
private Configuration conf;
private String toolName;
public static final int DEFAULT_NUM_MAPPERS = 4;
private String [] extraArgs;
// HBase table to import into.
@StoredAsProperty("hbase.table") private String hbaseTable;
// Column family to prepend to inserted cols.
@StoredAsProperty("hbase.col.family") private String hbaseColFamily;
// Column of the input to use as the row key.
@StoredAsProperty("hbase.row.key.col") private String hbaseRowKeyCol;
// if true, bulk loading will be used.
@StoredAsProperty("hbase.bulk.load.enabled") private boolean hbaseBulkLoadEnabled;
// if true, create tables/col families.
@StoredAsProperty("hbase.create.table") private boolean hbaseCreateTable;
// col to filter on for incremental imports.
@StoredAsProperty("incremental.col") private String incrementalTestCol;
// incremental import mode we're using.
@StoredAsProperty("incremental.mode")
private IncrementalMode incrementalMode;
// What was the last-imported value of incrementalTestCol?
@StoredAsProperty("incremental.last.value")
private String incrementalLastValue;
// exclude these tables when importing all tables.
@StoredAsProperty("import.all_tables.exclude")
private String allTablesExclude;
// HDFS paths for "old" and "new" datasets in merge tool.
@StoredAsProperty("merge.old.path") private String mergeOldPath;
@StoredAsProperty("merge.new.path") private String mergeNewPath;
// "key" column for the merge operation.
@StoredAsProperty("merge.key.col") private String mergeKeyCol;
// Dataset name for mainframe import tool
@StoredAsProperty("mainframe.input.dataset.name")
private String mainframeInputDatasetName;
// Dataset type for mainframe import tool
@StoredAsProperty("mainframe.input.dataset.type")
private String mainframeInputDatasetType;
// Indicates if the data set is on tape to use different FTP parser
@StoredAsProperty("mainframe.input.dataset.tape")
private String mainframeInputDatasetTape;
// Accumulo home directory
private String accumuloHome; // not serialized to metastore.
// Zookeeper home directory
private String zookeeperHome; // not serialized to metastore.
// Accumulo table to import into.
@StoredAsProperty("accumulo.table") private String accumuloTable;
// Column family to prepend to inserted cols.
@StoredAsProperty("accumulo.col.family") private String accumuloColFamily;
// Column of the input to use as the row key.
@StoredAsProperty("accumulo.row.key.col") private String accumuloRowKeyCol;
//
// Visibility token to be applied to each row imported.
@StoredAsProperty("accumulo.visibility") private String accumuloVisibility;
// Size of the write buffer.
@StoredAsProperty("accumulo.batch.size")
private long accumuloBatchSize;
// Maximum latency for batch writer.
@StoredAsProperty("accumulo.max.latency")
private long accumuloMaxLatency;
// if true, create table.
@StoredAsProperty("accumulo.create.table")
private boolean accumuloCreateTable;
// Accumulo user name
@StoredAsProperty("accumulo.user") private String accumuloUser;
// Accumulo password
@StoredAsProperty("accumulo.password") private String accumuloPassword;
// Accumulo instance
@StoredAsProperty("accumulo.instance") private String accumuloInstance;
// Accumulo zookeeper
@StoredAsProperty("accumulo.zookeepers") private String accumuloZookeepers;
// Relaxed Isolation
@StoredAsProperty("relaxed.isolation") private boolean relaxedIsolation;
// Use single mapper for non-primary key tables without
// explicit split by cols
@StoredAsProperty("reset.onemapper") private boolean autoResetToOneMapper;
// These next two fields are not serialized to the metastore.
// If this SqoopOptions is created by reading a saved job, these will
// be populated by the JobStorage to facilitate updating the same
// job.
private String jobName;
private Map<String, String> jobStorageDescriptor;
// If we restore a job and then allow the user to apply arguments on
// top, we retain the version without the arguments in a reference to the
// 'parent' SqoopOptions instance, here.
private com.cloudera.sqoop.SqoopOptions parent;
// Nonce directory name. Generate one per process, lazily, if
// getNonceJarDir() is called. Not recorded in metadata. This is used as
// a temporary holding area for compilation work done by this process.
private static String curNonce;
// the connection manager fully qualified class name
@StoredAsProperty("connection.manager") private String connManagerClassName;
// The currently active tool. (Not saved in properties)
// Used to pass the SqoopTool instance in to mapreduce job configuration
// (JobBase, etc).
private SqoopTool activeSqoopTool;
// Flag to determine if data copied needs to be validated against the source
private boolean isValidationEnabled;
// These take FQCN as input, convert them to Class in light of failing early
private Class validatorClass; // Class for the validator implementation.
private Class validationThresholdClass; // ValidationThreshold implementation
private Class validationFailureHandlerClass; // FailureHandler implementation
public SqoopOptions() {
initDefaults(null);
}
public SqoopOptions(Configuration conf) {
initDefaults(conf);
}
/**
* Alternate SqoopOptions interface used mostly for unit testing.
* @param connect JDBC connect string to use
* @param table Table to read
*/
public SqoopOptions(final String connect, final String table) {
initDefaults(null);
this.connectString = connect;
this.tableName = table;
}
private boolean getBooleanProperty(Properties props, String propName,
boolean defaultValue) {
String str = props.getProperty(propName,
Boolean.toString(defaultValue)).toLowerCase();
return "true".equals(str) || "yes".equals(str) || "1".equals(str);
}
private long getLongProperty(Properties props, String propName,
long defaultValue) {
String str = props.getProperty(propName,
Long.toString(defaultValue)).toLowerCase();
try {
return Long.parseLong(str);
} catch (NumberFormatException nfe) {
LOG.warn("Could not parse integer value for config parameter "
+ propName);
return defaultValue;
}
}
private int getIntProperty(Properties props, String propName,
int defaultVal) {
long longVal = getLongProperty(props, propName, defaultVal);
return (int) longVal;
}
private char getCharProperty(Properties props, String propName,
char defaultVal) {
int intVal = getIntProperty(props, propName, (int) defaultVal);
return (char) intVal;
}
private DelimiterSet getDelimiterProperties(Properties props,
String prefix, DelimiterSet defaults) {
if (null == defaults) {
defaults = new DelimiterSet();
}
char field = getCharProperty(props, prefix + ".field",
defaults.getFieldsTerminatedBy());
char record = getCharProperty(props, prefix + ".record",
defaults.getLinesTerminatedBy());
char enclose = getCharProperty(props, prefix + ".enclose",
defaults.getEnclosedBy());
char escape = getCharProperty(props, prefix + ".escape",
defaults.getEscapedBy());
boolean required = getBooleanProperty(props, prefix +".enclose.required",
defaults.isEncloseRequired());
return new DelimiterSet(field, record, enclose, escape, required);
}
private void setDelimiterProperties(Properties props,
String prefix, DelimiterSet values) {
putProperty(props, prefix + ".field",
Integer.toString((int) values.getFieldsTerminatedBy()));
putProperty(props, prefix + ".record",
Integer.toString((int) values.getLinesTerminatedBy()));
putProperty(props, prefix + ".enclose",
Integer.toString((int) values.getEnclosedBy()));
putProperty(props, prefix + ".escape",
Integer.toString((int) values.getEscapedBy()));
putProperty(props, prefix + ".enclose.required",
Boolean.toString(values.isEncloseRequired()));
}
/** Take a comma-delimited list of input and split the elements
* into an output array. */
private String [] listToArray(String strList) {
return strList.split(",");
}
private String arrayToList(String [] array) {
if (null == array) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String elem : array) {
if (!first) {
sb.append(",");
}
sb.append(elem);
first = false;
}
return sb.toString();
}
/**
* A put() method for Properties that is tolerent of 'null' values.
* If a null value is specified, the property is unset.
*/
private void putProperty(Properties props, String k, String v) {
if (null == v) {
props.remove(k);
} else {
props.setProperty(k, v);
}
}
/**
* Given a property prefix that denotes a set of numbered properties,
* return an array containing all the properties.
*
* For instance, if prefix is "foo", then return properties "foo.0",
* "foo.1", "foo.2", and so on as an array. If no such properties
* exist, return 'defaults'.
*/
private String [] getArgArrayProperty(Properties props, String prefix,
String [] defaults) {
int cur = 0;
ArrayList<String> al = new ArrayList<String>();
while (true) {
String curProp = prefix + "." + cur;
String curStr = props.getProperty(curProp, null);
if (null == curStr) {
break;
}
al.add(curStr);
cur++;
}
if (cur == 0) {
// Couldn't find an array here; return the defaults.
return defaults;
}
return al.toArray(new String[0]);
}
private void setArgArrayProperties(Properties props, String prefix,
String [] values) {
if (null == values) {
return;
}
for (int i = 0; i < values.length; i++) {
putProperty(props, prefix + "." + i, values[i]);
}
}
/**
* This method encodes the property key values found in the provided
* properties instance <tt>values</tt> into another properties instance
* <tt>props</tt>. The specified <tt>prefix</tt> is used as a namespace
* qualifier for keys when inserting. This allows easy introspection of the
* property key values in <tt>props</tt> instance to later separate out all
* the properties that belong to the <tt>values</tt> instance.
* @param props the container properties instance
* @param prefix the prefix for qualifying contained property keys.
* @param values the contained properties instance, all of whose elements will
* be added to the container properties instance.
*
* @see #getPropertiesAsNetstedProperties(Properties, String)
*/
private void setPropertiesAsNestedProperties(Properties props,
String prefix, Properties values) {
String nestedPropertyPrefix = prefix + ".";
if (null == values || values.size() == 0) {
Iterator<String> it = props.stringPropertyNames().iterator();
while (it.hasNext()) {
String name = it.next();
if (name.startsWith(nestedPropertyPrefix)) {
props.remove(name);
}
}
} else {
Iterator<String> it = values.stringPropertyNames().iterator();
while (it.hasNext()) {
String name = it.next();
putProperty(props,
nestedPropertyPrefix + name, values.getProperty(name));
}
}
}
/**
* This method decodes the property key values found in the provided
* properties instance <tt>props</tt> that have keys beginning with the
* given prefix. Matching elements from this properties instance are modified
* so that their prefix is dropped.
* @param props the properties container
* @param prefix the prefix qualifying properties that need to be removed
* @return a new properties instance that contains all matching elements from
* the container properties.
*/
private Properties getPropertiesAsNetstedProperties(
Properties props, String prefix) {
Properties nestedProps = new Properties();
String nestedPropertyPrefix = prefix + ".";
int index = nestedPropertyPrefix.length();
if (props != null && props.size() > 0) {
Iterator<String> it = props.stringPropertyNames().iterator();
while (it.hasNext()) {
String name = it.next();
if (name.startsWith(nestedPropertyPrefix)){
String shortName = name.substring(index);
nestedProps.put(shortName, props.get(name));
}
}
}
return nestedProps;
}
@SuppressWarnings("unchecked")
/**
* Given a set of properties, load this into the current SqoopOptions
* instance.
*/
public void loadProperties(Properties props) {
try {
Field [] fields = SqoopOptions.class.getDeclaredFields();
for (Field f : fields) {
if (f.isAnnotationPresent(StoredAsProperty.class)) {
Class typ = f.getType();
StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
String propName = storedAs.value();
if (typ.equals(int.class)) {
f.setInt(this,
getIntProperty(props, propName, f.getInt(this)));
} else if (typ.equals(boolean.class)) {
f.setBoolean(this,
getBooleanProperty(props, propName, f.getBoolean(this)));
} else if (typ.equals(long.class)) {
f.setLong(this,
getLongProperty(props, propName, f.getLong(this)));
} else if (typ.equals(String.class)) {
f.set(this, props.getProperty(propName, (String) f.get(this)));
} else if (typ.equals(Integer.class)) {
String value = props.getProperty(
propName,
f.get(this) == null ? "null" : f.get(this).toString());
f.set(this, value.equals("null") ? null : new Integer(value));
} else if (typ.isEnum()) {
f.set(this, Enum.valueOf(typ,
props.getProperty(propName, f.get(this).toString())));
} else if (typ.equals(Map.class)) {
f.set(this,
SqoopJsonUtil.getMapforJsonString(props.getProperty(propName)));
} else {
throw new RuntimeException("Could not retrieve property "
+ propName + " for type: " + typ);
}
}
}
} catch (IllegalAccessException iae) {
throw new RuntimeException("Illegal access to field in property setter",
iae);
}
// Now load properties that were stored with special types, or require
// additional logic to set.
loadPasswordProperty(props);
if (this.jarDirIsAuto) {
// We memoized a user-specific nonce dir for compilation to the data
// store. Disregard that setting and create a new nonce dir.
String localUsername = System.getProperty("user.name", "unknown");
this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername
+ "/compile");
}
String colListStr = props.getProperty("db.column.list", null);
if (null != colListStr) {
this.columns = listToArray(colListStr);
}
this.inputDelimiters = getDelimiterProperties(props,
"codegen.input.delimiters", this.inputDelimiters);
this.outputDelimiters = getDelimiterProperties(props,
"codegen.output.delimiters", this.outputDelimiters);
this.extraArgs = getArgArrayProperty(props, "tool.arguments",
this.extraArgs);
this.connectionParams =
getPropertiesAsNetstedProperties(props, "db.connect.params");
// Loading user mapping
this.mapColumnHive =
getPropertiesAsNetstedProperties(props, "map.column.hive");
this.mapColumnJava =
getPropertiesAsNetstedProperties(props, "map.column.java");
// Delimiters were previously memoized; don't let the tool override
// them with defaults.
this.areOutputDelimsManuallySet = true;
this.areInputDelimsManuallySet = true;
// If we loaded true verbose flag, we need to apply it
if (this.verbose) {
LoggingUtils.setDebugLevel();
}
}
private void loadPasswordProperty(Properties props) {
passwordFilePath = props.getProperty("db.password.file");
if (passwordFilePath != null) {
try {
password = CredentialsUtil.fetchPasswordFromLoader(passwordFilePath, getConf());
return; // short-circuit
} catch (IOException e) {
throw new RuntimeException("Unable to fetch password from file.", e);
}
}
passwordAlias = props.getProperty("db.password.alias");
if (passwordAlias != null) {
try {
setPassword(CredentialProviderHelper.resolveAlias(getConf(), passwordAlias));
return; // short-circuit
} catch (IOException e) {
throw new RuntimeException("Unable to resolve credentials.", e);
}
}
if (getBooleanProperty(props, "db.require.password", false)) {
// The user's password was stripped out from the metastore.
// Require that the user enter it now.
setPasswordFromConsole();
} else {
this.password = props.getProperty("db.password", this.password);
}
}
/**
* Return a Properties instance that encapsulates all the "sticky"
* state of this SqoopOptions that should be written to a metastore
* to restore the job later.
*/
public Properties writeProperties() {
Properties props = new Properties();
try {
Field [] fields = SqoopOptions.class.getDeclaredFields();
for (Field f : fields) {
if (f.isAnnotationPresent(StoredAsProperty.class)) {
Class typ = f.getType();
StoredAsProperty storedAs = f.getAnnotation(StoredAsProperty.class);
String propName = storedAs.value();
if (typ.equals(int.class)) {
putProperty(props, propName, Integer.toString(f.getInt(this)));
} else if (typ.equals(boolean.class)) {
putProperty(props, propName, Boolean.toString(f.getBoolean(this)));
} else if (typ.equals(long.class)) {
putProperty(props, propName, Long.toString(f.getLong(this)));
} else if (typ.equals(String.class)) {
putProperty(props, propName, (String) f.get(this));
} else if (typ.equals(Integer.class)) {
putProperty(
props,
propName,
f.get(this) == null ? "null" : f.get(this).toString());
} else if (typ.isEnum()) {
putProperty(props, propName, f.get(this).toString());
} else if (typ.equals(Map.class)) {
putProperty(
props,
propName,
SqoopJsonUtil.getJsonStringforMap((Map) f.get(this)));
} else {
throw new RuntimeException("Could not set property "
+ propName + " for type: " + typ);
}
}
}
} catch (IllegalAccessException iae) {
throw new RuntimeException("Illegal access to field in property setter",
iae);
}
writePasswordProperty(props);
putProperty(props, "db.column.list", arrayToList(this.columns));
setDelimiterProperties(props, "codegen.input.delimiters",
this.inputDelimiters);
setDelimiterProperties(props, "codegen.output.delimiters",
this.outputDelimiters);
setArgArrayProperties(props, "tool.arguments", this.extraArgs);
setPropertiesAsNestedProperties(props,
"db.connect.params", this.connectionParams);
setPropertiesAsNestedProperties(props,
"map.column.hive", this.mapColumnHive);
setPropertiesAsNestedProperties(props,
"map.column.java", this.mapColumnJava);
return props;
}
private void writePasswordProperty(Properties props) {
if (getPasswordFilePath() != null) { // short-circuit
putProperty(props, "db.password.file", getPasswordFilePath());
return;
}
if (getPasswordAlias() != null) { // short-circuit
putProperty(props, "db.password.alias", getPasswordAlias());
return;
}
if (this.getConf().getBoolean(
METASTORE_PASSWORD_KEY, METASTORE_PASSWORD_DEFAULT)) {
// If the user specifies, we may store the password in the metastore.
putProperty(props, "db.password", this.password);
putProperty(props, "db.require.password", "false");
} else if (this.password != null) {
// Otherwise, if the user has set a password, we just record
// a flag stating that the password will need to be reentered.
putProperty(props, "db.require.password", "true");
} else {
// No password saved or required.
putProperty(props, "db.require.password", "false");
}
}
@Override
public Object clone() {
try {
SqoopOptions other = (SqoopOptions) super.clone();
if (null != columns) {
other.columns = Arrays.copyOf(columns, columns.length);
}
if (null != dbOutColumns) {
other.dbOutColumns = Arrays.copyOf(dbOutColumns, dbOutColumns.length);
}
if (null != inputDelimiters) {
other.inputDelimiters = (DelimiterSet) inputDelimiters.clone();
}
if (null != outputDelimiters) {
other.outputDelimiters = (DelimiterSet) outputDelimiters.clone();
}
if (null != conf) {
other.conf = new Configuration(conf);
}
if (null != extraArgs) {
other.extraArgs = Arrays.copyOf(extraArgs, extraArgs.length);
}
if (null != connectionParams) {
other.setConnectionParams(this.connectionParams);
}
if (null != mapColumnHive) {
other.mapColumnHive = (Properties) this.mapColumnHive.clone();
}
if (null != mapColumnJava) {
other.mapColumnJava = (Properties) this.mapColumnJava.clone();
}
return other;
} catch (CloneNotSupportedException cnse) {
// Shouldn't happen.
return null;
}
}
/**
* @return the temp directory to use; this is guaranteed to end with
* the file separator character (e.g., '/').
*/
public String getTempDir() {
return this.tmpDir;
}
/**
* Return the name of a directory that does not exist before
* calling this method, and does exist afterward. We should be
* the only client of this directory. If this directory is not
* used during the lifetime of the JVM, schedule it to be removed
* when the JVM exits.
*/
private static String getNonceJarDir(String tmpBase) {
// Make sure we don't loop forever in the event of a permission error.
final int MAX_DIR_CREATE_ATTEMPTS = 32;
if (null != curNonce) {
return curNonce;
}
File baseDir = new File(tmpBase);
File hashDir = null;
for (int attempts = 0; attempts < MAX_DIR_CREATE_ATTEMPTS; attempts++) {
hashDir = new File(baseDir, RandomHash.generateMD5String());
while (hashDir.exists()) {
hashDir = new File(baseDir, RandomHash.generateMD5String());
}
if (hashDir.mkdirs()) {
// We created the directory. Use it.
// If this directory is not actually filled with files, delete it
// when the JVM quits.
hashDir.deleteOnExit();
break;
}
}
if (hashDir == null || !hashDir.exists()) {
throw new RuntimeException("Could not create temporary directory: "
+ hashDir + "; check for a directory permissions issue on /tmp.");
}
LOG.debug("Generated nonce dir: " + hashDir.toString());
SqoopOptions.curNonce = hashDir.toString();
return SqoopOptions.curNonce;
}
/**
* Reset the nonce directory and force a new one to be generated. This
* method is intended to be used only by multiple unit tests that want
* to isolate themselves from one another. It should not be called
* during normal Sqoop execution.
*/
public static void clearNonceDir() {
LOG.warn("Clearing nonce directory");
SqoopOptions.curNonce = null;
}
public static String getHiveHomeDefault() {
// Set this with $HIVE_HOME, but -Dhive.home can override.
String hiveHome = System.getenv("HIVE_HOME");
hiveHome = System.getProperty("hive.home", hiveHome);
if (hiveHome == null) {
hiveHome = DEF_HIVE_HOME;
}
return hiveHome;
}
public static String getHCatHomeDefault() {
// Set this with $HCAT_HOME, but -Dhcatalog.home can override.
String hcatHome = System.getenv("HCAT_HOME");
hcatHome = System.getProperty("hcat.home", hcatHome);
if (hcatHome == null) {
File file = new File(DEF_HCAT_HOME);
if (file.exists()) {
hcatHome = DEF_HCAT_HOME;
} else {
hcatHome = DEF_HCAT_HOME_OLD;
}
}
return hcatHome;
}
private void initDefaults(Configuration baseConfiguration) {
// first, set the true defaults if nothing else happens.
// default action is to run the full pipeline.
this.hadoopMapRedHome = System.getenv("HADOOP_MAPRED_HOME");
this.accumuloHome = getAccumuloHomeDefault();
this.zookeeperHome = getZookeeperHomeDefault();
this.hiveHome = getHiveHomeDefault();
this.hCatHome = getHCatHomeDefault();
this.inputDelimiters = new DelimiterSet(
DelimiterSet.NULL_CHAR, DelimiterSet.NULL_CHAR,
DelimiterSet.NULL_CHAR, DelimiterSet.NULL_CHAR, false);
this.outputDelimiters = new DelimiterSet();
// Set this to cwd, but -Dsqoop.src.dir can override.
this.codeOutputDir = System.getProperty("sqoop.src.dir", ".");
String myTmpDir = System.getProperty("test.build.data", "/tmp/");
if (!myTmpDir.endsWith(File.separator)) {
myTmpDir = myTmpDir + File.separator;
}
this.tmpDir = myTmpDir;
String localUsername = System.getProperty("user.name", "unknown");
this.jarOutputDir = getNonceJarDir(tmpDir + "sqoop-" + localUsername
+ "/compile");
this.jarDirIsAuto = true;
this.layout = FileLayout.TextFile;
this.areOutputDelimsManuallySet = false;
this.areInputDelimsManuallySet = false;
this.numMappers = DEFAULT_NUM_MAPPERS;
this.useCompression = false;
this.compressionCodec = null;
this.directSplitSize = 0;
this.maxInlineLobSize = LargeObjectLoader.DEFAULT_MAX_LOB_LENGTH;
// Don't set a default value for fetchsize. This allows a JDBCManager to
// provide a database-specific default, if no value is provided by the
// user.
this.fetchSize = null;
if (null == baseConfiguration) {
this.conf = new Configuration();
} else {