Search in sources :

Example 26 with XXTrxLog

use of org.apache.ranger.entity.XXTrxLog in project ranger by apache.

the class UserMgr method updateUser.

/**
 * @param userProfile
 * @return
 */
public XXPortalUser updateUser(VXPortalUser userProfile) {
    XXPortalUser gjUser = daoManager.getXXPortalUser().getById(userProfile.getId());
    if (gjUser == null) {
        logger.error("updateUser(). User not found. userProfile=" + userProfile);
        return null;
    }
    checkAccess(gjUser);
    rangerBizUtil.blockAuditorRoleUser();
    boolean updateUser = false;
    // status
    if (userProfile.getStatus() != gjUser.getStatus()) {
        updateUser = true;
    }
    // Allowing email address update even when its set to empty.
    // emailAddress
    String emailAddress = userProfile.getEmailAddress();
    if (stringUtil.isEmpty(emailAddress)) {
        userProfile.setEmailAddress(null);
        updateUser = true;
    } else {
        if (stringUtil.validateEmail(emailAddress)) {
            XXPortalUser checkUser = daoManager.getXXPortalUser().findByEmailAddress(emailAddress);
            if (checkUser != null) {
                String loginId = userProfile.getLoginId();
                if (loginId == null) {
                    throw restErrorUtil.createRESTException("Invalid user, please provide valid " + "username.", MessageEnums.INVALID_INPUT_DATA);
                } else if (!loginId.equals(checkUser.getLoginId())) {
                    throw restErrorUtil.createRESTException("The email address " + "you've provided already exists in system.", MessageEnums.INVALID_INPUT_DATA);
                } else {
                    userProfile.setEmailAddress(emailAddress);
                    updateUser = true;
                }
            } else {
                userProfile.setEmailAddress(emailAddress);
                updateUser = true;
            }
        } else {
            throw restErrorUtil.createRESTException("Please provide valid email address.", MessageEnums.INVALID_INPUT_DATA);
        }
    }
    // firstName
    if ("null".equalsIgnoreCase(userProfile.getFirstName())) {
        userProfile.setFirstName("");
    }
    if (!stringUtil.isEmpty(userProfile.getFirstName()) && !userProfile.getFirstName().equals(gjUser.getFirstName())) {
        userProfile.setFirstName(stringUtil.toCamelCaseAllWords(userProfile.getFirstName()));
        updateUser = true;
    }
    if ("null".equalsIgnoreCase(userProfile.getLastName())) {
        userProfile.setLastName("");
    }
    if (!stringUtil.isEmpty(userProfile.getLastName()) && !userProfile.getLastName().equals(gjUser.getLastName())) {
        userProfile.setLastName(stringUtil.toCamelCaseAllWords(userProfile.getLastName()));
        updateUser = true;
    }
    // publicScreenName
    if (userProfile.getFirstName() != null && userProfile.getLastName() != null && !userProfile.getFirstName().trim().isEmpty() && !userProfile.getLastName().trim().isEmpty()) {
        userProfile.setPublicScreenName(userProfile.getFirstName() + " " + userProfile.getLastName());
        updateUser = true;
    } else {
        userProfile.setPublicScreenName(gjUser.getLoginId());
        updateUser = true;
    }
    // notes
    /*
		 * if (!stringUtil.isEmpty(userProfile.getNotes()) &&
		 * !userProfile.getNotes().equalsIgnoreCase(gjUser.getNotes())) {
		 * updateUser = true; }
		 */
    // userRoleList
    updateRoles(userProfile.getId(), userProfile.getUserRoleList());
    if (updateUser) {
        List<XXTrxLog> trxLogList = xPortalUserService.getTransactionLog(userProfile, gjUser, "update");
        userProfile.setPassword(gjUser.getPassword());
        xPortalUserService.updateResource(userProfile);
        sessionMgr.resetUserSessionForProfiles(ContextUtil.getCurrentUserSession());
        rangerBizUtil.createTrxLog(trxLogList);
    }
    return gjUser;
}
Also used : XXPortalUser(org.apache.ranger.entity.XXPortalUser) VXString(org.apache.ranger.view.VXString) XXTrxLog(org.apache.ranger.entity.XXTrxLog)

Example 27 with XXTrxLog

use of org.apache.ranger.entity.XXTrxLog in project ranger by apache.

the class XUserMgr method createServiceConfigUser.

@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
public VXUser createServiceConfigUser(String userName) {
    if (userName == null || "null".equalsIgnoreCase(userName) || userName.trim().isEmpty()) {
        logger.error("User Name: " + userName);
        throw restErrorUtil.createRESTException("Please provide a valid username.", MessageEnums.INVALID_INPUT_DATA);
    }
    VXUser vXUser = null;
    VXPortalUser vXPortalUser = null;
    XXUser xxUser = daoManager.getXXUser().findByUserName(userName);
    XXPortalUser xXPortalUser = daoManager.getXXPortalUser().findByLoginId(userName);
    String actualPassword = "";
    if (xxUser != null) {
        vXUser = xUserService.populateViewBean(xxUser);
        return vXUser;
    }
    if (xxUser == null) {
        vXUser = new VXUser();
        vXUser.setName(userName);
        vXUser.setUserSource(RangerCommonEnums.USER_EXTERNAL);
        vXUser.setDescription(vXUser.getName());
        actualPassword = vXUser.getPassword();
    }
    if (xXPortalUser == null) {
        vXPortalUser = new VXPortalUser();
        vXPortalUser.setLoginId(userName);
        vXPortalUser.setEmailAddress(vXUser.getEmailAddress());
        vXPortalUser.setFirstName(vXUser.getFirstName());
        vXPortalUser.setLastName(vXUser.getLastName());
        vXPortalUser.setPassword(vXUser.getPassword());
        vXPortalUser.setUserSource(RangerCommonEnums.USER_EXTERNAL);
        ArrayList<String> roleList = new ArrayList<String>();
        roleList.add(RangerConstants.ROLE_USER);
        vXPortalUser.setUserRoleList(roleList);
        xXPortalUser = userMgr.mapVXPortalUserToXXPortalUser(vXPortalUser);
        xXPortalUser = userMgr.createUser(xXPortalUser, RangerCommonEnums.STATUS_ENABLED, roleList);
    }
    VXUser createdXUser = null;
    if (xxUser == null && vXUser != null) {
        try {
            createdXUser = xUserService.createResource(vXUser);
        } catch (Exception ex) {
            logger.error("Error creating user: " + vXUser.getName(), ex);
        }
    }
    if (createdXUser != null) {
        try {
            logger.info("User created: " + createdXUser.getName());
            createdXUser.setPassword(actualPassword);
            List<XXTrxLog> trxLogList = xUserService.getTransactionLog(createdXUser, "create");
            String hiddenPassword = PropertiesUtil.getProperty("ranger.password.hidden", "*****");
            createdXUser.setPassword(hiddenPassword);
            xaBizUtil.createTrxLog(trxLogList);
            if (xXPortalUser != null) {
                vXPortalUser = userMgr.mapXXPortalUserToVXPortalUserForDefaultAccount(xXPortalUser);
                assignPermissionToUser(vXPortalUser, true);
            }
        } catch (Exception ex) {
            logger.error("Error while assigning permissions to user: " + createdXUser.getName(), ex);
        }
    } else {
        xxUser = daoManager.getXXUser().findByUserName(userName);
        if (xxUser != null) {
            createdXUser = xUserService.populateViewBean(xxUser);
        }
    }
    return createdXUser;
}
Also used : XXUser(org.apache.ranger.entity.XXUser) XXPortalUser(org.apache.ranger.entity.XXPortalUser) ArrayList(java.util.ArrayList) XXTrxLog(org.apache.ranger.entity.XXTrxLog) Transactional(org.springframework.transaction.annotation.Transactional)

Example 28 with XXTrxLog

use of org.apache.ranger.entity.XXTrxLog in project ranger by apache.

the class ServiceDBStore method updatePolicy.

@Override
public RangerPolicy updatePolicy(RangerPolicy policy) throws Exception {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceDBStore.updatePolicy(" + policy + ")");
    }
    XXPolicy xxExisting = daoMgr.getXXPolicy().getById(policy.getId());
    RangerPolicy existing = policyService.getPopulatedViewObject(xxExisting);
    if (existing == null) {
        throw new Exception("no policy exists with ID=" + policy.getId());
    }
    RangerService service = getServiceByName(policy.getService());
    if (service == null) {
        throw new Exception("service does not exist - name=" + policy.getService());
    }
    XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(service.getType());
    if (xServiceDef == null) {
        throw new Exception("service-def does not exist - name=" + service.getType());
    }
    if (!StringUtils.equalsIgnoreCase(existing.getService(), policy.getService())) {
        throw new Exception("policy id=" + policy.getId() + " already exists in service " + existing.getService() + ". It can not be moved to service " + policy.getService());
    }
    boolean renamed = !StringUtils.equalsIgnoreCase(policy.getName(), existing.getName());
    if (renamed) {
        XXPolicy newNamePolicy = daoMgr.getXXPolicy().findByNameAndServiceId(policy.getName(), service.getId());
        if (newNamePolicy != null) {
            throw new Exception("another policy already exists with name '" + policy.getName() + "'. ID=" + newNamePolicy.getId());
        }
    }
    Map<String, RangerPolicyResource> newResources = policy.getResources();
    List<RangerPolicyItem> policyItems = policy.getPolicyItems();
    List<RangerPolicyItem> denyPolicyItems = policy.getDenyPolicyItems();
    List<RangerPolicyItem> allowExceptions = policy.getAllowExceptions();
    List<RangerPolicyItem> denyExceptions = policy.getDenyExceptions();
    List<RangerDataMaskPolicyItem> dataMaskPolicyItems = policy.getDataMaskPolicyItems();
    List<RangerRowFilterPolicyItem> rowFilterItems = policy.getRowFilterPolicyItems();
    List<String> policyLabels = policy.getPolicyLabels();
    policy.setCreateTime(xxExisting.getCreateTime());
    policy.setGuid(xxExisting.getGuid());
    policy.setVersion(xxExisting.getVersion());
    List<XXTrxLog> trxLogList = policyService.getTransactionLog(policy, xxExisting, RangerPolicyService.OPERATION_UPDATE_CONTEXT);
    updatePolicySignature(policy);
    boolean isTagVersionUpdateNeeded = false;
    if (EmbeddedServiceDefsUtil.EMBEDDED_SERVICEDEF_TAG_NAME.equals(service.getType())) {
        isTagVersionUpdateNeeded = existing.getIsEnabled() ? !policy.getIsEnabled() : policy.getIsEnabled();
        isTagVersionUpdateNeeded = isTagVersionUpdateNeeded || !StringUtils.equals(existing.getResourceSignature(), policy.getResourceSignature());
    }
    policy = policyService.update(policy);
    XXPolicy newUpdPolicy = daoMgr.getXXPolicy().getById(policy.getId());
    deleteExistingPolicyResources(policy);
    deleteExistingPolicyItems(policy);
    deleteExistingPolicyLabel(policy);
    createNewResourcesForPolicy(policy, newUpdPolicy, newResources);
    createNewPolicyItemsForPolicy(policy, newUpdPolicy, policyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW);
    createNewPolicyItemsForPolicy(policy, newUpdPolicy, denyPolicyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY);
    createNewPolicyItemsForPolicy(policy, newUpdPolicy, allowExceptions, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW_EXCEPTIONS);
    createNewPolicyItemsForPolicy(policy, newUpdPolicy, denyExceptions, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY_EXCEPTIONS);
    createNewDataMaskPolicyItemsForPolicy(policy, newUpdPolicy, dataMaskPolicyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK);
    createNewRowFilterPolicyItemsForPolicy(policy, newUpdPolicy, rowFilterItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER);
    createNewLabelsForPolicy(newUpdPolicy, policyLabels);
    handlePolicyUpdate(service, isTagVersionUpdateNeeded);
    RangerPolicy updPolicy = policyService.getPopulatedViewObject(newUpdPolicy);
    dataHistService.createObjectDataHistory(updPolicy, RangerDataHistService.ACTION_UPDATE);
    bizUtil.createTrxLog(trxLogList);
    return updPolicy;
}
Also used : XXServiceDef(org.apache.ranger.entity.XXServiceDef) RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) RangerRowFilterPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem) VXString(org.apache.ranger.view.VXString) XXTrxLog(org.apache.ranger.entity.XXTrxLog) XXPolicy(org.apache.ranger.entity.XXPolicy) RangerPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) JSONException(org.codehaus.jettison.json.JSONException) RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerDataMaskPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem) RangerService(org.apache.ranger.plugin.model.RangerService)

Example 29 with XXTrxLog

use of org.apache.ranger.entity.XXTrxLog in project ranger by apache.

the class ServiceDBStore method createPolicy.

@Override
public RangerPolicy createPolicy(RangerPolicy policy) throws Exception {
    RangerService service = getServiceByName(policy.getService());
    if (service == null) {
        throw new Exception("service does not exist - name=" + policy.getService());
    }
    XXServiceDef xServiceDef = daoMgr.getXXServiceDef().findByName(service.getType());
    if (xServiceDef == null) {
        throw new Exception("service-def does not exist - name=" + service.getType());
    }
    XXPolicy existing = daoMgr.getXXPolicy().findByNameAndServiceId(policy.getName(), service.getId());
    if (existing != null) {
        throw new Exception("policy already exists: ServiceName=" + policy.getService() + "; PolicyName=" + policy.getName() + ". ID=" + existing.getId());
    }
    Map<String, RangerPolicyResource> resources = policy.getResources();
    List<RangerPolicyItem> policyItems = policy.getPolicyItems();
    List<RangerPolicyItem> denyPolicyItems = policy.getDenyPolicyItems();
    List<RangerPolicyItem> allowExceptions = policy.getAllowExceptions();
    List<RangerPolicyItem> denyExceptions = policy.getDenyExceptions();
    List<RangerDataMaskPolicyItem> dataMaskItems = policy.getDataMaskPolicyItems();
    List<RangerRowFilterPolicyItem> rowFilterItems = policy.getRowFilterPolicyItems();
    List<String> policyLabels = policy.getPolicyLabels();
    policy.setVersion(Long.valueOf(1));
    updatePolicySignature(policy);
    if (populateExistingBaseFields) {
        assignedIdPolicyService.setPopulateExistingBaseFields(true);
        daoMgr.getXXPolicy().setIdentityInsert(true);
        policy = assignedIdPolicyService.create(policy);
        daoMgr.getXXPolicy().setIdentityInsert(false);
        daoMgr.getXXPolicy().updateSequence();
        assignedIdPolicyService.setPopulateExistingBaseFields(false);
    } else {
        policy = policyService.create(policy);
    }
    XXPolicy xCreatedPolicy = daoMgr.getXXPolicy().getById(policy.getId());
    createNewResourcesForPolicy(policy, xCreatedPolicy, resources);
    createNewPolicyItemsForPolicy(policy, xCreatedPolicy, policyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW);
    createNewPolicyItemsForPolicy(policy, xCreatedPolicy, denyPolicyItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY);
    createNewPolicyItemsForPolicy(policy, xCreatedPolicy, allowExceptions, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ALLOW_EXCEPTIONS);
    createNewPolicyItemsForPolicy(policy, xCreatedPolicy, denyExceptions, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DENY_EXCEPTIONS);
    createNewDataMaskPolicyItemsForPolicy(policy, xCreatedPolicy, dataMaskItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_DATAMASK);
    createNewRowFilterPolicyItemsForPolicy(policy, xCreatedPolicy, rowFilterItems, xServiceDef, RangerPolicyItemEvaluator.POLICY_ITEM_TYPE_ROWFILTER);
    createNewLabelsForPolicy(xCreatedPolicy, policyLabels);
    handlePolicyUpdate(service, true);
    RangerPolicy createdPolicy = policyService.getPopulatedViewObject(xCreatedPolicy);
    dataHistService.createObjectDataHistory(createdPolicy, RangerDataHistService.ACTION_CREATE);
    List<XXTrxLog> trxLogList = policyService.getTransactionLog(createdPolicy, RangerPolicyService.OPERATION_CREATE_CONTEXT);
    bizUtil.createTrxLog(trxLogList);
    return createdPolicy;
}
Also used : XXServiceDef(org.apache.ranger.entity.XXServiceDef) RangerPolicyResource(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyResource) RangerRowFilterPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerRowFilterPolicyItem) VXString(org.apache.ranger.view.VXString) XXTrxLog(org.apache.ranger.entity.XXTrxLog) XXPolicy(org.apache.ranger.entity.XXPolicy) RangerPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerPolicyItem) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) JSONException(org.codehaus.jettison.json.JSONException) RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerDataMaskPolicyItem(org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem) RangerService(org.apache.ranger.plugin.model.RangerService)

Example 30 with XXTrxLog

use of org.apache.ranger.entity.XXTrxLog in project ranger by apache.

the class ServiceREST method importPoliciesFromFile.

@POST
@Path("/policies/importPoliciesFromFile")
@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
@Produces({ "application/json", "application/xml" })
@PreAuthorize("@rangerPreAuthSecurityHandler.isAdminOrKeyAdminRole()")
public void importPoliciesFromFile(@Context HttpServletRequest request, @FormDataParam("servicesMapJson") InputStream serviceMapStream, @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @QueryParam("isOverride") Boolean isOverride) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("==> ServiceREST.importPoliciesFromFile()");
    }
    RangerPerfTracer perf = null;
    String metaDataInfo = null;
    List<XXTrxLog> trxLogListError = new ArrayList<XXTrxLog>();
    XXTrxLog xxTrxLogError = new XXTrxLog();
    try {
        if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
            perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.importPoliciesFromFile()");
        }
        List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
        XXTrxLog xxTrxLog = new XXTrxLog();
        xxTrxLog.setAction("IMPORT START");
        xxTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
        xxTrxLog.setPreviousValue("IMPORT START");
        trxLogList.add(xxTrxLog);
        bizUtil.createTrxLog(trxLogList);
        if (isOverride == null) {
            isOverride = false;
        }
        List<String> serviceNameList = new ArrayList<String>();
        String serviceType = null;
        List<String> serviceTypeList = null;
        SearchFilter filter = searchUtil.getSearchFilter(request, policyService.sortFields);
        if (StringUtils.isNotEmpty(request.getParameter(PARAM_SERVICE_TYPE))) {
            serviceType = request.getParameter(PARAM_SERVICE_TYPE);
        }
        if (StringUtils.isNotEmpty(serviceType)) {
            serviceTypeList = new ArrayList<String>(Arrays.asList(serviceType.split(",")));
        }
        List<RangerService> rangerServiceList = null;
        List<RangerService> rangerServiceLists = new ArrayList<RangerService>();
        if (CollectionUtils.isNotEmpty(serviceTypeList)) {
            for (String s : serviceTypeList) {
                filter.removeParam(PARAM_SERVICE_TYPE);
                filter.setParam(PARAM_SERVICE_TYPE, s.trim());
                rangerServiceList = getServices(filter);
                rangerServiceLists.addAll(rangerServiceList);
            }
        }
        if (!CollectionUtils.sizeIsEmpty(rangerServiceLists)) {
            for (RangerService rService : rangerServiceLists) {
                if (StringUtils.isNotEmpty(rService.getName())) {
                    serviceNameList.add(rService.getName());
                }
            }
        }
        Map<String, String> servicesMappingMap = new LinkedHashMap<String, String>();
        List<String> sourceServices = new ArrayList<String>();
        List<String> destinationServices = new ArrayList<String>();
        if (serviceMapStream != null) {
            servicesMappingMap = svcStore.getServiceMap(serviceMapStream);
        }
        if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) {
            for (Entry<String, String> map : servicesMappingMap.entrySet()) {
                String sourceServiceName = null;
                String destinationServiceName = null;
                if (StringUtils.isNotEmpty(map.getKey().trim()) && StringUtils.isNotEmpty(map.getValue().trim())) {
                    sourceServiceName = map.getKey().trim();
                    destinationServiceName = map.getValue().trim();
                } else {
                    LOG.error("Source service or destonation service name is not provided!!");
                    throw restErrorUtil.createRESTException("Source service or destonation service name is not provided!!");
                }
                if (StringUtils.isNotEmpty(sourceServiceName) && StringUtils.isNotEmpty(destinationServiceName)) {
                    sourceServices.add(sourceServiceName);
                    destinationServices.add(destinationServiceName);
                }
            }
        }
        String fileName = fileDetail.getFileName();
        int totalPolicyCreate = 0;
        Map<String, RangerPolicy> policiesMap = new LinkedHashMap<String, RangerPolicy>();
        List<String> dataFileSourceServices = new ArrayList<String>();
        if (fileName.endsWith("json")) {
            try {
                RangerExportPolicyList rangerExportPolicyList = null;
                List<RangerPolicy> policies = null;
                Gson gson = new Gson();
                String policiesString = IOUtils.toString(uploadedInputStream);
                policiesString = policiesString.trim();
                if (StringUtils.isNotEmpty(policiesString)) {
                    gson.fromJson(policiesString, RangerExportPolicyList.class);
                    rangerExportPolicyList = new ObjectMapper().readValue(policiesString, RangerExportPolicyList.class);
                } else {
                    LOG.error("Provided json file is empty!!");
                    throw restErrorUtil.createRESTException("Provided json file is empty!!");
                }
                if (rangerExportPolicyList != null && !CollectionUtils.sizeIsEmpty(rangerExportPolicyList.getMetaDataInfo())) {
                    metaDataInfo = new ObjectMapper().writeValueAsString(rangerExportPolicyList.getMetaDataInfo());
                } else {
                    LOG.info("metadata info is not provided!!");
                }
                if (rangerExportPolicyList != null && !CollectionUtils.sizeIsEmpty(rangerExportPolicyList.getPolicies())) {
                    policies = rangerExportPolicyList.getPolicies();
                } else {
                    LOG.error("Provided json file does not contain any policy!!");
                    throw restErrorUtil.createRESTException("Provided json file does not contain any policy!!");
                }
                if (CollectionUtils.sizeIsEmpty(servicesMappingMap) && isOverride) {
                    if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) {
                        for (RangerPolicy policyInJson : policies) {
                            if (policyInJson != null) {
                                if (StringUtils.isNotEmpty(policyInJson.getService().trim())) {
                                    String serviceName = policyInJson.getService().trim();
                                    if (CollectionUtils.isNotEmpty(serviceNameList) && serviceNameList.contains(serviceName)) {
                                        sourceServices.add(serviceName);
                                        destinationServices.add(serviceName);
                                    } else if (CollectionUtils.isEmpty(serviceNameList)) {
                                        sourceServices.add(serviceName);
                                        destinationServices.add(serviceName);
                                    }
                                } else {
                                    LOG.error("Service Name or Policy Name is not provided!!");
                                    throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!");
                                }
                            }
                        }
                    }
                } else if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) {
                    if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) {
                        for (RangerPolicy policyInJson : policies) {
                            if (policyInJson != null) {
                                if (StringUtils.isNotEmpty(policyInJson.getService().trim())) {
                                    dataFileSourceServices.add(policyInJson.getService().trim());
                                } else {
                                    LOG.error("Service Name or Policy Name is not provided!!");
                                    throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!");
                                }
                            }
                        }
                        if (!dataFileSourceServices.containsAll(sourceServices)) {
                            LOG.error("Json File does not contain sepcified source service name.");
                            throw restErrorUtil.createRESTException("Json File does not contain sepcified source service name.");
                        }
                    }
                }
                String updateIfExists = request.getParameter(PARAM_UPDATE_IF_EXISTS);
                String polResource = request.getParameter(SearchFilter.POL_RESOURCE);
                if (updateIfExists == null || updateIfExists.isEmpty()) {
                    updateIfExists = "false";
                } else if (updateIfExists.equalsIgnoreCase("true")) {
                    isOverride = false;
                }
                if (isOverride && "false".equalsIgnoreCase(updateIfExists) && StringUtils.isEmpty(polResource)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Deleting Policy from provided services in servicesMapJson file...");
                    }
                    if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) {
                        deletePoliciesProvidedInServiceMap(sourceServices, destinationServices);
                    }
                }
                if ("true".equalsIgnoreCase(updateIfExists) && StringUtils.isNotEmpty(polResource)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Deleting Policy from provided services in servicesMapJson file for specific resource...");
                    }
                    if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) {
                        deletePoliciesForResource(sourceServices, destinationServices, polResource, request, policies);
                    }
                }
                if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) {
                    for (RangerPolicy policyInJson : policies) {
                        if (policyInJson != null) {
                            policiesMap = svcStore.createPolicyMap(servicesMappingMap, sourceServices, destinationServices, policyInJson, policiesMap);
                        }
                    }
                }
                if (!CollectionUtils.sizeIsEmpty(policiesMap.entrySet())) {
                    for (Entry<String, RangerPolicy> entry : policiesMap.entrySet()) {
                        RangerPolicy policy = entry.getValue();
                        if (policy != null) {
                            if (!CollectionUtils.isEmpty(serviceNameList)) {
                                for (String service : serviceNameList) {
                                    if (StringUtils.isNotEmpty(service.trim()) && StringUtils.isNotEmpty(policy.getService().trim())) {
                                        if (policy.getService().trim().equalsIgnoreCase(service.trim())) {
                                            if (updateIfExists != null && !updateIfExists.isEmpty()) {
                                                request.setAttribute(PARAM_SERVICE_NAME, policy.getService());
                                                request.setAttribute(PARAM_POLICY_NAME, policy.getName());
                                            }
                                            createPolicy(policy, request);
                                            totalPolicyCreate = totalPolicyCreate + 1;
                                            if (LOG.isDebugEnabled()) {
                                                LOG.debug("Policy " + policy.getName() + " created successfully.");
                                            }
                                            break;
                                        }
                                    } else {
                                        LOG.error("Service Name or Policy Name is not provided!!");
                                        throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!");
                                    }
                                }
                            } else {
                                if (updateIfExists != null && !updateIfExists.isEmpty()) {
                                    request.setAttribute(PARAM_SERVICE_NAME, policy.getService());
                                    request.setAttribute(PARAM_POLICY_NAME, policy.getName());
                                }
                                createPolicy(policy, request);
                                totalPolicyCreate = totalPolicyCreate + 1;
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Policy " + policy.getName() + " created successfully.");
                                }
                            }
                        }
                    }
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Total Policy Created From Json file : " + totalPolicyCreate);
                    }
                    if (!(totalPolicyCreate > 0)) {
                        LOG.error("zero policy is created from provided data file!!");
                        throw restErrorUtil.createRESTException("zero policy is created from provided data file!!");
                    }
                }
            } catch (IOException e) {
                LOG.error(e.getMessage());
                throw restErrorUtil.createRESTException(e.getMessage());
            }
        } else {
            LOG.error("Provided file format is not supported!!");
            throw restErrorUtil.createRESTException("Provided file format is not supported!!");
        }
    } catch (JsonSyntaxException ex) {
        LOG.error("Provided json file is not valid!!", ex);
        xxTrxLogError.setAction("IMPORT ERROR");
        xxTrxLogError.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
        if (StringUtils.isNotEmpty(metaDataInfo)) {
            xxTrxLogError.setPreviousValue(metaDataInfo);
        }
        trxLogListError.add(xxTrxLogError);
        bizUtil.createTrxLog(trxLogListError);
        throw restErrorUtil.createRESTException(ex.getMessage());
    } catch (WebApplicationException excp) {
        LOG.error("Error while importing policy from file!!", excp);
        xxTrxLogError.setAction("IMPORT ERROR");
        xxTrxLogError.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
        if (StringUtils.isNotEmpty(metaDataInfo)) {
            xxTrxLogError.setPreviousValue(metaDataInfo);
        }
        trxLogListError.add(xxTrxLogError);
        bizUtil.createTrxLog(trxLogListError);
        throw excp;
    } catch (Throwable excp) {
        LOG.error("Error while importing policy from file!!", excp);
        xxTrxLogError.setAction("IMPORT ERROR");
        xxTrxLogError.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
        if (StringUtils.isNotEmpty(metaDataInfo)) {
            xxTrxLogError.setPreviousValue(metaDataInfo);
        }
        trxLogListError.add(xxTrxLogError);
        bizUtil.createTrxLog(trxLogListError);
        throw restErrorUtil.createRESTException(excp.getMessage());
    } finally {
        RangerPerfTracer.log(perf);
        List<XXTrxLog> trxLogListEnd = new ArrayList<XXTrxLog>();
        XXTrxLog xxTrxLogEnd = new XXTrxLog();
        xxTrxLogEnd.setAction("IMPORT END");
        xxTrxLogEnd.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
        if (StringUtils.isNotEmpty(metaDataInfo)) {
            xxTrxLogEnd.setPreviousValue(metaDataInfo);
        }
        trxLogListEnd.add(xxTrxLogEnd);
        bizUtil.createTrxLog(trxLogListEnd);
        if (LOG.isDebugEnabled()) {
            LOG.debug("<== ServiceREST.importPoliciesFromFile()");
        }
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) RangerExportPolicyList(org.apache.ranger.view.RangerExportPolicyList) ArrayList(java.util.ArrayList) Gson(com.google.gson.Gson) SearchFilter(org.apache.ranger.plugin.util.SearchFilter) VXString(org.apache.ranger.view.VXString) LinkedHashMap(java.util.LinkedHashMap) RangerPolicy(org.apache.ranger.plugin.model.RangerPolicy) RangerService(org.apache.ranger.plugin.model.RangerService) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) RangerPerfTracer(org.apache.ranger.plugin.util.RangerPerfTracer) XXTrxLog(org.apache.ranger.entity.XXTrxLog) IOException(java.io.IOException) JsonSyntaxException(com.google.gson.JsonSyntaxException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize)

Aggregations

XXTrxLog (org.apache.ranger.entity.XXTrxLog)38 ArrayList (java.util.ArrayList)21 VXString (org.apache.ranger.view.VXString)13 Field (java.lang.reflect.Field)12 RangerPolicy (org.apache.ranger.plugin.model.RangerPolicy)12 RangerService (org.apache.ranger.plugin.model.RangerService)12 VTrxLogAttr (org.apache.ranger.common.view.VTrxLogAttr)10 XXUser (org.apache.ranger.entity.XXUser)9 SearchField (org.apache.ranger.common.SearchField)7 XXPortalUser (org.apache.ranger.entity.XXPortalUser)7 IOException (java.io.IOException)6 UnknownHostException (java.net.UnknownHostException)5 XXPolicy (org.apache.ranger.entity.XXPolicy)5 RangerDataMaskPolicyItem (org.apache.ranger.plugin.model.RangerPolicy.RangerDataMaskPolicyItem)5 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 XXGroup (org.apache.ranger.entity.XXGroup)4 XXService (org.apache.ranger.entity.XXService)4 XXServiceConfigMap (org.apache.ranger.entity.XXServiceConfigMap)4