简单粗暴直接上代码
package com.bms.service;
import com.bms.entity.CreatePoliceReq;
import com.bms.entity.UpdatePoliceReq;
/**
* @author YeChunBo
* @time 2017年7月24日
*
* 类说明:Ranger 接口
*/
public interface Ranger {
/**
* 获取所有有效的策略
* @return
*/
public String getAllValidPolice();
/**
* 创建策略
* @param policeUser 策略对应的用户
* @param dbName :数据库,多个数据库用逗号分割(英文符)
* @param tableName :表,多个用逗号分割
* @param permissionsType 表,所对应的权限,多个用逗号分割,eg :drop, all, select, update, create, index, lock, alter
* @return
*/
public boolean createPolice(CreatePoliceReq createRequest);
/**
* 通过策略名称获取策略
* @param policyName
* @param policyType 策略类型:hive或hdfs/hbase
* @return
*/
public String getPolicyByName(String policyName, String policyType);
/**
* 通过policeName 删除策略
* @param policeName
* @return
*/
public boolean deletePoliceByPoliceName(String policeName);
/**
* 通过policeId 删除策略
* @param policeId
* @return
*/
public boolean deletePoliceByPoliceId(String policeId);
/**
* 修改策略
* @param updatePoliceReq
* @return
*/
public boolean updatePolicyById(UpdatePoliceReq updatePoliceReq);
/**
* 根据用户名,获取该用户对数据库的访问记录
* @param userName
* @param startDate
* @return
*/
public String getUserVisitInfo(String userName, String startDate);
}
package com.bms.service.rangerimpl;
import org.apache.ranger.admin.client.datatype.RESTResponse;
import org.apache.ranger.plugin.model.RangerPolicy;
import org.apache.ranger.plugin.util.RangerRESTUtils;
import org.apache.ranger.plugin.util.ServicePolicies;
import org.jboss.logging.Logger;
import com.bms.entity.CreatePoliceReq;
import com.bms.entity.UpdatePoliceReq;
import com.bms.service.Ranger;
import com.bms.utils.PropertyUtil;
import com.google.gson.Gson;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
/**
* @author YeChunBo
* @time 2017年7月24日
*
* 类说明:Ranger rest api 操作实现类
*/
public class RangerImpl implements Ranger {
private static Logger log = Logger.getLogger(RangerImpl.class);
private static final String EXPECTED_MIME_TYPE = PropertyUtil.getProperty("expected_mime_type");
private static String rangerBaseUrl = PropertyUtil.getProperty("rangerBaseUrl");
private static String service = PropertyUtil.getProperty("service"); // hive 的服务名
private static String adminUser = PropertyUtil.getProperty("adminUser");
private static String adminPwd = PropertyUtil.getProperty("adminPwd"); // ranger自己的登录密码(不是通过单点登录的密码)
public String getAllValidPolice() {
String url = rangerBaseUrl + "/service/plugins/policies/download/" + service;
log.info("getAllValidPolice, reqUrl=" + url);
ClientResponse response = null;
Client client = null;
String allPolice = null;
try {
client = Client.create();
WebResource webResource = client.resource(url)
.queryParam(RangerRESTUtils.REST_PARAM_LAST_KNOWN_POLICY_VERSION, Long.toString(68));
response = webResource.accept(RangerRESTUtils.REST_MIME_TYPE_JSON).get(ClientResponse.class);
if (response != null && response.getStatus() == 200) {
ServicePolicies ret = response.getEntity(ServicePolicies.class);
Gson gson = new Gson();
allPolice = gson.toJson(ret);
log.info("getAllValidPolice is success , the resp=" + gson.toJson(ret));
} else {
RESTResponse resp = RESTResponse.fromClientResponse(response);
log.warn("getAllValidPolice is fail," + resp.toString());
}
} catch (Exception e) {
log.error("getAllValidPolice is fail, errMassge=" + e.getMessage());
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.destroy();
}
}
return allPolice;
}
public String getPolicyByName(String policyName) {
String url = rangerBaseUrl + "/service/public/v2/api/service/" + service + "/policy/" + policyName;
log.info("getPolicyByName, reqUrl=" + url);
Client client = null;
ClientResponse response = null;
String jsonString = null;
try {
client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(adminUser, adminPwd));
WebResource webResource = client.resource(url);
response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
if (response.getStatus() == 200) {
jsonString = response.getEntity(String.class);
log.info("getPolicyByName is success, the response message is :" + jsonString);
} else {
RESTResponse resp = RESTResponse.fromClientResponse(response);
jsonString = resp.toJson();
log.warn("getPolicyByName is fail, the response message is :" + resp.toString());
}
} catch (Exception e) {
RESTResponse resp = RESTResponse.fromClientResponse(response);
jsonString = resp.toJson();
log.error("getPolicyByName is fail, the error message is :" + e.getMessage()
+ " and the response message is : " + jsonString);
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.destroy();
}
}
return jsonString;
}
public boolean createPolice(CreatePoliceReq req) {
boolean flag = false;
String url = rangerBaseUrl + "/service/public/v2/api/policy";
log.info("CreatePolice of reqUrl=" + url);
// 添加多个用户时将分割符逗号替换成下划线,用来生成新的策略名称
String newPoliceUser = req.getPoliceUser();
if (req.getPoliceUser().contains(",")) {
newPoliceUser = req.getPoliceUser().replace(",", "_");
}
String PoliceName = newPoliceUser + "_police";
ClientResponse response = null;
Client client = null;
try {
client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(adminUser, adminPwd));
WebResource webResource = client.resource(url);
Gson gson = new Gson();
RangerPolicy createOfPolicy = SupportRangerImpl.createOfPolicy(PoliceName, req.getPoliceUser(),
req.getDbName(), req.getTableName(), req.getPermissionsType());
response = webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE)
.type(RangerRESTUtils.REST_EXPECTED_MIME_TYPE)
.post(ClientResponse.class, gson.toJson(createOfPolicy));
if (response != null && response.getStatus() == 200) {
RangerPolicy rangerPolicy = response.getEntity(RangerPolicy.class);
log.info("Create Police is success, the police message is=" + rangerPolicy);
flag = true;
} else {
log.warn("Create Police is fail, the warn message is=" + response.toString());
}
} catch (Exception e) {
log.error("Create Police is fail, the error message is=" + e.getMessage());
flag = false;
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.destroy();
}
}
return flag;
}
public boolean deletePoliceByPoliceName(String policeName) {
boolean flag = false;
String url = rangerBaseUrl + "/service/public/v2/api/policy?servicename=" + service + "&policyname="
+ policeName;
log.info("DeletePoliceByPoliceName of requrl " + url);
ClientResponse response = null;
Client client = null;
try {
client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(adminUser, adminPwd));
WebResource webResource = client.resource(url);
webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).delete();
flag = true;
log.info("DeletePoliceByPoliceName is success.");
} catch (Exception e) {
log.error("DeletePoliceByPoliceName is fail. the errMassage is " + e.getMessage());
flag = false;
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.destroy();
}
}
return flag;
}
public boolean updatePolicyById(UpdatePoliceReq req) {
boolean flag = false;
String url = rangerBaseUrl + "/service/public/v2/api/policy/" + req.getPoliceId();
log.info("UpdatePolicyById of reqUrl=" + url);
RangerPolicy rangerPolicy = SupportRangerImpl.updateOfPolicy(req.getPoliceName(), req.getDbName(),
req.getTableName(), req.getPermissionsType(), req.getPoliceUser(), req.getColPermissionsType(),
req.getPoliceIsEnabled());
ClientResponse response = null;
Client client = null;
try {
client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(adminUser, adminPwd));
WebResource webResource = client.resource(url);
Gson gson = new Gson();
response = webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE)
.type(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).put(ClientResponse.class, gson.toJson(rangerPolicy));
if (response != null && response.getStatus() == 200) {
RangerPolicy policy = response.getEntity(RangerPolicy.class);
flag = true;
log.info("UpdatePolicyById is success, the police message is=" + policy);
} else {
log.warn("UpdatePolicyById is fail, the fail message is=" + response.toString());
}
} catch (Exception e) {
log.error("UpdatePolicyById is fail, the error message is=" + e.getMessage());
flag = false;
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.destroy();
}
}
return flag;
}
public boolean deletePoliceByPoliceId(String policeId) {
boolean flag = false;
String url = rangerBaseUrl + "/service/public/v2/api/policy/" + policeId;
log.info("DeletePoliceByPoliceId of reqUrl=" + url);
ClientResponse response = null;
Client client = null;
try {
client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(adminUser, adminPwd));
WebResource webResource = client.resource(url);
webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).delete();
flag = true;
} catch (Exception e) {
log.error("DeletePoliceByPoliceId is fail, the error Massage is=" + e.getMessage());
flag = false;
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.destroy();
}
}
return flag;
}
/**
* 这里的删除只是把用户设为不可见,不可见之后在配置策略时,这个用户就变成不可选,但是原先这个用户所拥有的策略还是存在的。真正删除这个用户后,其所拥有的策略才不存在。
* @param UserName
* @return
*/
public boolean deleteUserByUserName(String UserName) {
boolean flag = false;
String url = rangerBaseUrl + "/service/xusers/users/userName/" + UserName;
//service/xusers/secure/users/delete?forceDelete=true&
log.info("deleteUserByUserName of reqUrl=" + url);
ClientResponse response = null;
Client client = null;
try {
client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(adminUser, adminPwd));
WebResource webResource = client.resource(url);
webResource.accept(RangerRESTUtils.REST_EXPECTED_MIME_TYPE).delete();
flag = true;
} catch (Exception e) {
log.error("DeletePoliceByPoliceId is fail, the error Massage is=" + e.getMessage());
flag = false;
} finally {
if (response != null) {
response.close();
}
if (client != null) {
client.destroy();
}
}
return flag;
}
public static void main(String[] args) {
RangerImpl rangerImpl = new RangerImpl();
// 获取所有有效的策略
String allValidPolice = rangerImpl.getAllValidPolice();
System.out.println("system out: " + allValidPolice);
// 根据策略名获取
// String response = rangerImpl.getPolicyByName("test");
// System.out.println(response);
// 删除策略(根据策略名称)
// boolean flag = rangerImpl.deletePoliceByPoliceName("test");
// System.out.println(flag);
// 删除策略(根据策略ID)
// boolean flag = rangerImpl.deletePoliceByPoliceId("28");
// System.out.println(flag);
// 创建策略
// CreatePoliceReq createPoliceReq = new CreatePoliceReq();
// createPoliceReq.setPoliceUser("hive,hbase");
// createPoliceReq.setDbName("test1");
// //createPoliceReq.setTableName("test2");
// createPoliceReq.setPermissionsType("select,update");
// boolean createPoliceFlag = rangerImpl.createPolice(createPoliceReq);
// System.out.println(createPoliceFlag);
// 更新策略
// UpdatePoliceReq updatePoliceReq = new UpdatePoliceReq();
// updatePoliceReq.setPoliceName("12tUpdate13");
// updatePoliceReq.setPoliceId("36");
// updatePoliceReq.setDbName("test1");
// updatePoliceReq.setTableName("test,test2");
// updatePoliceReq.setPoliceUser("hive,hbase");
// updatePoliceReq.setPermissionsType("update");
// updatePoliceReq.setPoliceIsEnabled("0");
// boolean flag = rangerImpl.updatePolicyById(updatePoliceReq);
// System.out.println(flag);
boolean deleteFlag = rangerImpl.deleteUserByUserName("bmsoft_test");
System.out.println(deleteFlag);
}
}
package com.bms.service.rangerimpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.ranger.plugin.model.RangerPolicy;
import com.bms.utils.PropertyUtil;
/**
* @author YeChunBo
* @time 2017年7月25日
*
* 类说明 :Ranger 接口辅助类
*/
public class SupportRangerImpl {
private static String service = PropertyUtil.getProperty("service");// hive 的服务名
public static RangerPolicy updateOfPolicy(String policeName, String dbName, String tableName, String operatePermissionsType,
String policeUser, String colPermissionsType, String policeIsEnabled) {
RangerPolicy rangerPolicy = new RangerPolicy();
if (StringUtils.isNotBlank(policeName))
rangerPolicy.setName(policeName);
if (StringUtils.isBlank(policeIsEnabled) || "1".equals(policeIsEnabled))
rangerPolicy.setIsEnabled(true);
else if ("0".equals(policeIsEnabled))
rangerPolicy.setIsEnabled(false);
rangerPolicy.setService(service);
rangerPolicy.setIsAuditEnabled(true);
Map resources = new HashMap();
RangerPolicy.RangerPolicyResource dbRangerPolicyResource = new RangerPolicy.RangerPolicyResource();
RangerPolicy.RangerPolicyResource tablerRangerPolicyResource = new RangerPolicy.RangerPolicyResource();
RangerPolicy.RangerPolicyResource columRangerPolicyResource = new RangerPolicy.RangerPolicyResource();
dbRangerPolicyResource.setValue(dbName + ",policeUser_test");
dbRangerPolicyResource.setIsExcludes(false);
dbRangerPolicyResource.setIsRecursive(false);
tablerRangerPolicyResource.setValue(tableName);
if (StringUtils.isBlank(colPermissionsType))
columRangerPolicyResource.setValue("*");
else
columRangerPolicyResource.setValue(colPermissionsType);
resources.put("database", dbRangerPolicyResource);
resources.put("table", tablerRangerPolicyResource);
resources.put("column", columRangerPolicyResource);
List policyItems = new ArrayList();
RangerPolicy.RangerPolicyItem rangerPolicyItem = new RangerPolicy.RangerPolicyItem();
List users = new ArrayList();
if(StringUtils.isNotBlank(policeUser)){
String[] policeUserArr = policeUser.split("\\,");
if (policeUserArr.length > 0){
for (int i = 0; i < policeUserArr.length; i++) {
users.add(policeUserArr[i]);
}
}
rangerPolicyItem.setUsers(users);
}
List rangerPolicyItemAccesses = new ArrayList();
if(StringUtils.isNotBlank(operatePermissionsType)){
String[] operatePermArr = operatePermissionsType.split("\\,");
RangerPolicy.RangerPolicyItemAccess rangerPolicyItemAccess;
if (operatePermArr.length > 0){
for (int i = 0; i < operatePermArr.length; i++) {
rangerPolicyItemAccess = new RangerPolicy.RangerPolicyItemAccess();
rangerPolicyItemAccess.setType(operatePermArr[i]);
rangerPolicyItemAccess.setIsAllowed(Boolean.TRUE);
rangerPolicyItemAccesses.add(rangerPolicyItemAccess);
}
}
}
rangerPolicyItem.setAccesses(rangerPolicyItemAccesses);
policyItems.add(rangerPolicyItem);
rangerPolicy.setPolicyItems(policyItems);
rangerPolicy.setResources(resources);
return rangerPolicy;
}
/**
* 为创建策略而创建的策略对象
*
* @param PoliceName
* @param policeUser
* @param dbName
* @param tableName
* @param operatePermissionsType
* @return
*/
public static RangerPolicy createOfPolicy(String PoliceName, String policeUser, String dbName, String tableName,
String operatePermissionsType) {
RangerPolicy rangerPolicy = new RangerPolicy();
rangerPolicy.setService(service);
rangerPolicy.setName(PoliceName);
rangerPolicy.setIsAuditEnabled(true);
Map resources = new HashMap();
RangerPolicy.RangerPolicyResource dbRangerPolicyResource = new RangerPolicy.RangerPolicyResource();
RangerPolicy.RangerPolicyResource tablerRangerPolicyResource = new RangerPolicy.RangerPolicyResource();
RangerPolicy.RangerPolicyResource columRangerPolicyResource = new RangerPolicy.RangerPolicyResource();
String newPoliceUser = policeUser;
if (policeUser.contains(",")) {
newPoliceUser = policeUser.replace(",", "_");
}
ArrayList dbList = new ArrayList();
if (dbName.contains(",")) {
String[] dbArr = dbName.split(",");
for (String dbNameS : dbArr) {
dbList.add(dbNameS);
}
} else {
dbList.add(dbName);
}
dbList.add(newPoliceUser + "_autoCreateDb");// 默认为每个策略添加一个唯一的库,以区分创建了权限相同的策略
dbRangerPolicyResource.setValues(dbList);
tablerRangerPolicyResource.setValue(tableName);
columRangerPolicyResource.setValue("*");
resources.put("database", dbRangerPolicyResource);
resources.put("table", tablerRangerPolicyResource);
resources.put("column", columRangerPolicyResource);
List policyItems = new ArrayList();
RangerPolicy.RangerPolicyItem rangerPolicyItem = new RangerPolicy.RangerPolicyItem();
List users = new ArrayList();
String[] policeUserArr = policeUser.split("\\,");
if (policeUserArr.length > 0){
for (int i = 0; i < policeUserArr.length; i++) {
users.add(policeUserArr[i]);
}
}
rangerPolicyItem.setUsers(users);
List rangerPolicyItemAccesses = new ArrayList();
String[] operatePermArr = operatePermissionsType.split("\\,");
RangerPolicy.RangerPolicyItemAccess rangerPolicyItemAccess;
if (operatePermArr.length > 0){
for (int i = 0; i < operatePermArr.length; i++) {
rangerPolicyItemAccess = new RangerPolicy.RangerPolicyItemAccess();
rangerPolicyItemAccess.setType(operatePermArr[i]);
rangerPolicyItemAccess.setIsAllowed(Boolean.TRUE);
rangerPolicyItemAccesses.add(rangerPolicyItemAccess);
}
}
rangerPolicyItem.setAccesses(rangerPolicyItemAccesses);
policyItems.add(rangerPolicyItem);
rangerPolicy.setPolicyItems(policyItems);
rangerPolicy.setResources(resources);
return rangerPolicy;
}
}
package com.bms.entity;
/**
* @author YeChunBo
* @time 2017年7月25日
*
* 类说明
*
* 创建策略
* policeUser 策略对应的用户
* dbName :数据库,多个数据库用逗号分割
* tableName :表,多个用逗号分割, 默认拥有操作对应数据库中所有表
* permissionsType 表,所对应的权限,多个用逗号分割, 默认为拥有所有权限, 值为 all
* colPermissionsType = "*"; // 默认是所有列都可以访问
*/
public class CreatePoliceReq {
private String policeUser;
private String dbName;
private String tableName = "*";
private String permissionsType = "all";
private String colPermissionsType = "*"; // 默认是所有列都可以访问
public String getPoliceUser() {
return policeUser;
}
public void setPoliceUser(String policeUser) {
this.policeUser = policeUser;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getPermissionsType() {
return permissionsType;
}
public void setPermissionsType(String permissionsType) {
this.permissionsType = permissionsType;
}
public String getColPermissionsType() {
return colPermissionsType;
}
public void setColPermissionsType(String colPermissionsType) {
this.colPermissionsType = colPermissionsType;
}
@Override
public String toString() {
return "CreatePoliceReq [policeUser=" + policeUser + ", dbName=" + dbName + ", tableName=" + tableName
+ ", permissionsType=" + permissionsType + ", colPermissionsType=" + colPermissionsType + "]";
}
}
实体类:ResponseResult
package com.bms.entity;
/**
* @author YeChunBo
* @time 2017年7月25日
*
* 类说明
*/
public class ResponseResult {
private boolean result;
private String message;
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "ResponseResult [result=" + result + ", message=" + message + "]";
}
}
实体类:UpdatePoliceReq
package com.bms.entity;
/**
* @author YeChunBo
* @time 2017年7月25日
*
* 类说明
* 更新策略
* policeName
* id
* dbName
* tableName 默认拥有所有表
* permissionsType 表的操作权限,eg:select,update...
* policeUser
* colPermissionsType 列的操作权限,默认拥有所有权限
* policeIsEnabled 该策略是否有效,默认有效:1 有效,0 无效
*/
public class UpdatePoliceReq {
private String policeName;
private String policeId;
private String dbName;
private String tableName = "*";
private String permissionsType;
private String policeUser;
private String colPermissionsType = "*";
private String policeIsEnabled = "1";
private String service;
// hfds 相关属性
private String hdfsResourcePath;
// hbase 相关属性
private String hbaseTableName;
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getHdfsResourcePath() {
return hdfsResourcePath;
}
public void setHdfsResourcePath(String hdfsResourcePath) {
this.hdfsResourcePath = hdfsResourcePath;
}
public String getPoliceName() {
return policeName;
}
public void setPoliceName(String policeName) {
this.policeName = policeName;
}
public String getPoliceId() {
return policeId;
}
public void setPoliceId(String policeId) {
this.policeId = policeId;
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getPermissionsType() {
return permissionsType;
}
public void setPermissionsType(String permissionsType) {
this.permissionsType = permissionsType;
}
public String getPoliceUser() {
return policeUser;
}
public void setPoliceUser(String policeUser) {
this.policeUser = policeUser;
}
public String getColPermissionsType() {
return colPermissionsType;
}
public void setColPermissionsType(String colPermissionsType) {
this.colPermissionsType = colPermissionsType;
}
public String getPoliceIsEnabled() {
return policeIsEnabled;
}
public void setPoliceIsEnabled(String policeIsEnabled) {
this.policeIsEnabled = policeIsEnabled;
}
public String getHbaseTableName() {
return hbaseTableName;
}
public void setHbaseTableName(String hbaseTableName) {
this.hbaseTableName = hbaseTableName;
}
@Override
public String toString() {
return "UpdatePoliceReq [policeName=" + policeName + ", policeId=" + policeId + ", dbName=" + dbName
+ ", tableName=" + tableName + ", permissionsType=" + permissionsType + ", policeUser=" + policeUser
+ ", colPermissionsType=" + colPermissionsType + ", policeIsEnabled=" + policeIsEnabled + ", service="
+ service + ", hdfsResourcePath=" + hdfsResourcePath + ", hbaseTableName=" + hbaseTableName + "]";
}
}
4.0.0
Ranger
Ranger
0.0.1-SNAPSHOT
com.google.code.gson
gson
2.2.4
org.apache.ranger
ranger-plugins-common
0.6.0
jdk.tools
jdk.tools
1.8
system
${JAVA_HOME}/lib/tools.jar
log4j
log4j
1.2.17
jar
参考文档
源码:https://github.com/yechunbo/RangerALdapApi.git
https://cwiki.apache.org/confluence/display/RANGER/Apache+Ranger+0.6±+REST+APIs+for+Service+Definition%2C+Service+and+Policy+Management#ApacheRanger0.6-RESTAPIsforServiceDefinition,ServiceandPolicyManagement-UpdatePolicybyid