mymeiyi commented on a change in pull request #163: HBASE-21995 Add a coprocessor to set HDFS ACL for hbase granted user URL: https://github.com/apache/hbase/pull/163#discussion_r293715484
########## File path: hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/SnapshotScannerHDFSAclController.java ########## @@ -0,0 +1,652 @@ +/** + * 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.hbase.security.access; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.hbase.Cell; +import org.apache.hadoop.hbase.CellUtil; +import org.apache.hadoop.hbase.HBaseInterfaceAudience; +import org.apache.hadoop.hbase.NamespaceDescriptor; +import org.apache.hadoop.hbase.TableName; +import org.apache.hadoop.hbase.TableNotFoundException; +import org.apache.hadoop.hbase.client.Admin; +import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; +import org.apache.hadoop.hbase.client.Delete; +import org.apache.hadoop.hbase.client.Get; +import org.apache.hadoop.hbase.client.Put; +import org.apache.hadoop.hbase.client.RegionInfo; +import org.apache.hadoop.hbase.client.Result; +import org.apache.hadoop.hbase.client.ResultScanner; +import org.apache.hadoop.hbase.client.Scan; +import org.apache.hadoop.hbase.client.SnapshotDescription; +import org.apache.hadoop.hbase.client.Table; +import org.apache.hadoop.hbase.client.TableDescriptor; +import org.apache.hadoop.hbase.client.TableDescriptorBuilder; +import org.apache.hadoop.hbase.coprocessor.CoreCoprocessor; +import org.apache.hadoop.hbase.coprocessor.HasMasterServices; +import org.apache.hadoop.hbase.coprocessor.MasterCoprocessor; +import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment; +import org.apache.hadoop.hbase.coprocessor.MasterObserver; +import org.apache.hadoop.hbase.coprocessor.ObserverContext; +import org.apache.hadoop.hbase.master.MasterServices; +import org.apache.hadoop.hbase.security.User; +import org.apache.hadoop.hbase.security.UserProvider; +import org.apache.hadoop.hbase.security.access.Permission.Action; +import org.apache.hadoop.hbase.security.access.SnapshotScannerHDFSAclHelper.PathHelper; +import org.apache.hadoop.hbase.util.Bytes; +import org.apache.yetus.audience.InterfaceAudience; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Set HDFS ACLs to hFiles to make HBase granted users have permission to scan snapshot + * <p> + * To use this feature, please mask sure HDFS config: + * <ul> + * <li>dfs.permissions.enabled = true</li> + * <li>fs.permissions.umask-mode = 027 (or smaller umask than 027)</li> + * </ul> + * </p> + * <p> + * The implementation of this feature is as followings: + * <ul> + * <li>For common directories such as 'data' and 'archive', set other permission to '--x' to make + * everyone have the permission to access the directory.</li> + * <li>For namespace or table directories such as 'data/ns/table', 'archive/ns/table' and + * '.hbase-snapshot/snapshotName', set user 'r-x' access acl and 'r-x' default acl when following + * operations happen: + * <ul> + * <li>grant user with global, namespace or table permission;</li> + * <li>revoke user from global, namespace or table;</li> + * <li>snapshot table;</li> + * <li>truncate table;</li> + * </ul> + * </li> + * <li>Note: Because snapshots are at table level, so this feature just considers users with global, + * namespace or table permissions, ignores users with table CF or cell permissions.</li> + * </ul> + * </p> + */ +@CoreCoprocessor [email protected](HBaseInterfaceAudience.CONFIG) +public class SnapshotScannerHDFSAclController implements MasterCoprocessor, MasterObserver { + private static final Logger LOG = LoggerFactory.getLogger(SnapshotScannerHDFSAclController.class); + + private SnapshotScannerHDFSAclHelper hdfsAclHelper = null; + private PathHelper pathHelper = null; + private FileSystem fs = null; + private volatile boolean initialized = false; + /** Provider for mapping principal names to Users */ + private UserProvider userProvider; + + @Override + public Optional<MasterObserver> getMasterObserver() { + return Optional.of(this); + } + + @Override + public void preMasterInitialization(ObserverContext<MasterCoprocessorEnvironment> c) + throws IOException { + if (c.getEnvironment().getConfiguration() + .getBoolean(SnapshotScannerHDFSAclHelper.USER_SCAN_SNAPSHOT_ENABLE, false)) { + MasterCoprocessorEnvironment mEnv = c.getEnvironment(); + if (!(mEnv instanceof HasMasterServices)) { + throw new IOException("Does not implement HMasterServices"); + } + MasterServices masterServices = ((HasMasterServices) mEnv).getMasterServices(); + hdfsAclHelper = new SnapshotScannerHDFSAclHelper(masterServices.getConfiguration(), + masterServices.getConnection()); + pathHelper = hdfsAclHelper.getPathHelper(); + fs = pathHelper.getFileSystem(); + hdfsAclHelper.setCommonDirectoryPermission(); + initialized = true; + userProvider = UserProvider.instantiate(c.getEnvironment().getConfiguration()); + } else { + LOG.warn( + "Load SnapshotScannerHDFSAclController but hbase.user.scan.snapshot.enable is false"); + } + } + + @Override + public void postStartMaster(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException { + if (checkInitialized()) { + try (Admin admin = c.getEnvironment().getConnection().getAdmin()) { + if (admin.tableExists(PermissionStorage.ACL_TABLE_NAME)) { + // Check if hbase acl table has 'm' CF, if not, add 'm' CF + TableDescriptor tableDescriptor = admin.getDescriptor(PermissionStorage.ACL_TABLE_NAME); + boolean containHdfsAclFamily = + Arrays.stream(tableDescriptor.getColumnFamilies()).anyMatch(family -> Bytes + .equals(family.getName(), SnapshotScannerHDFSAclStorage.HDFS_ACL_FAMILY)); + if (!containHdfsAclFamily) { + TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableDescriptor) + .setColumnFamily(ColumnFamilyDescriptorBuilder + .newBuilder(SnapshotScannerHDFSAclStorage.HDFS_ACL_FAMILY).build()); + admin.modifyTable(builder.build()); + } + } else { + LOG.error( + "Table {} is not yet created. Please check if {} is configured after the {} Coprocessor", + PermissionStorage.ACL_TABLE_NAME, getClass().getSimpleName(), + AccessController.class.getSimpleName()); + throw new TableNotFoundException( + "Table " + PermissionStorage.ACL_TABLE_NAME + " is not yet created"); + } + } + } + } + + @Override + public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c) { + if (checkInitialized()) { + hdfsAclHelper.close(); + } + } + + @Override + public void postCompletedCreateTableAction(ObserverContext<MasterCoprocessorEnvironment> c, + TableDescriptor desc, RegionInfo[] regions) throws IOException { + if (!desc.getTableName().isSystemTable() && checkInitialized()) { + TableName tableName = desc.getTableName(); + Path[] paths = + new Path[] { pathHelper.getTmpTableDir(tableName), pathHelper.getDataTableDir(tableName), + pathHelper.getMobTableDir(tableName), pathHelper.getArchiveTableDir(tableName) }; + for (Path path : paths) { + if (!fs.exists(path)) { + fs.mkdirs(path); + } + } + // Add table owner HDFS acls + String owner = + desc.getOwnerString() == null ? getActiveUser(c).getShortName() : desc.getOwnerString(); + hdfsAclHelper.addTableAcl(desc.getTableName(), owner); + try (Table aclTable = + c.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { + SnapshotScannerHDFSAclStorage.addUserTableHdfsAcl(aclTable, owner, desc.getTableName()); + } + } + } + + @Override + public void postCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> c, + NamespaceDescriptor ns) throws IOException { + if (checkInitialized()) { + Path[] nsDirs = new Path[] { pathHelper.getTmpNsDir(ns.getName()), + pathHelper.getArchiveNsDir(ns.getName()), pathHelper.getMobDataNsDir(ns.getName()) }; + for (Path nsDir : nsDirs) { + if (!fs.exists(nsDir)) { + fs.mkdirs(nsDir); + } + } + } + } + + @Override + public void postCompletedSnapshotAction(ObserverContext<MasterCoprocessorEnvironment> c, + SnapshotDescription snapshot, TableDescriptor tableDescriptor) throws IOException { + if (!tableDescriptor.getTableName().isSystemTable() && checkInitialized()) { + hdfsAclHelper.snapshotAcl(snapshot); + } + } + + @Override + public void postCompletedTruncateTableAction(ObserverContext<MasterCoprocessorEnvironment> c, + TableName tableName) throws IOException { + if (!tableName.isSystemTable() && checkInitialized()) { + hdfsAclHelper.resetTableAcl(tableName); + } + } + + @Override + public void postDeleteTable(ObserverContext<MasterCoprocessorEnvironment> ctx, + TableName tableName) throws IOException { + if (!tableName.isSystemTable() && checkInitialized()) { + // remove table user HDFS acl from ns data directory if the user has no global/the ns/other + // tables of the ns permissions + Set<String> removeUsers = new HashSet<>(); + try (Table aclTable = + ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { + List<String> users = SnapshotScannerHDFSAclStorage.getTableUsers(aclTable, tableName); + SnapshotScannerHDFSAclStorage.deleteTableHdfsAcl(aclTable, tableName); + for (String user : users) { + List<byte[]> userEntries = SnapshotScannerHDFSAclStorage.getUserEntries(aclTable, user); + boolean remove = true; + for (byte[] entry : userEntries) { + if (PermissionStorage.isGlobalEntry(entry)) { + remove = false; + break; + } else if (PermissionStorage.isNamespaceEntry(entry) && Bytes + .equals(PermissionStorage.fromNamespaceEntry(entry), tableName.getNamespace())) { + remove = false; + break; + } else if (Bytes.equals(TableName.valueOf(entry).getNamespace(), + tableName.getNamespace())) { + remove = false; + break; + } + } + if (remove) { + removeUsers.add(user); + } + } + } + if (removeUsers.size() > 0) { + hdfsAclHelper.removeNamespaceAcl(tableName, removeUsers); + } + } + } + + @Override + public void postDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx, + String namespace) throws IOException { + if (checkInitialized()) { + try (Table aclTable = + ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { + SnapshotScannerHDFSAclStorage.deleteNamespaceHdfsAcl(aclTable, namespace); + } + Path tmpNsDir = pathHelper.getTmpNsDir(namespace); + if (fs.exists(tmpNsDir)) { + if (fs.listStatus(tmpNsDir).length == 0) { + fs.delete(tmpNsDir, false); + } else { + LOG.error("The tmp directory {} of namespace {} is not empty after delete namespace", + tmpNsDir, namespace); + } + } + } + } + + @Override + public void postGrant(ObserverContext<MasterCoprocessorEnvironment> c, + UserPermission userPermission, boolean mergeExistingPermissions) throws IOException { + if (!checkInitialized()) { + return; + } + try (Table aclTable = + c.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { + Configuration conf = c.getEnvironment().getConfiguration(); + String userName = userPermission.getUser(); + switch (userPermission.getAccessScope()) { + case GLOBAL: + UserPermission perm = getUserGlobalPermission(conf, userName); + if (containReadPermission(perm)) { + if (!isHdfsAclSet(aclTable, userName, Optional.empty(), Optional.empty())) { + List<byte[]> userEntries = + SnapshotScannerHDFSAclStorage.getUserEntries(aclTable, userName); + Set<String> skipNamespaces = new HashSet<>(); + Set<TableName> skipTables = new HashSet<>(); + for (byte[] entry : userEntries) { + if (PermissionStorage.isNamespaceEntry(entry)) { + skipNamespaces.add(PermissionStorage.fromNamespaceEntry(Bytes.toString(entry))); + } else if (!PermissionStorage.isGlobalEntry(entry)) { + skipTables.add(TableName.valueOf(entry)); + } + } + hdfsAclHelper.grantAcl(userPermission, skipNamespaces, skipTables); + SnapshotScannerHDFSAclStorage.addUserGlobalHdfsAcl(aclTable, userName); + } + } else { + revokeUserGlobalPermission(aclTable, userName, userPermission); + } + break; + case NAMESPACE: + String namespace = ((NamespacePermission) userPermission.getPermission()).getNamespace(); + UserPermission nsPerm = getUserNamespacePermission(conf, userName, namespace); + if (containReadPermission(nsPerm)) { + if (!isHdfsAclSet(aclTable, userName, Optional.of(namespace), Optional.empty())) { + List<byte[]> userEntries = + SnapshotScannerHDFSAclStorage.getUserEntries(aclTable, userName); + Set<TableName> skipTables = new HashSet<>(); + for (byte[] entry : userEntries) { + if (!PermissionStorage.isNamespaceEntry(entry) + && !PermissionStorage.isGlobalEntry(entry)) { + skipTables.add(TableName.valueOf(entry)); + } + } + hdfsAclHelper.grantAcl(userPermission, new HashSet<>(0), skipTables); + } + SnapshotScannerHDFSAclStorage.addUserNamespaceHdfsAcl(aclTable, userName, namespace); + } else { + revokeUserNamespacePermission(aclTable, userName, namespace, userPermission); + } + break; + case TABLE: + TableName tableName = ((TablePermission) userPermission.getPermission()).getTableName(); + UserPermission tPerm = getUserTablePermission(conf, userName, tableName); + TablePermission tablePermission = (TablePermission) tPerm.getPermission(); + if (tablePermission.hasFamily() || tablePermission.hasQualifier()) { + break; + } + if (containReadPermission(tPerm)) { + if (!isHdfsAclSet(aclTable, userName, Optional.empty(), Optional.of(tableName))) { + hdfsAclHelper.grantAcl(userPermission, new HashSet<>(0), new HashSet<>(0)); + } + SnapshotScannerHDFSAclStorage.addUserTableHdfsAcl(aclTable, userName, tableName); + } else { + revokeUserTablePermission(aclTable, userName, tableName, userPermission); + } + break; + case EMPTY: + default: + } + } + } + + @Override + public void postRevoke(ObserverContext<MasterCoprocessorEnvironment> c, + UserPermission userPermission) throws IOException { + if (checkInitialized()) { + try (Table aclTable = + c.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) { + String userName = userPermission.getUser(); + Configuration conf = c.getEnvironment().getConfiguration(); + switch (userPermission.getAccessScope()) { + case GLOBAL: + UserPermission perm = getUserGlobalPermission(conf, userName); + if (!containReadPermission(perm)) { + revokeUserGlobalPermission(aclTable, userName, userPermission); + } + break; + case NAMESPACE: + NamespacePermission nsPerm = (NamespacePermission) userPermission.getPermission(); + UserPermission userNsPerm = + getUserNamespacePermission(conf, userName, nsPerm.getNamespace()); + if (!containReadPermission(userNsPerm)) { + revokeUserNamespacePermission(aclTable, userName, nsPerm.getNamespace(), + userPermission); + } + break; + case TABLE: + TablePermission tPerm = (TablePermission) userPermission.getPermission(); + UserPermission userTablePerm = + getUserTablePermission(conf, userName, tPerm.getTableName()); + if (!containReadPermission(userTablePerm)) { + revokeUserTablePermission(aclTable, userName, tPerm.getTableName(), userPermission); + } + break; + default: + } + } + } + } + + private void revokeUserGlobalPermission(Table aclTable, String userName, + UserPermission userPermission) throws IOException { + if (SnapshotScannerHDFSAclStorage.hasUserGlobalHdfsAcl(aclTable, userName)) { + // remove user global acls but reserve ns and table acls + Set<String> skipNamespaces = new HashSet<>(); + Set<TableName> skipTables = new HashSet<>(); + List<byte[]> userEntries = SnapshotScannerHDFSAclStorage.getUserEntries(aclTable, userName); + for (byte[] entry : userEntries) { + if (PermissionStorage.isNamespaceEntry(entry)) { + skipNamespaces.add(Bytes.toString(PermissionStorage.fromNamespaceEntry(entry))); + } else if (!PermissionStorage.isGlobalEntry(entry)) { + skipTables.add(TableName.valueOf(entry)); + } + } + Set<TableName> filterTableNames = new HashSet<>(); + for (TableName tableName : skipTables) { + if (!skipNamespaces.contains(tableName.getNamespaceAsString())) { + filterTableNames.add(tableName); + } + } + hdfsAclHelper.revokeAcl(userPermission, skipNamespaces, filterTableNames); + SnapshotScannerHDFSAclStorage.deleteUserGlobalHdfsAcl(aclTable, userName); + } + } + + private void revokeUserNamespacePermission(Table aclTable, String userName, String namespace, + UserPermission userPermission) throws IOException { + // remove user ns acls but reserve table acls + if (SnapshotScannerHDFSAclStorage.hasUserNamespaceHdfsAcl(aclTable, userName, namespace)) { + if (!SnapshotScannerHDFSAclStorage.hasUserGlobalHdfsAcl(aclTable, userName)) { + Set<TableName> skipTables = new HashSet<>(); + List<byte[]> userEntries = SnapshotScannerHDFSAclStorage.getUserEntries(aclTable, userName); + for (byte[] entry : userEntries) { + if (!PermissionStorage.isNamespaceEntry(entry) + && !PermissionStorage.isGlobalEntry(entry)) { + skipTables.add(TableName.valueOf(entry)); + } + } + hdfsAclHelper.revokeAcl(userPermission, new HashSet<>(), skipTables); + } + SnapshotScannerHDFSAclStorage.deleteUserNamespaceHdfsAcl(aclTable, userName, namespace); + } + } + + private void revokeUserTablePermission(Table aclTable, String userName, TableName tableName, + UserPermission userPermission) throws IOException { + if (SnapshotScannerHDFSAclStorage.hasUserTableHdfsAcl(aclTable, userName, tableName)) { + if (!SnapshotScannerHDFSAclStorage.hasUserGlobalHdfsAcl(aclTable, userName) + && !SnapshotScannerHDFSAclStorage.hasUserNamespaceHdfsAcl(aclTable, userName, + tableName.getNamespaceAsString())) { + // remove table acls + hdfsAclHelper.revokeAcl(userPermission, new HashSet<>(0), new HashSet<>(0)); + } + SnapshotScannerHDFSAclStorage.deleteUserTableHdfsAcl(aclTable, userName, tableName); + } + } + + private boolean containReadPermission(UserPermission userPermission) { + if (userPermission != null) { + return Arrays.stream(userPermission.getPermission().getActions()) + .anyMatch(action -> action == Action.READ); + } + return false; + } + + private UserPermission getUserGlobalPermission(Configuration conf, String userName) + throws IOException { + List<UserPermission> permissions = PermissionStorage.getUserPermissions(conf, + PermissionStorage.ACL_GLOBAL_NAME, null, null, userName, true); + if (permissions != null && permissions.size() > 0) { + return permissions.get(0); + } + return null; + } + + private UserPermission getUserNamespacePermission(Configuration conf, String userName, + String namespace) throws IOException { + List<UserPermission> permissions = + PermissionStorage.getUserNamespacePermissions(conf, namespace, userName, true); + if (permissions != null && permissions.size() > 0) { + return permissions.get(0); + } + return null; + } + + private UserPermission getUserTablePermission(Configuration conf, String userName, + TableName tableName) throws IOException { + List<UserPermission> permissions = + PermissionStorage.getUserTablePermissions(conf, tableName, null, null, userName, true); + if (permissions != null && permissions.size() > 0) { + return permissions.get(0); + } + return null; + } + + /** + * Check if user global/namespace/table HDFS acls is already set to hfile + */ + private boolean isHdfsAclSet(Table aclTable, String userName, Optional<String> namespace, + Optional<TableName> tableName) throws IOException { + boolean isSet = SnapshotScannerHDFSAclStorage.hasUserGlobalHdfsAcl(aclTable, userName); + if (namespace.isPresent()) { + isSet = isSet || SnapshotScannerHDFSAclStorage.hasUserNamespaceHdfsAcl(aclTable, userName, + namespace.get()); + } + if (tableName.isPresent()) { + TableName table = tableName.get(); + isSet = isSet + || SnapshotScannerHDFSAclStorage.hasUserNamespaceHdfsAcl(aclTable, userName, + table.getNamespaceAsString()) + || SnapshotScannerHDFSAclStorage.hasUserTableHdfsAcl(aclTable, userName, table); + } + return isSet; + } + + private boolean checkInitialized() { + if (initialized) { + return true; + } else { + LOG.error("The SnapshotScannerHDFSAclController has not been initialized"); + return false; + } + } + + private User getActiveUser(ObserverContext<?> ctx) throws IOException { + // for non-rpc handling, fallback to system user + Optional<User> optionalUser = ctx.getCaller(); + if (optionalUser.isPresent()) { + return optionalUser.get(); + } + return userProvider.getCurrent(); + } + + protected static final class SnapshotScannerHDFSAclStorage { + static final byte[] HDFS_ACL_FAMILY = Bytes.toBytes("m"); + private static final byte[] HDFS_ACL_VALUE = Bytes.toBytes("R"); Review comment: The value 'R' has no specific meaning, if cell value is not null, it means that the user HDFS acls is set to hfiles. I will add doc here. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
