/
Hadoop23Shims.java
1329 lines (1157 loc) · 43.3 KB
/
Hadoop23Shims.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.hadoop.hive.shims;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.security.AccessControlException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.crypto.key.KeyProvider;
import org.apache.hadoop.crypto.key.KeyProvider.Options;
import org.apache.hadoop.crypto.key.KeyProviderCryptoExtension;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.fs.DefaultFileAccess;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsShell;
import org.apache.hadoop.fs.LocatedFileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.PathFilter;
import org.apache.hadoop.fs.ProxyFileSystem;
import org.apache.hadoop.fs.RemoteIterator;
import org.apache.hadoop.fs.Trash;
import org.apache.hadoop.fs.TrashPolicy;
import org.apache.hadoop.fs.permission.AclEntry;
import org.apache.hadoop.fs.permission.AclEntryScope;
import org.apache.hadoop.fs.permission.AclEntryType;
import org.apache.hadoop.fs.permission.AclStatus;
import org.apache.hadoop.fs.permission.FsAction;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.protocol.BlockStoragePolicy;
import org.apache.hadoop.hdfs.protocol.HdfsConstants;
import org.apache.hadoop.hdfs.client.HdfsAdmin;
import org.apache.hadoop.hdfs.protocol.EncryptionZone;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapred.ClusterStatus;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MiniMRCluster;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.WebHCatJTShim23;
import org.apache.hadoop.mapred.lib.TotalOrderPartitioner;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.JobID;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.OutputFormat;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.mapreduce.TaskID;
import org.apache.hadoop.mapreduce.TaskType;
import org.apache.hadoop.mapreduce.task.JobContextImpl;
import org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.security.authentication.util.KerberosName;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.util.Progressable;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.tez.test.MiniTezCluster;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
/**
* Implemention of shims against Hadoop 0.23.0.
*/
public class Hadoop23Shims extends HadoopShimsSecure {
HadoopShims.MiniDFSShim cluster = null;
final boolean zeroCopy;
final boolean storagePolicy;
public Hadoop23Shims() {
boolean zcr = false;
boolean storage = false;
try {
Class.forName("org.apache.hadoop.fs.CacheFlag", false,
ShimLoader.class.getClassLoader());
zcr = true;
} catch (ClassNotFoundException ce) {
}
if (zcr) {
// in-memory HDFS is only available after zcr
try {
Class.forName("org.apache.hadoop.hdfs.protocol.BlockStoragePolicy",
false, ShimLoader.class.getClassLoader());
storage = true;
} catch (ClassNotFoundException ce) {
}
}
this.storagePolicy = storage;
this.zeroCopy = zcr;
}
@Override
public HadoopShims.CombineFileInputFormatShim getCombineFileInputFormat() {
return new CombineFileInputFormatShim() {
@Override
public RecordReader getRecordReader(InputSplit split,
JobConf job, Reporter reporter) throws IOException {
throw new IOException("CombineFileInputFormat.getRecordReader not needed.");
}
@Override
protected List<FileStatus> listStatus(JobContext job) throws IOException {
List<FileStatus> result = super.listStatus(job);
Iterator<FileStatus> it = result.iterator();
while (it.hasNext()) {
FileStatus stat = it.next();
if (!stat.isFile()) {
it.remove();
}
}
return result;
}
};
}
@Override
public String getTaskAttemptLogUrl(JobConf conf,
String taskTrackerHttpAddress, String taskAttemptId)
throws MalformedURLException {
if (conf.get("mapreduce.framework.name") != null
&& conf.get("mapreduce.framework.name").equals("yarn")) {
// if the cluster is running in MR2 mode, return null
LOG.warn("Can't fetch tasklog: TaskLogServlet is not supported in MR2 mode.");
return null;
} else {
// Was using Hadoop-internal API to get tasklogs, disable until MAPREDUCE-5857 is fixed.
LOG.warn("Can't fetch tasklog: TaskLogServlet is not supported in MR1 mode.");
return null;
}
}
@Override
public JobTrackerState getJobTrackerState(ClusterStatus clusterStatus) throws Exception {
switch (clusterStatus.getJobTrackerStatus()) {
case INITIALIZING:
return JobTrackerState.INITIALIZING;
case RUNNING:
return JobTrackerState.RUNNING;
default:
String errorMsg = "Unrecognized JobTracker state: " + clusterStatus.getJobTrackerStatus();
throw new Exception(errorMsg);
}
}
@Override
public org.apache.hadoop.mapreduce.TaskAttemptContext newTaskAttemptContext(Configuration conf, final Progressable progressable) {
TaskAttemptID taskAttemptId = TaskAttemptID.forName(conf.get(MRJobConfig.TASK_ATTEMPT_ID));
if (taskAttemptId == null) {
// If the caller is not within a mapper/reducer (if reading from the table via CliDriver),
// then TaskAttemptID.forname() may return NULL. Fall back to using default constructor.
taskAttemptId = new TaskAttemptID();
}
return new TaskAttemptContextImpl(conf, taskAttemptId) {
@Override
public void progress() {
progressable.progress();
}
};
}
@Override
public TaskAttemptID newTaskAttemptID(JobID jobId, boolean isMap, int taskId, int id) {
return new TaskAttemptID(jobId.getJtIdentifier(), jobId.getId(), isMap ? TaskType.MAP : TaskType.REDUCE, taskId, id);
}
@Override
public org.apache.hadoop.mapreduce.JobContext newJobContext(Job job) {
return new JobContextImpl(job.getConfiguration(), job.getJobID());
}
@Override
public void startPauseMonitor(Configuration conf) {
try {
Class.forName("org.apache.hadoop.util.JvmPauseMonitor");
org.apache.hadoop.util.JvmPauseMonitor pauseMonitor = new org.apache.hadoop.util
.JvmPauseMonitor(conf);
pauseMonitor.start();
} catch (Throwable t) {
LOG.warn("Could not initiate the JvmPauseMonitor thread." + " GCs and Pauses may not be " +
"warned upon.", t);
}
}
@Override
public boolean isLocalMode(Configuration conf) {
return "local".equals(conf.get("mapreduce.framework.name"));
}
@Override
public String getJobLauncherRpcAddress(Configuration conf) {
return conf.get("yarn.resourcemanager.address");
}
@Override
public void setJobLauncherRpcAddress(Configuration conf, String val) {
if (val.equals("local")) {
// LocalClientProtocolProvider expects both parameters to be 'local'.
conf.set("mapreduce.framework.name", val);
conf.set("mapreduce.jobtracker.address", val);
}
else {
conf.set("mapreduce.framework.name", "yarn");
conf.set("yarn.resourcemanager.address", val);
}
}
@Override
public String getJobLauncherHttpAddress(Configuration conf) {
return conf.get("yarn.resourcemanager.webapp.address");
}
protected boolean isExtendedAclEnabled(Configuration conf) {
return Objects.equal(conf.get("dfs.namenode.acls.enabled"), "true");
}
@Override
public long getDefaultBlockSize(FileSystem fs, Path path) {
return fs.getDefaultBlockSize(path);
}
@Override
public short getDefaultReplication(FileSystem fs, Path path) {
return fs.getDefaultReplication(path);
}
@Override
public boolean moveToAppropriateTrash(FileSystem fs, Path path, Configuration conf)
throws IOException {
return Trash.moveToAppropriateTrash(fs, path, conf);
}
@Override
public void setTotalOrderPartitionFile(JobConf jobConf, Path partitionFile){
TotalOrderPartitioner.setPartitionFile(jobConf, partitionFile);
}
@Override
public Comparator<LongWritable> getLongComparator() {
return new Comparator<LongWritable>() {
@Override
public int compare(LongWritable o1, LongWritable o2) {
return o1.compareTo(o2);
}
};
}
/**
* Load the fair scheduler queue for given user if available.
*/
@Override
public void refreshDefaultQueue(Configuration conf, String userName) throws IOException {
if (StringUtils.isNotBlank(userName) && isFairScheduler(conf)) {
ShimLoader.getSchedulerShims().refreshDefaultQueue(conf, userName);
}
}
private boolean isFairScheduler (Configuration conf) {
return "org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairScheduler".
equalsIgnoreCase(conf.get(YarnConfiguration.RM_SCHEDULER));
}
/**
* Returns a shim to wrap MiniMrCluster
*/
@Override
public MiniMrShim getMiniMrCluster(Configuration conf, int numberOfTaskTrackers,
String nameNode, int numDir) throws IOException {
return new MiniMrShim(conf, numberOfTaskTrackers, nameNode, numDir);
}
/**
* Shim for MiniMrCluster
*/
public class MiniMrShim implements HadoopShims.MiniMrShim {
private final MiniMRCluster mr;
private final Configuration conf;
public MiniMrShim() {
mr = null;
conf = null;
}
public MiniMrShim(Configuration conf, int numberOfTaskTrackers,
String nameNode, int numDir) throws IOException {
this.conf = conf;
JobConf jConf = new JobConf(conf);
jConf.set("yarn.scheduler.capacity.root.queues", "default");
jConf.set("yarn.scheduler.capacity.root.default.capacity", "100");
mr = new MiniMRCluster(numberOfTaskTrackers, nameNode, numDir, null, null, jConf);
}
@Override
public int getJobTrackerPort() throws UnsupportedOperationException {
String address = conf.get("yarn.resourcemanager.address");
address = StringUtils.substringAfterLast(address, ":");
if (StringUtils.isBlank(address)) {
throw new IllegalArgumentException("Invalid YARN resource manager port.");
}
return Integer.parseInt(address);
}
@Override
public void shutdown() throws IOException {
mr.shutdown();
}
@Override
public void setupConfiguration(Configuration conf) {
JobConf jConf = mr.createJobConf();
for (Map.Entry<String, String> pair: jConf) {
conf.set(pair.getKey(), pair.getValue());
}
}
}
/**
* Returns a shim to wrap MiniMrTez
*/
@Override
public MiniMrShim getMiniTezCluster(Configuration conf, int numberOfTaskTrackers,
String nameNode, int numDir) throws IOException {
return new MiniTezShim(conf, numberOfTaskTrackers, nameNode, numDir);
}
/**
* Shim for MiniTezCluster
*/
public class MiniTezShim extends Hadoop23Shims.MiniMrShim {
private final MiniTezCluster mr;
private final Configuration conf;
public MiniTezShim(Configuration conf, int numberOfTaskTrackers,
String nameNode, int numDir) throws IOException {
mr = new MiniTezCluster("hive", numberOfTaskTrackers);
conf.set("fs.defaultFS", nameNode);
conf.set("tez.am.log.level", "DEBUG");
conf.set(MRJobConfig.MR_AM_STAGING_DIR, "/apps_staging_dir");
mr.init(conf);
mr.start();
this.conf = mr.getConfig();
}
@Override
public int getJobTrackerPort() throws UnsupportedOperationException {
String address = conf.get("yarn.resourcemanager.address");
address = StringUtils.substringAfterLast(address, ":");
if (StringUtils.isBlank(address)) {
throw new IllegalArgumentException("Invalid YARN resource manager port.");
}
return Integer.parseInt(address);
}
@Override
public void shutdown() throws IOException {
mr.stop();
}
@Override
public void setupConfiguration(Configuration conf) {
Configuration config = mr.getConfig();
for (Map.Entry<String, String> pair: config) {
conf.set(pair.getKey(), pair.getValue());
}
Path jarPath = new Path("hdfs:///user/hive");
Path hdfsPath = new Path("hdfs:///user/");
try {
FileSystem fs = cluster.getFileSystem();
jarPath = fs.makeQualified(jarPath);
conf.set("hive.jar.directory", jarPath.toString());
fs.mkdirs(jarPath);
hdfsPath = fs.makeQualified(hdfsPath);
conf.set("hive.user.install.directory", hdfsPath.toString());
fs.mkdirs(hdfsPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Returns a shim to wrap MiniSparkOnYARNCluster
*/
@Override
public MiniMrShim getMiniSparkCluster(Configuration conf, int numberOfTaskTrackers,
String nameNode, int numDir) throws IOException {
return new MiniSparkShim(conf, numberOfTaskTrackers, nameNode, numDir);
}
/**
* Shim for MiniSparkOnYARNCluster
*/
public class MiniSparkShim extends Hadoop23Shims.MiniMrShim {
private final MiniSparkOnYARNCluster mr;
private final Configuration conf;
public MiniSparkShim(Configuration conf, int numberOfTaskTrackers,
String nameNode, int numDir) throws IOException {
mr = new MiniSparkOnYARNCluster("sparkOnYarn");
conf.set("fs.defaultFS", nameNode);
mr.init(conf);
mr.start();
this.conf = mr.getConfig();
}
@Override
public int getJobTrackerPort() throws UnsupportedOperationException {
String address = conf.get("yarn.resourcemanager.address");
address = StringUtils.substringAfterLast(address, ":");
if (StringUtils.isBlank(address)) {
throw new IllegalArgumentException("Invalid YARN resource manager port.");
}
return Integer.parseInt(address);
}
@Override
public void shutdown() throws IOException {
mr.stop();
}
@Override
public void setupConfiguration(Configuration conf) {
Configuration config = mr.getConfig();
for (Map.Entry<String, String> pair : config) {
conf.set(pair.getKey(), pair.getValue());
}
Path jarPath = new Path("hdfs:///user/hive");
Path hdfsPath = new Path("hdfs:///user/");
try {
FileSystem fs = cluster.getFileSystem();
jarPath = fs.makeQualified(jarPath);
conf.set("hive.jar.directory", jarPath.toString());
fs.mkdirs(jarPath);
hdfsPath = fs.makeQualified(hdfsPath);
conf.set("hive.user.install.directory", hdfsPath.toString());
fs.mkdirs(hdfsPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Don't move this code to the parent class. There's a binary
// incompatibility between hadoop 1 and 2 wrt MiniDFSCluster and we
// need to have two different shim classes even though they are
// exactly the same.
@Override
public HadoopShims.MiniDFSShim getMiniDfs(Configuration conf,
int numDataNodes,
boolean format,
String[] racks) throws IOException {
MiniDFSCluster miniDFSCluster = new MiniDFSCluster(conf, numDataNodes, format, racks);
// Need to set the client's KeyProvider to the NN's for JKS,
// else the updates do not get flushed properly
KeyProviderCryptoExtension keyProvider = miniDFSCluster.getNameNode().getNamesystem().getProvider();
if (keyProvider != null) {
miniDFSCluster.getFileSystem().getClient().setKeyProvider(keyProvider);
}
cluster = new MiniDFSShim(miniDFSCluster);
return cluster;
}
/**
* MiniDFSShim.
*
*/
public class MiniDFSShim implements HadoopShims.MiniDFSShim {
private final MiniDFSCluster cluster;
public MiniDFSShim(MiniDFSCluster cluster) {
this.cluster = cluster;
}
@Override
public FileSystem getFileSystem() throws IOException {
return cluster.getFileSystem();
}
@Override
public void shutdown() {
cluster.shutdown();
}
}
private volatile HCatHadoopShims hcatShimInstance;
@Override
public HCatHadoopShims getHCatShim() {
if(hcatShimInstance == null) {
hcatShimInstance = new HCatHadoopShims23();
}
return hcatShimInstance;
}
private final class HCatHadoopShims23 implements HCatHadoopShims {
@Override
public TaskID createTaskID() {
return new TaskID("", 0, TaskType.MAP, 0);
}
@Override
public TaskAttemptID createTaskAttemptID() {
return new TaskAttemptID("", 0, TaskType.MAP, 0, 0);
}
@Override
public org.apache.hadoop.mapreduce.TaskAttemptContext createTaskAttemptContext(Configuration conf,
org.apache.hadoop.mapreduce.TaskAttemptID taskId) {
return new org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl(
conf instanceof JobConf? new JobConf(conf) : conf,
taskId);
}
@Override
public org.apache.hadoop.mapred.TaskAttemptContext createTaskAttemptContext(org.apache.hadoop.mapred.JobConf conf,
org.apache.hadoop.mapred.TaskAttemptID taskId, Progressable progressable) {
org.apache.hadoop.mapred.TaskAttemptContext newContext = null;
try {
java.lang.reflect.Constructor construct = org.apache.hadoop.mapred.TaskAttemptContextImpl.class.getDeclaredConstructor(
org.apache.hadoop.mapred.JobConf.class, org.apache.hadoop.mapred.TaskAttemptID.class,
Reporter.class);
construct.setAccessible(true);
newContext = (org.apache.hadoop.mapred.TaskAttemptContext) construct.newInstance(
new JobConf(conf), taskId, progressable);
} catch (Exception e) {
throw new RuntimeException(e);
}
return newContext;
}
@Override
public JobContext createJobContext(Configuration conf,
JobID jobId) {
return new JobContextImpl(conf instanceof JobConf? new JobConf(conf) : conf,
jobId);
}
@Override
public org.apache.hadoop.mapred.JobContext createJobContext(org.apache.hadoop.mapred.JobConf conf,
org.apache.hadoop.mapreduce.JobID jobId, Progressable progressable) {
return new org.apache.hadoop.mapred.JobContextImpl(
new JobConf(conf), jobId, progressable);
}
@Override
public void commitJob(OutputFormat outputFormat, Job job) throws IOException {
// Do nothing as this was fixed by MAPREDUCE-1447.
}
@Override
public void abortJob(OutputFormat outputFormat, Job job) throws IOException {
// Do nothing as this was fixed by MAPREDUCE-1447.
}
@Override
public InetSocketAddress getResourceManagerAddress(Configuration conf) {
String addr = conf.get("yarn.resourcemanager.address", "localhost:8032");
return NetUtils.createSocketAddr(addr);
}
@Override
public String getPropertyName(PropertyName name) {
switch (name) {
case CACHE_ARCHIVES:
return MRJobConfig.CACHE_ARCHIVES;
case CACHE_FILES:
return MRJobConfig.CACHE_FILES;
case CACHE_SYMLINK:
return MRJobConfig.CACHE_SYMLINK;
case CLASSPATH_ARCHIVES:
return MRJobConfig.CLASSPATH_ARCHIVES;
case CLASSPATH_FILES:
return MRJobConfig.CLASSPATH_FILES;
}
return "";
}
@Override
public boolean isFileInHDFS(FileSystem fs, Path path) throws IOException {
// In case of viewfs we need to lookup where the actual file is to know the filesystem in use.
// resolvePath is a sure shot way of knowing which file system the file is.
return "hdfs".equals(fs.resolvePath(path).toUri().getScheme());
}
}
@Override
public WebHCatJTShim getWebHCatShim(Configuration conf, UserGroupInformation ugi) throws IOException {
return new WebHCatJTShim23(conf, ugi);//this has state, so can't be cached
}
@Override
public List<FileStatus> listLocatedStatus(final FileSystem fs,
final Path path,
final PathFilter filter
) throws IOException {
RemoteIterator<LocatedFileStatus> itr = fs.listLocatedStatus(path);
List<FileStatus> result = new ArrayList<FileStatus>();
while(itr.hasNext()) {
FileStatus stat = itr.next();
if (filter == null || filter.accept(stat.getPath())) {
result.add(stat);
}
}
return result;
}
@Override
public BlockLocation[] getLocations(FileSystem fs,
FileStatus status) throws IOException {
if (status instanceof LocatedFileStatus) {
return ((LocatedFileStatus) status).getBlockLocations();
} else {
return fs.getFileBlockLocations(status, 0, status.getLen());
}
}
@Override
public TreeMap<Long, BlockLocation> getLocationsWithOffset(FileSystem fs,
FileStatus status) throws IOException {
TreeMap<Long, BlockLocation> offsetBlockMap = new TreeMap<Long, BlockLocation>();
BlockLocation[] locations = getLocations(fs, status);
for (BlockLocation location : locations) {
offsetBlockMap.put(location.getOffset(), location);
}
return offsetBlockMap;
}
@Override
public void hflush(FSDataOutputStream stream) throws IOException {
stream.hflush();
}
@Override
public HdfsFileStatus getFullFileStatus(Configuration conf, FileSystem fs,
Path file) throws IOException {
FileStatus fileStatus = fs.getFileStatus(file);
AclStatus aclStatus = null;
if (isExtendedAclEnabled(conf)) {
//Attempt extended Acl operations only if its enabled, but don't fail the operation regardless.
try {
aclStatus = fs.getAclStatus(file);
} catch (Exception e) {
LOG.info("Skipping ACL inheritance: File system for path " + file + " " +
"does not support ACLs but dfs.namenode.acls.enabled is set to true: " + e, e);
}
}
return new Hadoop23FileStatus(fileStatus, aclStatus);
}
@Override
public void setFullFileStatus(Configuration conf, HdfsFileStatus sourceStatus,
FileSystem fs, Path target) throws IOException {
String group = sourceStatus.getFileStatus().getGroup();
//use FsShell to change group, permissions, and extended ACL's recursively
try {
FsShell fsShell = new FsShell();
fsShell.setConf(conf);
run(fsShell, new String[]{"-chgrp", "-R", group, target.toString()});
if (isExtendedAclEnabled(conf)) {
//Attempt extended Acl operations only if its enabled, 8791but don't fail the operation regardless.
try {
AclStatus aclStatus = ((Hadoop23FileStatus) sourceStatus).getAclStatus();
if (aclStatus != null) {
List<AclEntry> aclEntries = aclStatus.getEntries();
removeBaseAclEntries(aclEntries);
//the ACL api's also expect the tradition user/group/other permission in the form of ACL
FsPermission sourcePerm = sourceStatus.getFileStatus().getPermission();
aclEntries.add(newAclEntry(AclEntryScope.ACCESS, AclEntryType.USER, sourcePerm.getUserAction()));
aclEntries.add(newAclEntry(AclEntryScope.ACCESS, AclEntryType.GROUP, sourcePerm.getGroupAction()));
aclEntries.add(newAclEntry(AclEntryScope.ACCESS, AclEntryType.OTHER, sourcePerm.getOtherAction()));
//construct the -setfacl command
String aclEntry = Joiner.on(",").join(aclStatus.getEntries());
run(fsShell, new String[]{"-setfacl", "-R", "--set", aclEntry, target.toString()});
}
} catch (Exception e) {
LOG.info("Skipping ACL inheritance: File system for path " + target + " " +
"does not support ACLs but dfs.namenode.acls.enabled is set to true: " + e, e);
}
} else {
String permission = Integer.toString(sourceStatus.getFileStatus().getPermission().toShort(), 8);
run(fsShell, new String[]{"-chmod", "-R", permission, target.toString()});
}
} catch (Exception e) {
throw new IOException("Unable to set permissions of " + target, e);
}
try {
if (LOG.isDebugEnabled()) { //some trace logging
getFullFileStatus(conf, fs, target).debugLog();
}
} catch (Exception e) {
//ignore.
}
}
public class Hadoop23FileStatus implements HdfsFileStatus {
private final FileStatus fileStatus;
private final AclStatus aclStatus;
public Hadoop23FileStatus(FileStatus fileStatus, AclStatus aclStatus) {
this.fileStatus = fileStatus;
this.aclStatus = aclStatus;
}
@Override
public FileStatus getFileStatus() {
return fileStatus;
}
public AclStatus getAclStatus() {
return aclStatus;
}
@Override
public void debugLog() {
if (fileStatus != null) {
LOG.debug(fileStatus.toString());
}
if (aclStatus != null) {
LOG.debug(aclStatus.toString());
}
}
}
/**
* Create a new AclEntry with scope, type and permission (no name).
*
* @param scope
* AclEntryScope scope of the ACL entry
* @param type
* AclEntryType ACL entry type
* @param permission
* FsAction set of permissions in the ACL entry
* @return AclEntry new AclEntry
*/
private AclEntry newAclEntry(AclEntryScope scope, AclEntryType type,
FsAction permission) {
return new AclEntry.Builder().setScope(scope).setType(type)
.setPermission(permission).build();
}
/**
* Removes basic permission acls (unamed acls) from the list of acl entries
* @param entries acl entries to remove from.
*/
private void removeBaseAclEntries(List<AclEntry> entries) {
Iterables.removeIf(entries, new Predicate<AclEntry>() {
@Override
public boolean apply(AclEntry input) {
if (input.getName() == null) {
return true;
}
return false;
}
});
}
class ProxyFileSystem23 extends ProxyFileSystem {
public ProxyFileSystem23(FileSystem fs) {
super(fs);
}
public ProxyFileSystem23(FileSystem fs, URI uri) {
super(fs, uri);
}
@Override
public RemoteIterator<LocatedFileStatus> listLocatedStatus(final Path f)
throws FileNotFoundException, IOException {
return new RemoteIterator<LocatedFileStatus>() {
private final RemoteIterator<LocatedFileStatus> stats =
ProxyFileSystem23.super.listLocatedStatus(
ProxyFileSystem23.super.swizzleParamPath(f));
@Override
public boolean hasNext() throws IOException {
return stats.hasNext();
}
@Override
public LocatedFileStatus next() throws IOException {
LocatedFileStatus result = stats.next();
return new LocatedFileStatus(
ProxyFileSystem23.super.swizzleFileStatus(result, false),
result.getBlockLocations());
}
};
}
/**
* Proxy file system also needs to override the access() method behavior.
* Cannot add Override annotation since FileSystem.access() may not exist in
* the version of hadoop used to build Hive.
*/
public void access(Path path, FsAction action) throws AccessControlException,
FileNotFoundException, IOException {
Path underlyingFsPath = swizzleParamPath(path);
FileStatus underlyingFsStatus = fs.getFileStatus(underlyingFsPath);
try {
if (accessMethod != null) {
accessMethod.invoke(fs, underlyingFsPath, action);
} else {
// If the FS has no access() method, we can try DefaultFileAccess ..
DefaultFileAccess.checkFileAccess(fs, underlyingFsStatus, action);
}
} catch (AccessControlException err) {
throw err;
} catch (FileNotFoundException err) {
throw err;
} catch (IOException err) {
throw err;
} catch (Exception err) {
throw new RuntimeException(err.getMessage(), err);
}
}
}
@Override
public FileSystem createProxyFileSystem(FileSystem fs, URI uri) {
return new ProxyFileSystem23(fs, uri);
}
@Override
public Map<String, String> getHadoopConfNames() {
Map<String, String> ret = new HashMap<String, String>();
ret.put("HADOOPFS", "fs.defaultFS");
ret.put("HADOOPMAPFILENAME", "mapreduce.map.input.file");
ret.put("HADOOPMAPREDINPUTDIR", "mapreduce.input.fileinputformat.inputdir");
ret.put("HADOOPMAPREDINPUTDIRRECURSIVE", "mapreduce.input.fileinputformat.input.dir.recursive");
ret.put("MAPREDMAXSPLITSIZE", "mapreduce.input.fileinputformat.split.maxsize");
ret.put("MAPREDMINSPLITSIZE", "mapreduce.input.fileinputformat.split.minsize");
ret.put("MAPREDMINSPLITSIZEPERNODE", "mapreduce.input.fileinputformat.split.minsize.per.node");
ret.put("MAPREDMINSPLITSIZEPERRACK", "mapreduce.input.fileinputformat.split.minsize.per.rack");
ret.put("HADOOPNUMREDUCERS", "mapreduce.job.reduces");
ret.put("HADOOPJOBNAME", "mapreduce.job.name");
ret.put("HADOOPSPECULATIVEEXECREDUCERS", "mapreduce.reduce.speculative");
ret.put("MAPREDSETUPCLEANUPNEEDED", "mapreduce.job.committer.setup.cleanup.needed");
ret.put("MAPREDTASKCLEANUPNEEDED", "mapreduce.job.committer.task.cleanup.needed");
return ret;
}
@Override
public ZeroCopyReaderShim getZeroCopyReader(FSDataInputStream in, ByteBufferPoolShim pool) throws IOException {
if(zeroCopy) {
return ZeroCopyShims.getZeroCopyReader(in, pool);
}
/* not supported */
return null;
}
@Override
public DirectDecompressorShim getDirectDecompressor(DirectCompressionType codec) {
if(zeroCopy) {
return ZeroCopyShims.getDirectDecompressor(codec);
}
/* not supported */
return null;
}
@Override
public Configuration getConfiguration(org.apache.hadoop.mapreduce.JobContext context) {
return context.getConfiguration();
}
@Override
public JobConf getJobConf(org.apache.hadoop.mapred.JobContext context) {
return context.getJobConf();
}
@Override
public FileSystem getNonCachedFileSystem(URI uri, Configuration conf) throws IOException {
return FileSystem.newInstance(uri, conf);
}
@Override
public void getMergedCredentials(JobConf jobConf) throws IOException {
jobConf.getCredentials().mergeAll(UserGroupInformation.getCurrentUser().getCredentials());
}
@Override
public void mergeCredentials(JobConf dest, JobConf src) throws IOException {
dest.getCredentials().mergeAll(src.getCredentials());
}
protected static final Method accessMethod;
protected static final Method getPasswordMethod;
static {
Method m = null;
try {
m = FileSystem.class.getMethod("access", Path.class, FsAction.class);
} catch (NoSuchMethodException err) {
// This version of Hadoop does not support FileSystem.access().
}
accessMethod = m;
try {
m = Configuration.class.getMethod("getPassword", String.class);
} catch (NoSuchMethodException err) {
// This version of Hadoop does not support getPassword(), just retrieve password from conf.
m = null;
}
getPasswordMethod = m;
}
@Override
public void checkFileAccess(FileSystem fs, FileStatus stat, FsAction action)
throws IOException, AccessControlException, Exception {
try {
if (accessMethod == null) {
// Have to rely on Hive implementation of filesystem permission checks.
DefaultFileAccess.checkFileAccess(fs, stat, action);
} else {
accessMethod.invoke(fs, stat.getPath(), action);
}
} catch (Exception err) {
throw wrapAccessException(err);
}
}
/**
* If there is an AccessException buried somewhere in the chain of failures, wrap the original
* exception in an AccessException. Othewise just return the original exception.
*/
private static Exception wrapAccessException(Exception err) {
final int maxDepth = 20;
Throwable curErr = err;
for (int idx = 0; curErr != null && idx < maxDepth; ++idx) {
// fs.permission.AccessControlException removed by HADOOP-11356, but Hive users on older
// Hadoop versions may still see this exception .. have to reference by name.
if (curErr instanceof org.apache.hadoop.security.AccessControlException
|| curErr.getClass().getName().equals("org.apache.hadoop.fs.permission.AccessControlException")) {
Exception newErr = new AccessControlException(curErr.getMessage());
newErr.initCause(err);
return newErr;
}
curErr = curErr.getCause();
}
return err;
}
@Override
public String getPassword(Configuration conf, String name) throws IOException {
if (getPasswordMethod == null) {
// Just retrieve value from conf
return conf.get(name);
} else {
try {