Java Code Examples for org.apache.ranger.plugin.util.ServicePolicies#getPolicyVersion()

The following examples show how to use org.apache.ranger.plugin.util.ServicePolicies#getPolicyVersion() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ServiceREST.java    From ranger with Apache License 2.0 4 votes vote down vote up
@GET
@Path("/policies/download/{serviceName}")
@Produces({ "application/json", "application/xml" })
public ServicePolicies getServicePoliciesIfUpdated(
		@PathParam("serviceName") String serviceName,
		@QueryParam("lastKnownVersion") Long lastKnownVersion,
		@DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime,
		@QueryParam("pluginId") String pluginId,
		@DefaultValue("") @QueryParam("clusterName") String clusterName,
		@DefaultValue("") @QueryParam("zoneName") String zoneName,
		@DefaultValue("false") @QueryParam("supportsPolicyDeltas") Boolean supportsPolicyDeltas,
		@DefaultValue("") @QueryParam("pluginCapabilities") String pluginCapabilities,
		@Context HttpServletRequest request) throws Exception {
	if (LOG.isDebugEnabled()) {
		LOG.debug("==> ServiceREST.getServicePoliciesIfUpdated("
				+ serviceName + ", " + lastKnownVersion + ", "
				+ lastActivationTime + ", " + pluginId + ", "
				+ clusterName + ", " + supportsPolicyDeltas + ")");
	}

	ServicePolicies ret      = null;
	int             httpCode = HttpServletResponse.SC_OK;
	String          logMsg   = null;
	RangerPerfTracer perf    = null;
	Long downloadedVersion   = null;
	boolean isValid          = false;

	try {
		bizUtil.failUnauthenticatedIfNotAllowed();

		isValid = serviceUtil.isValidateHttpsAuthentication(serviceName, request);
	} catch (WebApplicationException webException) {
		httpCode = webException.getResponse().getStatus();
		logMsg = webException.getResponse().getEntity().toString();
	} catch (Exception e) {
		httpCode = HttpServletResponse.SC_BAD_REQUEST;
		logMsg = e.getMessage();
	}
	if (isValid) {
		if (lastKnownVersion == null) {
			lastKnownVersion = Long.valueOf(-1);
		}

		try {
			if(RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
				perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePoliciesIfUpdated(serviceName=" + serviceName + ",lastKnownVersion=" + lastKnownVersion + ",lastActivationTime=" + lastActivationTime + ")");
			}
			ServicePolicies servicePolicies = svcStore.getServicePoliciesIfUpdated(serviceName, lastKnownVersion, !supportsPolicyDeltas);

			if (servicePolicies == null) {
				downloadedVersion = lastKnownVersion;
				httpCode = HttpServletResponse.SC_NOT_MODIFIED;
				logMsg = "No change since last update";
			} else {
				Map<String, RangerSecurityZone.RangerSecurityZoneService> securityZones = zoneStore.getSecurityZonesForService(serviceName);
				ServicePolicies updatedServicePolicies = servicePolicies;
				if (MapUtils.isNotEmpty(securityZones)) {
					updatedServicePolicies = RangerPolicyAdminCache.getUpdatedServicePoliciesForZones(servicePolicies, securityZones);
					patchAssociatedTagServiceInSecurityZoneInfos(updatedServicePolicies);
				}
				downloadedVersion = updatedServicePolicies.getPolicyVersion();
				if (lastKnownVersion == -1L || !supportsPolicyDeltas) {
					ret = filterServicePolicies(updatedServicePolicies);
				} else {
					ret = updatedServicePolicies;
				}
				ret.setServiceConfig(svcStore.getServiceConfigForPlugin(ret.getServiceId()));
				httpCode = HttpServletResponse.SC_OK;
				logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : (ret.getPolicyDeltas() != null ? ret.getPolicyDeltas().size() : 0)) + " policies. Policy version=" + ret.getPolicyVersion();
			}
		} catch (Throwable excp) {
			LOG.error("getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ") failed", excp);

			httpCode = HttpServletResponse.SC_BAD_REQUEST;
			logMsg = excp.getMessage();
		} finally {
			createPolicyDownloadAudit(serviceName, lastKnownVersion, pluginId, httpCode, clusterName, zoneName, request);
			RangerPerfTracer.log(perf);
		}
	}
	assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_POLICIES, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode, clusterName, pluginCapabilities);

	if(httpCode != HttpServletResponse.SC_OK) {
		boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED;
		throw restErrorUtil.createRESTException(httpCode, logMsg, logError);
	}

	if(LOG.isDebugEnabled()) {
		LOG.debug("<== ServiceREST.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ", " + pluginId + ", " + clusterName + ", " + supportsPolicyDeltas + "): count=" + ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size()));
	}

	return ret;
}
 
Example 2
Source File: RangerPolicyAdminCache.java    From ranger with Apache License 2.0 4 votes vote down vote up
final RangerPolicyAdmin getServicePoliciesAdmin(String serviceName, ServiceStore svcStore, RoleStore roleStore, SecurityZoneStore zoneStore, RangerPolicyEngineOptions options) {
	RangerPolicyAdmin ret = null;

	if (serviceName == null || svcStore == null || roleStore == null || zoneStore == null) {
		LOG.warn("Cannot get policy-admin for null serviceName or serviceStore or roleStore or zoneStore");

		return ret;
	}

	ret = policyAdminCache.get(serviceName);

	long        policyVersion;
	long        roleVersion;
	RangerRoles roles;
	boolean     isRolesUpdated = true;

	try {
		if (ret == null) {
			policyVersion = -1L;
			roleVersion   = -1L;
			roles         = roleStore.getRoles(serviceName, roleVersion);

			if (roles == null) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("There are no roles in ranger-admin for service:" + serviceName + "]");
				}
			}
		} else {
			policyVersion = ret.getPolicyVersion();
			roleVersion   = ret.getRoleVersion();
			roles         = roleStore.getRoles(serviceName, roleVersion);

			if (roles == null) { // No changes to roles
				roles          = roleStore.getRoles(serviceName, -1L);
				isRolesUpdated = false;
			}
		}

		ServicePolicies policies = svcStore.getServicePoliciesIfUpdated(serviceName, policyVersion, false);

		if (policies != null) {
			if (policies.getPolicyVersion() != null && !policies.getPolicyVersion().equals(policyVersion)) {
				ServicePolicies updatedServicePolicies = getUpdatedServicePolicies(serviceName, policies, svcStore, zoneStore);

				ret = addOrUpdatePolicyAdmin(ret, updatedServicePolicies, roles, options);
			} else {
				LOG.error("policies object is null or its version is null for getPolicyAdmin(" + serviceName + ") !!");
				LOG.error("Returning old policy admin");
			}
		} else {
			if (ret == null) {
				LOG.error("getPolicyAdmin(" + serviceName + "): failed to get any policies from service-store");
			} else {
				if (isRolesUpdated) {
					ret.setRoles(roles);
				}
			}
		}
	} catch (Exception excp) {
		LOG.error("getPolicyAdmin(" + serviceName + "): failed to get latest policies from service-store", excp);
	}
	if (ret == null) {
		LOG.error("Policy-engine is not built! Returning null policy-engine!");
	}

	return ret;
}
 
Example 3
Source File: RangerPolicyRepository.java    From ranger with Apache License 2.0 4 votes vote down vote up
RangerPolicyRepository(ServicePolicies servicePolicies, RangerPluginContext pluginContext, String zoneName) {
    super();

    this.componentServiceName = this.serviceName = servicePolicies.getServiceName();
    this.componentServiceDef  = this.serviceDef = ServiceDefUtil.normalize(servicePolicies.getServiceDef());
    this.zoneName             = zoneName;
    this.appId                = pluginContext.getConfig().getAppId();
    this.options              = new RangerPolicyEngineOptions(pluginContext.getConfig().getPolicyEngineOptions());
    this.pluginContext        = pluginContext;

    if (StringUtils.isEmpty(zoneName)) {
        this.policies = Collections.unmodifiableList(servicePolicies.getPolicies());
    } else {
        this.policies = Collections.unmodifiableList(servicePolicies.getSecurityZones().get(zoneName).getPolicies());
    }
    this.policyVersion = servicePolicies.getPolicyVersion() != null ? servicePolicies.getPolicyVersion() : -1;

    String auditMode = servicePolicies.getAuditMode();

    if (StringUtils.equals(auditMode, RangerPolicyEngine.AUDIT_ALL)) {
        auditModeEnum = AuditModeEnum.AUDIT_ALL;
    } else if (StringUtils.equals(auditMode, RangerPolicyEngine.AUDIT_NONE)) {
        auditModeEnum = AuditModeEnum.AUDIT_NONE;
    } else {
        auditModeEnum = AuditModeEnum.AUDIT_DEFAULT;
    }

    if (auditModeEnum == AuditModeEnum.AUDIT_DEFAULT) {
        String propertyName = "ranger.plugin." + serviceName + ".policyengine.auditcachesize";

        if (options.cacheAuditResults) {
            final int RANGER_POLICYENGINE_AUDITRESULT_CACHE_SIZE = 64 * 1024;

            int auditResultCacheSize = pluginContext.getConfig().getInt(propertyName, RANGER_POLICYENGINE_AUDITRESULT_CACHE_SIZE);
            accessAuditCache = Collections.synchronizedMap(new CacheMap<String, AuditInfo>(auditResultCacheSize));
        } else {
            accessAuditCache = null;
        }
    } else {
        this.accessAuditCache = null;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("RangerPolicyRepository : building policy-repository for service[" + serviceName + "], and zone:[" + zoneName + "] with auditMode[" + auditModeEnum + "]");
    }

    init(options);

    if (StringUtils.isEmpty(zoneName)) {
        this.contextEnrichers = Collections.unmodifiableList(buildContextEnrichers(options));
    } else {
        this.contextEnrichers = null;
    }

    if (options.disableTrieLookupPrefilter) {
        policyResourceTrie    = null;
        dataMaskResourceTrie  = null;
        rowFilterResourceTrie = null;
    } else {
        policyResourceTrie    = createResourceTrieMap(policyEvaluators, options.optimizeTrieForRetrieval);
        dataMaskResourceTrie  = createResourceTrieMap(dataMaskPolicyEvaluators, options.optimizeTrieForRetrieval);
        rowFilterResourceTrie = createResourceTrieMap(rowFilterPolicyEvaluators, options.optimizeTrieForRetrieval);
    }
}