1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.security.access;
20
21 import com.google.common.annotations.VisibleForTesting;
22 import com.google.protobuf.RpcCallback;
23 import com.google.protobuf.RpcController;
24 import com.google.protobuf.Service;
25
26 import org.apache.commons.lang.StringUtils;
27 import org.apache.commons.lang.mutable.MutableInt;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.hadoop.hbase.classification.InterfaceAudience;
31 import org.apache.hadoop.hbase.client.Connection;
32 import org.apache.hadoop.conf.Configuration;
33 import org.apache.hadoop.fs.FileStatus;
34 import org.apache.hadoop.fs.FileSystem;
35 import org.apache.hadoop.fs.FileUtil;
36 import org.apache.hadoop.fs.Path;
37 import org.apache.hadoop.fs.permission.FsPermission;
38 import org.apache.hadoop.hbase.Coprocessor;
39 import org.apache.hadoop.hbase.CoprocessorEnvironment;
40 import org.apache.hadoop.hbase.TableName;
41 import org.apache.hadoop.hbase.DoNotRetryIOException;
42 import org.apache.hadoop.hbase.coprocessor.BulkLoadObserver;
43 import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
44 import org.apache.hadoop.hbase.coprocessor.ObserverContext;
45 import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
46 import org.apache.hadoop.hbase.ipc.RpcServer;
47 import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
48 import org.apache.hadoop.hbase.protobuf.ResponseConverter;
49 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
50 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadService;
51 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadRequest;
52 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.PrepareBulkLoadResponse;
53 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadRequest;
54 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.CleanupBulkLoadResponse;
55 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadHFilesRequest;
56 import org.apache.hadoop.hbase.protobuf.generated.SecureBulkLoadProtos.SecureBulkLoadHFilesResponse;
57 import org.apache.hadoop.hbase.regionserver.Region;
58 import org.apache.hadoop.hbase.regionserver.Region.BulkLoadListener;
59 import org.apache.hadoop.hbase.regionserver.RegionServerServices;
60 import org.apache.hadoop.hbase.security.SecureBulkLoadUtil;
61 import org.apache.hadoop.hbase.security.User;
62 import org.apache.hadoop.hbase.security.UserProvider;
63 import org.apache.hadoop.hbase.security.token.FsDelegationToken;
64 import org.apache.hadoop.hbase.security.token.TokenUtil;
65 import org.apache.hadoop.hbase.util.Bytes;
66 import org.apache.hadoop.hbase.util.FSHDFSUtils;
67 import org.apache.hadoop.hbase.util.Methods;
68 import org.apache.hadoop.hbase.util.Pair;
69 import org.apache.hadoop.io.Text;
70 import org.apache.hadoop.security.UserGroupInformation;
71 import org.apache.hadoop.security.token.Token;
72
73 import java.io.IOException;
74 import java.math.BigInteger;
75 import java.security.PrivilegedAction;
76 import java.security.SecureRandom;
77 import java.util.ArrayList;
78 import java.util.Arrays;
79 import java.util.HashMap;
80 import java.util.HashSet;
81 import java.util.List;
82 import java.util.Map;
83 import java.util.Set;
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 @InterfaceAudience.Private
112 public class SecureBulkLoadEndpoint extends SecureBulkLoadService
113 implements CoprocessorService, Coprocessor {
114
115 public static final long VERSION = 0L;
116
117
118 private static final int RANDOM_WIDTH = 320;
119 private static final int RANDOM_RADIX = 32;
120
121 private static final Log LOG = LogFactory.getLog(SecureBulkLoadEndpoint.class);
122
123 private final static FsPermission PERM_ALL_ACCESS = FsPermission.valueOf("-rwxrwxrwx");
124 private final static FsPermission PERM_HIDDEN = FsPermission.valueOf("-rwx--x--x");
125
126 public static final String FS_WITHOUT_SUPPORT_PERMISSION_KEY =
127 "hbase.secure.bulkload.fs.permission.lacking";
128 public static final String FS_WITHOUT_SUPPORT_PERMISSION_DEFAULT =
129 "s3,s3a,s3n,wasb,wasbs,swift,adfs,abfs,viewfs";
130
131 private SecureRandom random;
132 private FileSystem fs;
133 private Configuration conf;
134
135
136
137 private Path baseStagingDir;
138
139 private RegionCoprocessorEnvironment env;
140 private Connection conn;
141
142 private UserProvider userProvider;
143 private static HashMap<UserGroupInformation, MutableInt> ugiReferenceCounter = new HashMap<>();
144
145 @Override
146 public void start(CoprocessorEnvironment env) {
147 this.env = (RegionCoprocessorEnvironment)env;
148 random = new SecureRandom();
149 RegionServerServices svc = ((RegionCoprocessorEnvironment)env).getRegionServerServices();
150 this.conn = svc.getConnection();
151 conf = env.getConfiguration();
152 baseStagingDir = SecureBulkLoadUtil.getBaseStagingDir(conf);
153 this.userProvider = UserProvider.instantiate(conf);
154 Set<String> fsSet = getFileSystemSchemesWithoutPermissionSupport(conf);
155
156 try {
157 fs = baseStagingDir.getFileSystem(conf);
158 if (!fs.exists(baseStagingDir)) {
159 fs.mkdirs(baseStagingDir, PERM_HIDDEN);
160 }
161 FileStatus status = fs.getFileStatus(baseStagingDir);
162 if (status == null) {
163 throw new IllegalStateException("Failed to create staging directory");
164 }
165
166
167
168 if (!status.getPermission().equals(PERM_HIDDEN)) {
169 fs.setPermission(baseStagingDir, PERM_HIDDEN);
170 status = fs.getFileStatus(baseStagingDir);
171 }
172
173
174 Path doNotEraseDir = new Path(baseStagingDir, "DONOTERASE");
175 if (!fs.exists(doNotEraseDir)) {
176 fs.mkdirs(doNotEraseDir, PERM_HIDDEN);
177 fs.setPermission(doNotEraseDir, PERM_HIDDEN);
178 }
179
180 String scheme = fs.getScheme().toLowerCase();
181 if (!fsSet.contains(scheme) && !status.getPermission().equals(PERM_HIDDEN)) {
182 throw new IllegalStateException(
183 "Staging directory of " + baseStagingDir + " already exists but permissions aren't set to '-rwx--x--x' ");
184 }
185 } catch (IOException e) {
186 throw new IllegalStateException("Failed to get FileSystem instance",e);
187 }
188 }
189
190 Set<String> getFileSystemSchemesWithoutPermissionSupport(Configuration conf) {
191 final String value = conf.get(
192 FS_WITHOUT_SUPPORT_PERMISSION_KEY, FS_WITHOUT_SUPPORT_PERMISSION_DEFAULT);
193 return new HashSet<String>(Arrays.asList(StringUtils.split(value, ',')));
194 }
195
196 @Override
197 public void stop(CoprocessorEnvironment env) throws IOException {
198 }
199
200 @Override
201 public void prepareBulkLoad(RpcController controller,
202 PrepareBulkLoadRequest request,
203 RpcCallback<PrepareBulkLoadResponse> done){
204 try {
205 List<BulkLoadObserver> bulkLoadObservers = getBulkLoadObservers();
206
207 if(bulkLoadObservers != null) {
208 ObserverContext<RegionCoprocessorEnvironment> ctx =
209 new ObserverContext<RegionCoprocessorEnvironment>();
210 ctx.prepare(env);
211
212 for(BulkLoadObserver bulkLoadObserver : bulkLoadObservers) {
213 bulkLoadObserver.prePrepareBulkLoad(ctx, request);
214 }
215 }
216
217 String bulkToken = createStagingDir(baseStagingDir,
218 getActiveUser(), ProtobufUtil.toTableName(request.getTableName())).toString();
219 done.run(PrepareBulkLoadResponse.newBuilder().setBulkToken(bulkToken).build());
220 } catch (IOException e) {
221 ResponseConverter.setControllerException(controller, e);
222 }
223 done.run(null);
224 }
225
226 @Override
227 public void cleanupBulkLoad(RpcController controller,
228 CleanupBulkLoadRequest request,
229 RpcCallback<CleanupBulkLoadResponse> done) {
230 try {
231 List<BulkLoadObserver> bulkLoadObservers = getBulkLoadObservers();
232
233 if(bulkLoadObservers != null) {
234 ObserverContext<RegionCoprocessorEnvironment> ctx =
235 new ObserverContext<RegionCoprocessorEnvironment>();
236 ctx.prepare(env);
237
238 for(BulkLoadObserver bulkLoadObserver : bulkLoadObservers) {
239 bulkLoadObserver.preCleanupBulkLoad(ctx, request);
240 }
241 }
242
243 Path path = new Path(request.getBulkToken());
244 if (!fs.delete(path, true)) {
245 if (fs.exists(path)) {
246 throw new IOException("Failed to clean up " + path);
247 }
248 }
249 LOG.info("Cleaned up " + path + " successfully.");
250 done.run(CleanupBulkLoadResponse.newBuilder().build());
251 } catch (IOException e) {
252 ResponseConverter.setControllerException(controller, e);
253 } finally {
254 UserGroupInformation ugi = getActiveUser().getUGI();
255 try {
256 if (!UserGroupInformation.getLoginUser().equals(ugi) && !isUserReferenced(ugi)) {
257 FileSystem.closeAllForUGI(ugi);
258 }
259 } catch (IOException e) {
260 LOG.error("Failed to close FileSystem for: " + ugi, e);
261 }
262 }
263 done.run(null);
264 }
265
266 @VisibleForTesting
267 interface Consumer<T> {
268 void accept(T t);
269 }
270 private static Consumer<Region> fsCreatedListener;
271
272 @VisibleForTesting
273 static void setFsCreatedListener(Consumer<Region> listener) {
274 fsCreatedListener = listener;
275 }
276
277
278 private void incrementUgiReference(UserGroupInformation ugi) {
279 synchronized (ugiReferenceCounter) {
280 final MutableInt counter = ugiReferenceCounter.get(ugi);
281 if (counter == null) {
282 ugiReferenceCounter.put(ugi, new MutableInt(1));
283 } else {
284 counter.increment();
285 }
286 }
287 }
288
289 private void decrementUgiReference(UserGroupInformation ugi) {
290 synchronized (ugiReferenceCounter) {
291 final MutableInt counter = ugiReferenceCounter.get(ugi);
292 if(counter == null || counter.intValue() <= 1) {
293 ugiReferenceCounter.remove(ugi);
294 } else {
295 counter.decrement();
296 }
297 }
298 }
299
300 private boolean isUserReferenced(UserGroupInformation ugi) {
301 synchronized (ugiReferenceCounter) {
302 final MutableInt counter = ugiReferenceCounter.get(ugi);
303 return counter != null && counter.intValue() > 0;
304 }
305 }
306
307 @Override
308 public void secureBulkLoadHFiles(RpcController controller,
309 final SecureBulkLoadHFilesRequest request,
310 RpcCallback<SecureBulkLoadHFilesResponse> done) {
311 final List<Pair<byte[], String>> familyPaths = new ArrayList<Pair<byte[], String>>();
312 for(ClientProtos.BulkLoadHFileRequest.FamilyPath el : request.getFamilyPathList()) {
313 familyPaths.add(new Pair(el.getFamily().toByteArray(),el.getPath()));
314 }
315
316 Token userToken = null;
317 if (userProvider.isHadoopSecurityEnabled()) {
318 userToken = new Token(request.getFsToken().getIdentifier().toByteArray(), request.getFsToken()
319 .getPassword().toByteArray(), new Text(request.getFsToken().getKind()), new Text(
320 request.getFsToken().getService()));
321 }
322 final String bulkToken = request.getBulkToken();
323 User user = getActiveUser();
324 final UserGroupInformation ugi = user.getUGI();
325 if (userProvider.isHadoopSecurityEnabled()) {
326 try {
327 Token tok = TokenUtil.obtainToken(conn);
328 if (tok != null) {
329 boolean b = ugi.addToken(tok);
330 LOG.debug("extra token added " + tok + " ret=" + b);
331 }
332 } catch (IOException ioe) {
333 LOG.warn("unable to add token", ioe);
334 }
335 }
336 if (userToken != null) {
337 ugi.addToken(userToken);
338 } else if (userProvider.isHadoopSecurityEnabled()) {
339
340
341 ResponseConverter.setControllerException(controller,
342 new DoNotRetryIOException("User token cannot be null"));
343 done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(false).build());
344 return;
345 }
346
347 Region region = env.getRegion();
348 boolean bypass = false;
349 if (region.getCoprocessorHost() != null) {
350 try {
351 bypass = region.getCoprocessorHost().preBulkLoadHFile(familyPaths);
352 } catch (IOException e) {
353 ResponseConverter.setControllerException(controller, e);
354 done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(false).build());
355 return;
356 }
357 }
358 boolean loaded = false;
359 if (!bypass) {
360
361
362
363
364
365 if (userProvider.isHadoopSecurityEnabled()) {
366 FsDelegationToken targetfsDelegationToken = new FsDelegationToken(userProvider, "renewer");
367 try {
368 targetfsDelegationToken.acquireDelegationToken(fs);
369 } catch (IOException e) {
370 ResponseConverter.setControllerException(controller, e);
371 done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(false).build());
372 return;
373 }
374 Token<?> targetFsToken = targetfsDelegationToken.getUserToken();
375 if (targetFsToken != null
376 && (userToken == null || !targetFsToken.getService().equals(userToken.getService()))) {
377 ugi.addToken(targetFsToken);
378 }
379 }
380
381 incrementUgiReference(ugi);
382 loaded = ugi.doAs(new PrivilegedAction<Boolean>() {
383 @Override
384 public Boolean run() {
385 FileSystem fs = null;
386 try {
387 Configuration conf = env.getConfiguration();
388 fs = FileSystem.get(conf);
389 for(Pair<byte[], String> el: familyPaths) {
390 Path stageFamily = new Path(bulkToken, Bytes.toString(el.getFirst()));
391 if(!fs.exists(stageFamily)) {
392 fs.mkdirs(stageFamily);
393 fs.setPermission(stageFamily, PERM_ALL_ACCESS);
394 }
395 }
396 if (fsCreatedListener != null) {
397 fsCreatedListener.accept(env.getRegion());
398 }
399
400
401 return env.getRegion().bulkLoadHFiles(familyPaths, true,
402 new SecureBulkLoadListener(fs, bulkToken, conf), request.getClusterIdsList());
403 } catch (Exception e) {
404 LOG.error("Failed to complete bulk load", e);
405 }
406 return false;
407 }
408 });
409 decrementUgiReference(ugi);
410 }
411 if (region.getCoprocessorHost() != null) {
412 try {
413 loaded = region.getCoprocessorHost().postBulkLoadHFile(familyPaths, loaded);
414 } catch (IOException e) {
415 ResponseConverter.setControllerException(controller, e);
416 done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(false).build());
417 return;
418 }
419 }
420 done.run(SecureBulkLoadHFilesResponse.newBuilder().setLoaded(loaded).build());
421 }
422
423 private List<BulkLoadObserver> getBulkLoadObservers() {
424 List<BulkLoadObserver> coprocessorList =
425 this.env.getRegion().getCoprocessorHost().findCoprocessors(BulkLoadObserver.class);
426
427 return coprocessorList;
428 }
429
430 private Path createStagingDir(Path baseDir,
431 User user,
432 TableName tableName) throws IOException {
433 String tblName = tableName.getNameAsString().replace(":", "_");
434 String randomDir = user.getShortName()+"__"+ tblName +"__"+
435 (new BigInteger(RANDOM_WIDTH, random).toString(RANDOM_RADIX));
436 return createStagingDir(baseDir, user, randomDir);
437 }
438
439 private Path createStagingDir(Path baseDir,
440 User user,
441 String randomDir) throws IOException {
442 Path p = new Path(baseDir, randomDir);
443 fs.mkdirs(p, PERM_ALL_ACCESS);
444 fs.setPermission(p, PERM_ALL_ACCESS);
445 return p;
446 }
447
448 private User getActiveUser() {
449 User user = RpcServer.getRequestUser();
450 if (user == null) {
451 return null;
452 }
453
454
455 if (userProvider.isHadoopSecurityEnabled()
456 && "simple".equalsIgnoreCase(conf.get(User.HBASE_SECURITY_CONF_KEY))) {
457 return User.createUserForTesting(conf, user.getShortName(), new String[]{});
458 }
459
460 return user;
461 }
462
463 @Override
464 public Service getService() {
465 return this;
466 }
467
468 private static class SecureBulkLoadListener implements BulkLoadListener {
469
470 private FileSystem fs;
471 private String stagingDir;
472 private Configuration conf;
473
474 private FileSystem srcFs = null;
475 private Map<String, FsPermission> origPermissions = null;
476
477 public SecureBulkLoadListener(FileSystem fs, String stagingDir, Configuration conf) {
478 this.fs = fs;
479 this.stagingDir = stagingDir;
480 this.conf = conf;
481 this.origPermissions = new HashMap<String, FsPermission>();
482 }
483
484 @Override
485 public String prepareBulkLoad(final byte[] family, final String srcPath) throws IOException {
486 Path p = new Path(srcPath);
487 Path stageP = new Path(stagingDir, new Path(Bytes.toString(family), p.getName()));
488
489
490 if (p.equals(stageP)) {
491 LOG.debug(p.getName()
492 + " is already available in staging directory. Skipping copy or rename.");
493 return stageP.toString();
494 }
495
496 if (srcFs == null) {
497 srcFs = FileSystem.newInstance(p.toUri(), conf);
498 }
499
500 if(!isFile(p)) {
501 throw new IOException("Path does not reference a file: " + p);
502 }
503
504
505 if (!FSHDFSUtils.isSameHdfs(conf, srcFs, fs)) {
506 LOG.debug("Bulk-load file " + srcPath + " is on different filesystem than " +
507 "the destination filesystem. Copying file over to destination staging dir.");
508 FileUtil.copy(srcFs, p, fs, stageP, false, conf);
509 } else {
510 LOG.debug("Moving " + p + " to " + stageP);
511 FileStatus origFileStatus = fs.getFileStatus(p);
512 origPermissions.put(srcPath, origFileStatus.getPermission());
513 if(!fs.rename(p, stageP)) {
514 throw new IOException("Failed to move HFile: " + p + " to " + stageP);
515 }
516 }
517 fs.setPermission(stageP, PERM_ALL_ACCESS);
518 return stageP.toString();
519 }
520
521 @Override
522 public void doneBulkLoad(byte[] family, String srcPath) throws IOException {
523 LOG.debug("Bulk Load done for: " + srcPath);
524 closeSrcFs();
525 }
526
527 private void closeSrcFs() throws IOException {
528 if (srcFs != null) {
529 srcFs.close();
530 srcFs = null;
531 }
532 }
533
534 @Override
535 public void failedBulkLoad(final byte[] family, final String srcPath) throws IOException {
536 try {
537 Path p = new Path(srcPath);
538 if (srcFs == null) {
539 srcFs = FileSystem.newInstance(p.toUri(), conf);
540 }
541 if (!FSHDFSUtils.isSameHdfs(conf, srcFs, fs)) {
542
543 return;
544 }
545 Path stageP = new Path(stagingDir, new Path(Bytes.toString(family), p.getName()));
546
547
548
549 if (p.equals(stageP)) {
550 LOG.debug(p.getName() + " is already available in source directory. Skipping rename.");
551 return;
552 }
553
554 LOG.debug("Moving " + stageP + " back to " + p);
555 if (!fs.rename(stageP, p))
556 throw new IOException("Failed to move HFile: " + stageP + " to " + p);
557
558
559 if (origPermissions.containsKey(srcPath)) {
560 fs.setPermission(p, origPermissions.get(srcPath));
561 } else {
562 LOG.warn("Can't find previous permission for path=" + srcPath);
563 }
564 } finally {
565 closeSrcFs();
566 }
567 }
568
569
570
571
572
573
574
575
576 private boolean isFile(Path p) throws IOException {
577 FileStatus status = srcFs.getFileStatus(p);
578 boolean isFile = !status.isDirectory();
579 try {
580 isFile = isFile && !(Boolean)Methods.call(FileStatus.class, status, "isSymlink", null, null);
581 } catch (Exception e) {
582 }
583 return isFile;
584 }
585 }
586 }